xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 86ecf0b4)
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 2008 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
78 #define	SD_MODULE_NAME	"SCSI Disk Driver"
79 char _depends_on[]	= "misc/scsi misc/cmlb";
80 #endif
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 /*
359  * Vendor specific data name property declarations
360  */
361 
362 #if defined(__fibre) || defined(__i386) ||defined(__amd64)
363 
364 static sd_tunables seagate_properties = {
365 	SEAGATE_THROTTLE_VALUE,
366 	0,
367 	0,
368 	0,
369 	0,
370 	0,
371 	0,
372 	0,
373 	0
374 };
375 
376 
377 static sd_tunables fujitsu_properties = {
378 	FUJITSU_THROTTLE_VALUE,
379 	0,
380 	0,
381 	0,
382 	0,
383 	0,
384 	0,
385 	0,
386 	0
387 };
388 
389 static sd_tunables ibm_properties = {
390 	IBM_THROTTLE_VALUE,
391 	0,
392 	0,
393 	0,
394 	0,
395 	0,
396 	0,
397 	0,
398 	0
399 };
400 
401 static sd_tunables purple_properties = {
402 	PURPLE_THROTTLE_VALUE,
403 	0,
404 	0,
405 	PURPLE_BUSY_RETRIES,
406 	PURPLE_RESET_RETRY_COUNT,
407 	PURPLE_RESERVE_RELEASE_TIME,
408 	0,
409 	0,
410 	0
411 };
412 
413 static sd_tunables sve_properties = {
414 	SVE_THROTTLE_VALUE,
415 	0,
416 	0,
417 	SVE_BUSY_RETRIES,
418 	SVE_RESET_RETRY_COUNT,
419 	SVE_RESERVE_RELEASE_TIME,
420 	SVE_MIN_THROTTLE_VALUE,
421 	SVE_DISKSORT_DISABLED_FLAG,
422 	0
423 };
424 
425 static sd_tunables maserati_properties = {
426 	0,
427 	0,
428 	0,
429 	0,
430 	0,
431 	0,
432 	0,
433 	MASERATI_DISKSORT_DISABLED_FLAG,
434 	MASERATI_LUN_RESET_ENABLED_FLAG
435 };
436 
437 static sd_tunables pirus_properties = {
438 	PIRUS_THROTTLE_VALUE,
439 	0,
440 	PIRUS_NRR_COUNT,
441 	PIRUS_BUSY_RETRIES,
442 	PIRUS_RESET_RETRY_COUNT,
443 	0,
444 	PIRUS_MIN_THROTTLE_VALUE,
445 	PIRUS_DISKSORT_DISABLED_FLAG,
446 	PIRUS_LUN_RESET_ENABLED_FLAG
447 };
448 
449 #endif
450 
451 #if (defined(__sparc) && !defined(__fibre)) || \
452 	(defined(__i386) || defined(__amd64))
453 
454 
455 static sd_tunables elite_properties = {
456 	ELITE_THROTTLE_VALUE,
457 	0,
458 	0,
459 	0,
460 	0,
461 	0,
462 	0,
463 	0,
464 	0
465 };
466 
467 static sd_tunables st31200n_properties = {
468 	ST31200N_THROTTLE_VALUE,
469 	0,
470 	0,
471 	0,
472 	0,
473 	0,
474 	0,
475 	0,
476 	0
477 };
478 
479 #endif /* Fibre or not */
480 
481 static sd_tunables lsi_properties_scsi = {
482 	LSI_THROTTLE_VALUE,
483 	0,
484 	LSI_NOTREADY_RETRIES,
485 	0,
486 	0,
487 	0,
488 	0,
489 	0,
490 	0
491 };
492 
493 static sd_tunables symbios_properties = {
494 	SYMBIOS_THROTTLE_VALUE,
495 	0,
496 	SYMBIOS_NOTREADY_RETRIES,
497 	0,
498 	0,
499 	0,
500 	0,
501 	0,
502 	0
503 };
504 
505 static sd_tunables lsi_properties = {
506 	0,
507 	0,
508 	LSI_NOTREADY_RETRIES,
509 	0,
510 	0,
511 	0,
512 	0,
513 	0,
514 	0
515 };
516 
517 static sd_tunables lsi_oem_properties = {
518 	0,
519 	0,
520 	LSI_OEM_NOTREADY_RETRIES,
521 	0,
522 	0,
523 	0,
524 	0,
525 	0,
526 	0,
527 	1
528 };
529 
530 
531 
532 #if (defined(SD_PROP_TST))
533 
534 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
535 #define	SD_TST_THROTTLE_VAL	16
536 #define	SD_TST_NOTREADY_VAL	12
537 #define	SD_TST_BUSY_VAL		60
538 #define	SD_TST_RST_RETRY_VAL	36
539 #define	SD_TST_RSV_REL_TIME	60
540 
541 static sd_tunables tst_properties = {
542 	SD_TST_THROTTLE_VAL,
543 	SD_TST_CTYPE_VAL,
544 	SD_TST_NOTREADY_VAL,
545 	SD_TST_BUSY_VAL,
546 	SD_TST_RST_RETRY_VAL,
547 	SD_TST_RSV_REL_TIME,
548 	0,
549 	0,
550 	0
551 };
552 #endif
553 
554 /* This is similar to the ANSI toupper implementation */
555 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
556 
557 /*
558  * Static Driver Configuration Table
559  *
560  * This is the table of disks which need throttle adjustment (or, perhaps
561  * something else as defined by the flags at a future time.)  device_id
562  * is a string consisting of concatenated vid (vendor), pid (product/model)
563  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
564  * the parts of the string are as defined by the sizes in the scsi_inquiry
565  * structure.  Device type is searched as far as the device_id string is
566  * defined.  Flags defines which values are to be set in the driver from the
567  * properties list.
568  *
569  * Entries below which begin and end with a "*" are a special case.
570  * These do not have a specific vendor, and the string which follows
571  * can appear anywhere in the 16 byte PID portion of the inquiry data.
572  *
573  * Entries below which begin and end with a " " (blank) are a special
574  * case. The comparison function will treat multiple consecutive blanks
575  * as equivalent to a single blank. For example, this causes a
576  * sd_disk_table entry of " NEC CDROM " to match a device's id string
577  * of  "NEC       CDROM".
578  *
579  * Note: The MD21 controller type has been obsoleted.
580  *	 ST318202F is a Legacy device
581  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
582  *	 made with an FC connection. The entries here are a legacy.
583  */
584 static sd_disk_config_t sd_disk_table[] = {
585 #if defined(__fibre) || defined(__i386) || defined(__amd64)
586 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
587 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
588 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
589 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
590 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
591 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
592 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
593 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
594 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
595 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
596 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
597 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
598 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
599 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
600 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
601 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
602 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
603 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
604 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
605 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
606 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
607 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
608 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
609 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
610 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
611 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
612 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
613 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
614 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
615 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
616 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
617 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
618 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
619 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
620 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
621 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
622 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
623 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
624 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
625 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
626 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
627 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
628 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
629 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
630 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
631 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
632 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
633 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
634 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
635 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
636 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
637 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
638 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
639 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
640 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
641 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
642 			SD_CONF_BSET_BSY_RETRY_COUNT|
643 			SD_CONF_BSET_RST_RETRIES|
644 			SD_CONF_BSET_RSV_REL_TIME,
645 		&purple_properties },
646 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
647 		SD_CONF_BSET_BSY_RETRY_COUNT|
648 		SD_CONF_BSET_RST_RETRIES|
649 		SD_CONF_BSET_RSV_REL_TIME|
650 		SD_CONF_BSET_MIN_THROTTLE|
651 		SD_CONF_BSET_DISKSORT_DISABLED,
652 		&sve_properties },
653 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
654 			SD_CONF_BSET_BSY_RETRY_COUNT|
655 			SD_CONF_BSET_RST_RETRIES|
656 			SD_CONF_BSET_RSV_REL_TIME,
657 		&purple_properties },
658 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
659 		SD_CONF_BSET_LUN_RESET_ENABLED,
660 		&maserati_properties },
661 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
662 		SD_CONF_BSET_NRR_COUNT|
663 		SD_CONF_BSET_BSY_RETRY_COUNT|
664 		SD_CONF_BSET_RST_RETRIES|
665 		SD_CONF_BSET_MIN_THROTTLE|
666 		SD_CONF_BSET_DISKSORT_DISABLED|
667 		SD_CONF_BSET_LUN_RESET_ENABLED,
668 		&pirus_properties },
669 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
670 		SD_CONF_BSET_NRR_COUNT|
671 		SD_CONF_BSET_BSY_RETRY_COUNT|
672 		SD_CONF_BSET_RST_RETRIES|
673 		SD_CONF_BSET_MIN_THROTTLE|
674 		SD_CONF_BSET_DISKSORT_DISABLED|
675 		SD_CONF_BSET_LUN_RESET_ENABLED,
676 		&pirus_properties },
677 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
678 		SD_CONF_BSET_NRR_COUNT|
679 		SD_CONF_BSET_BSY_RETRY_COUNT|
680 		SD_CONF_BSET_RST_RETRIES|
681 		SD_CONF_BSET_MIN_THROTTLE|
682 		SD_CONF_BSET_DISKSORT_DISABLED|
683 		SD_CONF_BSET_LUN_RESET_ENABLED,
684 		&pirus_properties },
685 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
686 		SD_CONF_BSET_NRR_COUNT|
687 		SD_CONF_BSET_BSY_RETRY_COUNT|
688 		SD_CONF_BSET_RST_RETRIES|
689 		SD_CONF_BSET_MIN_THROTTLE|
690 		SD_CONF_BSET_DISKSORT_DISABLED|
691 		SD_CONF_BSET_LUN_RESET_ENABLED,
692 		&pirus_properties },
693 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
694 		SD_CONF_BSET_NRR_COUNT|
695 		SD_CONF_BSET_BSY_RETRY_COUNT|
696 		SD_CONF_BSET_RST_RETRIES|
697 		SD_CONF_BSET_MIN_THROTTLE|
698 		SD_CONF_BSET_DISKSORT_DISABLED|
699 		SD_CONF_BSET_LUN_RESET_ENABLED,
700 		&pirus_properties },
701 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
702 		SD_CONF_BSET_NRR_COUNT|
703 		SD_CONF_BSET_BSY_RETRY_COUNT|
704 		SD_CONF_BSET_RST_RETRIES|
705 		SD_CONF_BSET_MIN_THROTTLE|
706 		SD_CONF_BSET_DISKSORT_DISABLED|
707 		SD_CONF_BSET_LUN_RESET_ENABLED,
708 		&pirus_properties },
709 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
710 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
711 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
712 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
713 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
714 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
715 #endif /* fibre or NON-sparc platforms */
716 #if ((defined(__sparc) && !defined(__fibre)) ||\
717 	(defined(__i386) || defined(__amd64)))
718 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
719 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
720 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
721 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
722 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
723 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
724 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
725 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
726 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
727 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
728 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
729 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
730 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
731 	    &symbios_properties },
732 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
733 	    &lsi_properties_scsi },
734 #if defined(__i386) || defined(__amd64)
735 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
736 				    | SD_CONF_BSET_READSUB_BCD
737 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
738 				    | SD_CONF_BSET_NO_READ_HEADER
739 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
740 
741 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
742 				    | SD_CONF_BSET_READSUB_BCD
743 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
744 				    | SD_CONF_BSET_NO_READ_HEADER
745 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
746 #endif /* __i386 || __amd64 */
747 #endif /* sparc NON-fibre or NON-sparc platforms */
748 
749 #if (defined(SD_PROP_TST))
750 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
751 				| SD_CONF_BSET_CTYPE
752 				| SD_CONF_BSET_NRR_COUNT
753 				| SD_CONF_BSET_FAB_DEVID
754 				| SD_CONF_BSET_NOCACHE
755 				| SD_CONF_BSET_BSY_RETRY_COUNT
756 				| SD_CONF_BSET_PLAYMSF_BCD
757 				| SD_CONF_BSET_READSUB_BCD
758 				| SD_CONF_BSET_READ_TOC_TRK_BCD
759 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
760 				| SD_CONF_BSET_NO_READ_HEADER
761 				| SD_CONF_BSET_READ_CD_XD4
762 				| SD_CONF_BSET_RST_RETRIES
763 				| SD_CONF_BSET_RSV_REL_TIME
764 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
765 #endif
766 };
767 
768 static const int sd_disk_table_size =
769 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
770 
771 
772 
773 #define	SD_INTERCONNECT_PARALLEL	0
774 #define	SD_INTERCONNECT_FABRIC		1
775 #define	SD_INTERCONNECT_FIBRE		2
776 #define	SD_INTERCONNECT_SSA		3
777 #define	SD_INTERCONNECT_SATA		4
778 #define	SD_IS_PARALLEL_SCSI(un)		\
779 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
780 #define	SD_IS_SERIAL(un)		\
781 	((un)->un_interconnect_type == SD_INTERCONNECT_SATA)
782 
783 /*
784  * Definitions used by device id registration routines
785  */
786 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
787 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
788 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
789 
790 static kmutex_t sd_sense_mutex = {0};
791 
792 /*
793  * Macros for updates of the driver state
794  */
795 #define	New_state(un, s)        \
796 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
797 #define	Restore_state(un)	\
798 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
799 
800 static struct sd_cdbinfo sd_cdbtab[] = {
801 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
802 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
803 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
804 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
805 };
806 
807 /*
808  * Specifies the number of seconds that must have elapsed since the last
809  * cmd. has completed for a device to be declared idle to the PM framework.
810  */
811 static int sd_pm_idletime = 1;
812 
813 /*
814  * Internal function prototypes
815  */
816 
817 #if (defined(__fibre))
818 /*
819  * These #defines are to avoid namespace collisions that occur because this
820  * code is currently used to compile two separate driver modules: sd and ssd.
821  * All function names need to be treated this way (even if declared static)
822  * in order to allow the debugger to resolve the names properly.
823  * It is anticipated that in the near future the ssd module will be obsoleted,
824  * at which time this ugliness should go away.
825  */
826 #define	sd_log_trace			ssd_log_trace
827 #define	sd_log_info			ssd_log_info
828 #define	sd_log_err			ssd_log_err
829 #define	sdprobe				ssdprobe
830 #define	sdinfo				ssdinfo
831 #define	sd_prop_op			ssd_prop_op
832 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
833 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
834 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
835 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
836 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
837 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
838 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
839 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
840 #define	sd_spin_up_unit			ssd_spin_up_unit
841 #define	sd_enable_descr_sense		ssd_enable_descr_sense
842 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
843 #define	sd_set_mmc_caps			ssd_set_mmc_caps
844 #define	sd_read_unit_properties		ssd_read_unit_properties
845 #define	sd_process_sdconf_file		ssd_process_sdconf_file
846 #define	sd_process_sdconf_table		ssd_process_sdconf_table
847 #define	sd_sdconf_id_match		ssd_sdconf_id_match
848 #define	sd_blank_cmp			ssd_blank_cmp
849 #define	sd_chk_vers1_data		ssd_chk_vers1_data
850 #define	sd_set_vers1_properties		ssd_set_vers1_properties
851 
852 #define	sd_get_physical_geometry	ssd_get_physical_geometry
853 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
854 #define	sd_update_block_info		ssd_update_block_info
855 #define	sd_register_devid		ssd_register_devid
856 #define	sd_get_devid			ssd_get_devid
857 #define	sd_create_devid			ssd_create_devid
858 #define	sd_write_deviceid		ssd_write_deviceid
859 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
860 #define	sd_setup_pm			ssd_setup_pm
861 #define	sd_create_pm_components		ssd_create_pm_components
862 #define	sd_ddi_suspend			ssd_ddi_suspend
863 #define	sd_ddi_pm_suspend		ssd_ddi_pm_suspend
864 #define	sd_ddi_resume			ssd_ddi_resume
865 #define	sd_ddi_pm_resume		ssd_ddi_pm_resume
866 #define	sdpower				ssdpower
867 #define	sdattach			ssdattach
868 #define	sddetach			ssddetach
869 #define	sd_unit_attach			ssd_unit_attach
870 #define	sd_unit_detach			ssd_unit_detach
871 #define	sd_set_unit_attributes		ssd_set_unit_attributes
872 #define	sd_create_errstats		ssd_create_errstats
873 #define	sd_set_errstats			ssd_set_errstats
874 #define	sd_set_pstats			ssd_set_pstats
875 #define	sddump				ssddump
876 #define	sd_scsi_poll			ssd_scsi_poll
877 #define	sd_send_polled_RQS		ssd_send_polled_RQS
878 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
879 #define	sd_init_event_callbacks		ssd_init_event_callbacks
880 #define	sd_event_callback		ssd_event_callback
881 #define	sd_cache_control		ssd_cache_control
882 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
883 #define	sd_get_nv_sup			ssd_get_nv_sup
884 #define	sd_make_device			ssd_make_device
885 #define	sdopen				ssdopen
886 #define	sdclose				ssdclose
887 #define	sd_ready_and_valid		ssd_ready_and_valid
888 #define	sdmin				ssdmin
889 #define	sdread				ssdread
890 #define	sdwrite				ssdwrite
891 #define	sdaread				ssdaread
892 #define	sdawrite			ssdawrite
893 #define	sdstrategy			ssdstrategy
894 #define	sdioctl				ssdioctl
895 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
896 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
897 #define	sd_checksum_iostart		ssd_checksum_iostart
898 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
899 #define	sd_pm_iostart			ssd_pm_iostart
900 #define	sd_core_iostart			ssd_core_iostart
901 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
902 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
903 #define	sd_checksum_iodone		ssd_checksum_iodone
904 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
905 #define	sd_pm_iodone			ssd_pm_iodone
906 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
907 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
908 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
909 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
910 #define	sd_buf_iodone			ssd_buf_iodone
911 #define	sd_uscsi_strategy		ssd_uscsi_strategy
912 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
913 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
914 #define	sd_uscsi_iodone			ssd_uscsi_iodone
915 #define	sd_xbuf_strategy		ssd_xbuf_strategy
916 #define	sd_xbuf_init			ssd_xbuf_init
917 #define	sd_pm_entry			ssd_pm_entry
918 #define	sd_pm_exit			ssd_pm_exit
919 
920 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
921 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
922 
923 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
924 #define	sdintr				ssdintr
925 #define	sd_start_cmds			ssd_start_cmds
926 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
927 #define	sd_bioclone_alloc		ssd_bioclone_alloc
928 #define	sd_bioclone_free		ssd_bioclone_free
929 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
930 #define	sd_shadow_buf_free		ssd_shadow_buf_free
931 #define	sd_print_transport_rejected_message	\
932 					ssd_print_transport_rejected_message
933 #define	sd_retry_command		ssd_retry_command
934 #define	sd_set_retry_bp			ssd_set_retry_bp
935 #define	sd_send_request_sense_command	ssd_send_request_sense_command
936 #define	sd_start_retry_command		ssd_start_retry_command
937 #define	sd_start_direct_priority_command	\
938 					ssd_start_direct_priority_command
939 #define	sd_return_failed_command	ssd_return_failed_command
940 #define	sd_return_failed_command_no_restart	\
941 					ssd_return_failed_command_no_restart
942 #define	sd_return_command		ssd_return_command
943 #define	sd_sync_with_callback		ssd_sync_with_callback
944 #define	sdrunout			ssdrunout
945 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
946 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
947 #define	sd_reduce_throttle		ssd_reduce_throttle
948 #define	sd_restore_throttle		ssd_restore_throttle
949 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
950 #define	sd_init_cdb_limits		ssd_init_cdb_limits
951 #define	sd_pkt_status_good		ssd_pkt_status_good
952 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
953 #define	sd_pkt_status_busy		ssd_pkt_status_busy
954 #define	sd_pkt_status_reservation_conflict	\
955 					ssd_pkt_status_reservation_conflict
956 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
957 #define	sd_handle_request_sense		ssd_handle_request_sense
958 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
959 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
960 #define	sd_validate_sense_data		ssd_validate_sense_data
961 #define	sd_decode_sense			ssd_decode_sense
962 #define	sd_print_sense_msg		ssd_print_sense_msg
963 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
964 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
965 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
966 #define	sd_sense_key_medium_or_hardware_error	\
967 					ssd_sense_key_medium_or_hardware_error
968 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
969 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
970 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
971 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
972 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
973 #define	sd_sense_key_default		ssd_sense_key_default
974 #define	sd_print_retry_msg		ssd_print_retry_msg
975 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
976 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
977 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
978 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
979 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
980 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
981 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
982 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
983 #define	sd_pkt_reason_default		ssd_pkt_reason_default
984 #define	sd_reset_target			ssd_reset_target
985 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
986 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
987 #define	sd_taskq_create			ssd_taskq_create
988 #define	sd_taskq_delete			ssd_taskq_delete
989 #define	sd_target_change_task		ssd_target_change_task
990 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
991 #define	sd_media_change_task		ssd_media_change_task
992 #define	sd_handle_mchange		ssd_handle_mchange
993 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
994 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
995 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
996 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
997 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
998 					sd_send_scsi_feature_GET_CONFIGURATION
999 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
1000 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
1001 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
1002 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
1003 					ssd_send_scsi_PERSISTENT_RESERVE_IN
1004 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
1005 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
1006 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
1007 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
1008 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1009 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1010 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1011 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1012 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1013 #define	sd_alloc_rqs			ssd_alloc_rqs
1014 #define	sd_free_rqs			ssd_free_rqs
1015 #define	sd_dump_memory			ssd_dump_memory
1016 #define	sd_get_media_info		ssd_get_media_info
1017 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1018 #define	sd_nvpair_str_decode		ssd_nvpair_str_decode
1019 #define	sd_strtok_r			ssd_strtok_r
1020 #define	sd_set_properties		ssd_set_properties
1021 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1022 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1023 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1024 #define	sd_check_mhd			ssd_check_mhd
1025 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1026 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1027 #define	sd_sname			ssd_sname
1028 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1029 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1030 #define	sd_take_ownership		ssd_take_ownership
1031 #define	sd_reserve_release		ssd_reserve_release
1032 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1033 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1034 #define	sd_persistent_reservation_in_read_keys	\
1035 					ssd_persistent_reservation_in_read_keys
1036 #define	sd_persistent_reservation_in_read_resv	\
1037 					ssd_persistent_reservation_in_read_resv
1038 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1039 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1040 #define	sd_mhdioc_release		ssd_mhdioc_release
1041 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1042 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1043 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1044 #define	sr_change_blkmode		ssr_change_blkmode
1045 #define	sr_change_speed			ssr_change_speed
1046 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1047 #define	sr_pause_resume			ssr_pause_resume
1048 #define	sr_play_msf			ssr_play_msf
1049 #define	sr_play_trkind			ssr_play_trkind
1050 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1051 #define	sr_read_subchannel		ssr_read_subchannel
1052 #define	sr_read_tocentry		ssr_read_tocentry
1053 #define	sr_read_tochdr			ssr_read_tochdr
1054 #define	sr_read_cdda			ssr_read_cdda
1055 #define	sr_read_cdxa			ssr_read_cdxa
1056 #define	sr_read_mode1			ssr_read_mode1
1057 #define	sr_read_mode2			ssr_read_mode2
1058 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1059 #define	sr_sector_mode			ssr_sector_mode
1060 #define	sr_eject			ssr_eject
1061 #define	sr_ejected			ssr_ejected
1062 #define	sr_check_wp			ssr_check_wp
1063 #define	sd_check_media			ssd_check_media
1064 #define	sd_media_watch_cb		ssd_media_watch_cb
1065 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1066 #define	sr_volume_ctrl			ssr_volume_ctrl
1067 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1068 #define	sd_log_page_supported		ssd_log_page_supported
1069 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1070 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1071 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1072 #define	sd_range_lock			ssd_range_lock
1073 #define	sd_get_range			ssd_get_range
1074 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1075 #define	sd_range_unlock			ssd_range_unlock
1076 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1077 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1078 
1079 #define	sd_iostart_chain		ssd_iostart_chain
1080 #define	sd_iodone_chain			ssd_iodone_chain
1081 #define	sd_initpkt_map			ssd_initpkt_map
1082 #define	sd_destroypkt_map		ssd_destroypkt_map
1083 #define	sd_chain_type_map		ssd_chain_type_map
1084 #define	sd_chain_index_map		ssd_chain_index_map
1085 
1086 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1087 #define	sd_failfast_flushq		ssd_failfast_flushq
1088 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1089 
1090 #define	sd_is_lsi			ssd_is_lsi
1091 #define	sd_tg_rdwr			ssd_tg_rdwr
1092 #define	sd_tg_getinfo			ssd_tg_getinfo
1093 
1094 #endif	/* #if (defined(__fibre)) */
1095 
1096 
1097 int _init(void);
1098 int _fini(void);
1099 int _info(struct modinfo *modinfop);
1100 
1101 /*PRINTFLIKE3*/
1102 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1103 /*PRINTFLIKE3*/
1104 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1105 /*PRINTFLIKE3*/
1106 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1107 
1108 static int sdprobe(dev_info_t *devi);
1109 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1110     void **result);
1111 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1112     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1113 
1114 /*
1115  * Smart probe for parallel scsi
1116  */
1117 static void sd_scsi_probe_cache_init(void);
1118 static void sd_scsi_probe_cache_fini(void);
1119 static void sd_scsi_clear_probe_cache(void);
1120 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1121 
1122 /*
1123  * Attached luns on target for parallel scsi
1124  */
1125 static void sd_scsi_target_lun_init(void);
1126 static void sd_scsi_target_lun_fini(void);
1127 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1128 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1129 
1130 static int	sd_spin_up_unit(sd_ssc_t *ssc);
1131 
1132 /*
1133  * Using sd_ssc_init to establish sd_ssc_t struct
1134  * Using sd_ssc_send to send uscsi internal command
1135  * Using sd_ssc_fini to free sd_ssc_t struct
1136  */
1137 static sd_ssc_t *sd_ssc_init(struct sd_lun *un);
1138 static int sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd,
1139     int flag, enum uio_seg dataspace, int path_flag);
1140 static void sd_ssc_fini(sd_ssc_t *ssc);
1141 
1142 /*
1143  * Using sd_ssc_assessment to set correct type-of-assessment
1144  * Using sd_ssc_post to post ereport & system log
1145  *       sd_ssc_post will call sd_ssc_print to print system log
1146  *       sd_ssc_post will call sd_ssd_ereport_post to post ereport
1147  */
1148 static void sd_ssc_assessment(sd_ssc_t *ssc,
1149     enum sd_type_assessment tp_assess);
1150 
1151 static void sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess);
1152 static void sd_ssc_print(sd_ssc_t *ssc, int sd_severity);
1153 static void sd_ssc_ereport_post(sd_ssc_t *ssc,
1154     enum sd_driver_assessment drv_assess);
1155 
1156 /*
1157  * Using sd_ssc_set_info to mark an un-decodable-data error.
1158  * Using sd_ssc_extract_info to transfer information from internal
1159  *       data structures to sd_ssc_t.
1160  */
1161 static void sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp,
1162     const char *fmt, ...);
1163 static void sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un,
1164     struct scsi_pkt *pktp, struct buf *bp, struct sd_xbuf *xp);
1165 
1166 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1167     enum uio_seg dataspace, int path_flag);
1168 
1169 #ifdef _LP64
1170 static void	sd_enable_descr_sense(sd_ssc_t *ssc);
1171 static void	sd_reenable_dsense_task(void *arg);
1172 #endif /* _LP64 */
1173 
1174 static void	sd_set_mmc_caps(sd_ssc_t *ssc);
1175 
1176 static void sd_read_unit_properties(struct sd_lun *un);
1177 static int  sd_process_sdconf_file(struct sd_lun *un);
1178 static void sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str);
1179 static char *sd_strtok_r(char *string, const char *sepset, char **lasts);
1180 static void sd_set_properties(struct sd_lun *un, char *name, char *value);
1181 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1182     int *data_list, sd_tunables *values);
1183 static void sd_process_sdconf_table(struct sd_lun *un);
1184 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1185 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1186 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1187 	int list_len, char *dataname_ptr);
1188 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1189     sd_tunables *prop_list);
1190 
1191 static void sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi,
1192     int reservation_flag);
1193 static int  sd_get_devid(sd_ssc_t *ssc);
1194 static ddi_devid_t sd_create_devid(sd_ssc_t *ssc);
1195 static int  sd_write_deviceid(sd_ssc_t *ssc);
1196 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1197 static int  sd_check_vpd_page_support(sd_ssc_t *ssc);
1198 
1199 static void sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi);
1200 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1201 
1202 static int  sd_ddi_suspend(dev_info_t *devi);
1203 static int  sd_ddi_pm_suspend(struct sd_lun *un);
1204 static int  sd_ddi_resume(dev_info_t *devi);
1205 static int  sd_ddi_pm_resume(struct sd_lun *un);
1206 static int  sdpower(dev_info_t *devi, int component, int level);
1207 
1208 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1209 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1210 static int  sd_unit_attach(dev_info_t *devi);
1211 static int  sd_unit_detach(dev_info_t *devi);
1212 
1213 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1214 static void sd_create_errstats(struct sd_lun *un, int instance);
1215 static void sd_set_errstats(struct sd_lun *un);
1216 static void sd_set_pstats(struct sd_lun *un);
1217 
1218 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1219 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1220 static int  sd_send_polled_RQS(struct sd_lun *un);
1221 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1222 
1223 #if (defined(__fibre))
1224 /*
1225  * Event callbacks (photon)
1226  */
1227 static void sd_init_event_callbacks(struct sd_lun *un);
1228 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1229 #endif
1230 
1231 /*
1232  * Defines for sd_cache_control
1233  */
1234 
1235 #define	SD_CACHE_ENABLE		1
1236 #define	SD_CACHE_DISABLE	0
1237 #define	SD_CACHE_NOCHANGE	-1
1238 
1239 static int   sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag);
1240 static int   sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled);
1241 static void  sd_get_nv_sup(sd_ssc_t *ssc);
1242 static dev_t sd_make_device(dev_info_t *devi);
1243 
1244 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1245 	uint64_t capacity);
1246 
1247 /*
1248  * Driver entry point functions.
1249  */
1250 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1251 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1252 static int  sd_ready_and_valid(sd_ssc_t *ssc, int part);
1253 
1254 static void sdmin(struct buf *bp);
1255 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1256 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1257 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1258 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1259 
1260 static int sdstrategy(struct buf *bp);
1261 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1262 
1263 /*
1264  * Function prototypes for layering functions in the iostart chain.
1265  */
1266 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1267 	struct buf *bp);
1268 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1269 	struct buf *bp);
1270 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1271 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1272 	struct buf *bp);
1273 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1274 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1275 
1276 /*
1277  * Function prototypes for layering functions in the iodone chain.
1278  */
1279 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1280 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1281 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1282 	struct buf *bp);
1283 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1284 	struct buf *bp);
1285 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1286 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1287 	struct buf *bp);
1288 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1289 
1290 /*
1291  * Prototypes for functions to support buf(9S) based IO.
1292  */
1293 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1294 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1295 static void sd_destroypkt_for_buf(struct buf *);
1296 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1297 	struct buf *bp, int flags,
1298 	int (*callback)(caddr_t), caddr_t callback_arg,
1299 	diskaddr_t lba, uint32_t blockcount);
1300 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1301 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1302 
1303 /*
1304  * Prototypes for functions to support USCSI IO.
1305  */
1306 static int sd_uscsi_strategy(struct buf *bp);
1307 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1308 static void sd_destroypkt_for_uscsi(struct buf *);
1309 
1310 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1311 	uchar_t chain_type, void *pktinfop);
1312 
1313 static int  sd_pm_entry(struct sd_lun *un);
1314 static void sd_pm_exit(struct sd_lun *un);
1315 
1316 static void sd_pm_idletimeout_handler(void *arg);
1317 
1318 /*
1319  * sd_core internal functions (used at the sd_core_io layer).
1320  */
1321 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1322 static void sdintr(struct scsi_pkt *pktp);
1323 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1324 
1325 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1326 	enum uio_seg dataspace, int path_flag);
1327 
1328 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1329 	daddr_t blkno, int (*func)(struct buf *));
1330 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1331 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1332 static void sd_bioclone_free(struct buf *bp);
1333 static void sd_shadow_buf_free(struct buf *bp);
1334 
1335 static void sd_print_transport_rejected_message(struct sd_lun *un,
1336 	struct sd_xbuf *xp, int code);
1337 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1338     void *arg, int code);
1339 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1340     void *arg, int code);
1341 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1342     void *arg, int code);
1343 
1344 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1345 	int retry_check_flag,
1346 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1347 		int c),
1348 	void *user_arg, int failure_code,  clock_t retry_delay,
1349 	void (*statp)(kstat_io_t *));
1350 
1351 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1352 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1353 
1354 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1355 	struct scsi_pkt *pktp);
1356 static void sd_start_retry_command(void *arg);
1357 static void sd_start_direct_priority_command(void *arg);
1358 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1359 	int errcode);
1360 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1361 	struct buf *bp, int errcode);
1362 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1363 static void sd_sync_with_callback(struct sd_lun *un);
1364 static int sdrunout(caddr_t arg);
1365 
1366 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1367 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1368 
1369 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1370 static void sd_restore_throttle(void *arg);
1371 
1372 static void sd_init_cdb_limits(struct sd_lun *un);
1373 
1374 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1375 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1376 
1377 /*
1378  * Error handling functions
1379  */
1380 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1381 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1382 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1383 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1384 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1385 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1386 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1387 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1388 
1389 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1390 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1391 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1392 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1393 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1394 	struct sd_xbuf *xp, size_t actual_len);
1395 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1396 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1397 
1398 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1399 	void *arg, int code);
1400 
1401 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1402 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1403 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1404 	uint8_t *sense_datap,
1405 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1406 static void sd_sense_key_not_ready(struct sd_lun *un,
1407 	uint8_t *sense_datap,
1408 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1409 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1410 	uint8_t *sense_datap,
1411 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1412 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1413 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1414 static void sd_sense_key_unit_attention(struct sd_lun *un,
1415 	uint8_t *sense_datap,
1416 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1417 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1418 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1419 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1420 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1421 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1422 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1423 static void sd_sense_key_default(struct sd_lun *un,
1424 	uint8_t *sense_datap,
1425 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1426 
1427 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1428 	void *arg, int flag);
1429 
1430 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1431 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1432 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1433 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1434 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1435 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1436 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1437 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1438 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1439 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1440 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1441 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1442 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1443 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1444 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1445 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1446 
1447 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1448 
1449 static void sd_start_stop_unit_callback(void *arg);
1450 static void sd_start_stop_unit_task(void *arg);
1451 
1452 static void sd_taskq_create(void);
1453 static void sd_taskq_delete(void);
1454 static void sd_target_change_task(void *arg);
1455 static void sd_log_lun_expansion_event(struct sd_lun *un, int km_flag);
1456 static void sd_media_change_task(void *arg);
1457 
1458 static int sd_handle_mchange(struct sd_lun *un);
1459 static int sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag);
1460 static int sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp,
1461 	uint32_t *lbap, int path_flag);
1462 static int sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
1463 	uint32_t *lbap, int path_flag);
1464 static int sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int flag,
1465 	int path_flag);
1466 static int sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr,
1467 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1468 static int sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag);
1469 static int sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc,
1470 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1471 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc,
1472 	uchar_t usr_cmd, uchar_t *usr_bufp);
1473 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1474 	struct dk_callback *dkc);
1475 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1476 static int sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc,
1477 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1478 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1479 static int sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
1480 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1481 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1482 static int sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize,
1483 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1484 static int sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize,
1485 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1486 static int sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
1487 	size_t buflen, daddr_t start_block, int path_flag);
1488 #define	sd_send_scsi_READ(ssc, bufaddr, buflen, start_block, path_flag)	\
1489 	sd_send_scsi_RDWR(ssc, SCMD_READ, bufaddr, buflen, start_block, \
1490 	path_flag)
1491 #define	sd_send_scsi_WRITE(ssc, bufaddr, buflen, start_block, path_flag)\
1492 	sd_send_scsi_RDWR(ssc, SCMD_WRITE, bufaddr, buflen, start_block,\
1493 	path_flag)
1494 
1495 static int sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr,
1496 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1497 	uint16_t param_ptr, int path_flag);
1498 
1499 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1500 static void sd_free_rqs(struct sd_lun *un);
1501 
1502 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1503 	uchar_t *data, int len, int fmt);
1504 static void sd_panic_for_res_conflict(struct sd_lun *un);
1505 
1506 /*
1507  * Disk Ioctl Function Prototypes
1508  */
1509 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1510 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1511 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1512 
1513 /*
1514  * Multi-host Ioctl Prototypes
1515  */
1516 static int sd_check_mhd(dev_t dev, int interval);
1517 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1518 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1519 static char *sd_sname(uchar_t status);
1520 static void sd_mhd_resvd_recover(void *arg);
1521 static void sd_resv_reclaim_thread();
1522 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1523 static int sd_reserve_release(dev_t dev, int cmd);
1524 static void sd_rmv_resv_reclaim_req(dev_t dev);
1525 static void sd_mhd_reset_notify_cb(caddr_t arg);
1526 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1527 	mhioc_inkeys_t *usrp, int flag);
1528 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1529 	mhioc_inresvs_t *usrp, int flag);
1530 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1531 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1532 static int sd_mhdioc_release(dev_t dev);
1533 static int sd_mhdioc_register_devid(dev_t dev);
1534 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1535 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1536 
1537 /*
1538  * SCSI removable prototypes
1539  */
1540 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1541 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1542 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1543 static int sr_pause_resume(dev_t dev, int mode);
1544 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1545 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1546 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1547 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1548 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1549 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1550 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1551 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1552 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1553 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1554 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1555 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1556 static int sr_eject(dev_t dev);
1557 static void sr_ejected(register struct sd_lun *un);
1558 static int sr_check_wp(dev_t dev);
1559 static int sd_check_media(dev_t dev, enum dkio_state state);
1560 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1561 static void sd_delayed_cv_broadcast(void *arg);
1562 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1563 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1564 
1565 static int sd_log_page_supported(sd_ssc_t *ssc, int log_page);
1566 
1567 /*
1568  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1569  */
1570 static void sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag);
1571 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1572 static void sd_wm_cache_destructor(void *wm, void *un);
1573 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1574 	daddr_t endb, ushort_t typ);
1575 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1576 	daddr_t endb);
1577 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1578 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1579 static void sd_read_modify_write_task(void * arg);
1580 static int
1581 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1582 	struct buf **bpp);
1583 
1584 
1585 /*
1586  * Function prototypes for failfast support.
1587  */
1588 static void sd_failfast_flushq(struct sd_lun *un);
1589 static int sd_failfast_flushq_callback(struct buf *bp);
1590 
1591 /*
1592  * Function prototypes to check for lsi devices
1593  */
1594 static void sd_is_lsi(struct sd_lun *un);
1595 
1596 /*
1597  * Function prototypes for partial DMA support
1598  */
1599 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1600 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1601 
1602 
1603 /* Function prototypes for cmlb */
1604 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1605     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1606 
1607 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1608 
1609 /*
1610  * Constants for failfast support:
1611  *
1612  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1613  * failfast processing being performed.
1614  *
1615  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1616  * failfast processing on all bufs with B_FAILFAST set.
1617  */
1618 
1619 #define	SD_FAILFAST_INACTIVE		0
1620 #define	SD_FAILFAST_ACTIVE		1
1621 
1622 /*
1623  * Bitmask to control behavior of buf(9S) flushes when a transition to
1624  * the failfast state occurs. Optional bits include:
1625  *
1626  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1627  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1628  * be flushed.
1629  *
1630  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1631  * driver, in addition to the regular wait queue. This includes the xbuf
1632  * queues. When clear, only the driver's wait queue will be flushed.
1633  */
1634 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1635 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1636 
1637 /*
1638  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1639  * to flush all queues within the driver.
1640  */
1641 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1642 
1643 
1644 /*
1645  * SD Testing Fault Injection
1646  */
1647 #ifdef SD_FAULT_INJECTION
1648 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1649 static void sd_faultinjection(struct scsi_pkt *pktp);
1650 static void sd_injection_log(char *buf, struct sd_lun *un);
1651 #endif
1652 
1653 /*
1654  * Device driver ops vector
1655  */
1656 static struct cb_ops sd_cb_ops = {
1657 	sdopen,			/* open */
1658 	sdclose,		/* close */
1659 	sdstrategy,		/* strategy */
1660 	nodev,			/* print */
1661 	sddump,			/* dump */
1662 	sdread,			/* read */
1663 	sdwrite,		/* write */
1664 	sdioctl,		/* ioctl */
1665 	nodev,			/* devmap */
1666 	nodev,			/* mmap */
1667 	nodev,			/* segmap */
1668 	nochpoll,		/* poll */
1669 	sd_prop_op,		/* cb_prop_op */
1670 	0,			/* streamtab  */
1671 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1672 	CB_REV,			/* cb_rev */
1673 	sdaread, 		/* async I/O read entry point */
1674 	sdawrite		/* async I/O write entry point */
1675 };
1676 
1677 static struct dev_ops sd_ops = {
1678 	DEVO_REV,		/* devo_rev, */
1679 	0,			/* refcnt  */
1680 	sdinfo,			/* info */
1681 	nulldev,		/* identify */
1682 	sdprobe,		/* probe */
1683 	sdattach,		/* attach */
1684 	sddetach,		/* detach */
1685 	nodev,			/* reset */
1686 	&sd_cb_ops,		/* driver operations */
1687 	NULL,			/* bus operations */
1688 	sdpower,		/* power */
1689 	ddi_quiesce_not_needed,		/* quiesce */
1690 };
1691 
1692 
1693 /*
1694  * This is the loadable module wrapper.
1695  */
1696 #include <sys/modctl.h>
1697 
1698 static struct modldrv modldrv = {
1699 	&mod_driverops,		/* Type of module. This one is a driver */
1700 	SD_MODULE_NAME,		/* Module name. */
1701 	&sd_ops			/* driver ops */
1702 };
1703 
1704 
1705 static struct modlinkage modlinkage = {
1706 	MODREV_1,
1707 	&modldrv,
1708 	NULL
1709 };
1710 
1711 static cmlb_tg_ops_t sd_tgops = {
1712 	TG_DK_OPS_VERSION_1,
1713 	sd_tg_rdwr,
1714 	sd_tg_getinfo
1715 	};
1716 
1717 static struct scsi_asq_key_strings sd_additional_codes[] = {
1718 	0x81, 0, "Logical Unit is Reserved",
1719 	0x85, 0, "Audio Address Not Valid",
1720 	0xb6, 0, "Media Load Mechanism Failed",
1721 	0xB9, 0, "Audio Play Operation Aborted",
1722 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1723 	0x53, 2, "Medium removal prevented",
1724 	0x6f, 0, "Authentication failed during key exchange",
1725 	0x6f, 1, "Key not present",
1726 	0x6f, 2, "Key not established",
1727 	0x6f, 3, "Read without proper authentication",
1728 	0x6f, 4, "Mismatched region to this logical unit",
1729 	0x6f, 5, "Region reset count error",
1730 	0xffff, 0x0, NULL
1731 };
1732 
1733 
1734 /*
1735  * Struct for passing printing information for sense data messages
1736  */
1737 struct sd_sense_info {
1738 	int	ssi_severity;
1739 	int	ssi_pfa_flag;
1740 };
1741 
1742 /*
1743  * Table of function pointers for iostart-side routines. Separate "chains"
1744  * of layered function calls are formed by placing the function pointers
1745  * sequentially in the desired order. Functions are called according to an
1746  * incrementing table index ordering. The last function in each chain must
1747  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1748  * in the sd_iodone_chain[] array.
1749  *
1750  * Note: It may seem more natural to organize both the iostart and iodone
1751  * functions together, into an array of structures (or some similar
1752  * organization) with a common index, rather than two separate arrays which
1753  * must be maintained in synchronization. The purpose of this division is
1754  * to achieve improved performance: individual arrays allows for more
1755  * effective cache line utilization on certain platforms.
1756  */
1757 
1758 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1759 
1760 
1761 static sd_chain_t sd_iostart_chain[] = {
1762 
1763 	/* Chain for buf IO for disk drive targets (PM enabled) */
1764 	sd_mapblockaddr_iostart,	/* Index: 0 */
1765 	sd_pm_iostart,			/* Index: 1 */
1766 	sd_core_iostart,		/* Index: 2 */
1767 
1768 	/* Chain for buf IO for disk drive targets (PM disabled) */
1769 	sd_mapblockaddr_iostart,	/* Index: 3 */
1770 	sd_core_iostart,		/* Index: 4 */
1771 
1772 	/* Chain for buf IO for removable-media targets (PM enabled) */
1773 	sd_mapblockaddr_iostart,	/* Index: 5 */
1774 	sd_mapblocksize_iostart,	/* Index: 6 */
1775 	sd_pm_iostart,			/* Index: 7 */
1776 	sd_core_iostart,		/* Index: 8 */
1777 
1778 	/* Chain for buf IO for removable-media targets (PM disabled) */
1779 	sd_mapblockaddr_iostart,	/* Index: 9 */
1780 	sd_mapblocksize_iostart,	/* Index: 10 */
1781 	sd_core_iostart,		/* Index: 11 */
1782 
1783 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1784 	sd_mapblockaddr_iostart,	/* Index: 12 */
1785 	sd_checksum_iostart,		/* Index: 13 */
1786 	sd_pm_iostart,			/* Index: 14 */
1787 	sd_core_iostart,		/* Index: 15 */
1788 
1789 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1790 	sd_mapblockaddr_iostart,	/* Index: 16 */
1791 	sd_checksum_iostart,		/* Index: 17 */
1792 	sd_core_iostart,		/* Index: 18 */
1793 
1794 	/* Chain for USCSI commands (all targets) */
1795 	sd_pm_iostart,			/* Index: 19 */
1796 	sd_core_iostart,		/* Index: 20 */
1797 
1798 	/* Chain for checksumming USCSI commands (all targets) */
1799 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1800 	sd_pm_iostart,			/* Index: 22 */
1801 	sd_core_iostart,		/* Index: 23 */
1802 
1803 	/* Chain for "direct" USCSI commands (all targets) */
1804 	sd_core_iostart,		/* Index: 24 */
1805 
1806 	/* Chain for "direct priority" USCSI commands (all targets) */
1807 	sd_core_iostart,		/* Index: 25 */
1808 };
1809 
1810 /*
1811  * Macros to locate the first function of each iostart chain in the
1812  * sd_iostart_chain[] array. These are located by the index in the array.
1813  */
1814 #define	SD_CHAIN_DISK_IOSTART			0
1815 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1816 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1817 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1818 #define	SD_CHAIN_CHKSUM_IOSTART			12
1819 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1820 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1821 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1822 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1823 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1824 
1825 
1826 /*
1827  * Table of function pointers for the iodone-side routines for the driver-
1828  * internal layering mechanism.  The calling sequence for iodone routines
1829  * uses a decrementing table index, so the last routine called in a chain
1830  * must be at the lowest array index location for that chain.  The last
1831  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1832  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1833  * of the functions in an iodone side chain must correspond to the ordering
1834  * of the iostart routines for that chain.  Note that there is no iodone
1835  * side routine that corresponds to sd_core_iostart(), so there is no
1836  * entry in the table for this.
1837  */
1838 
1839 static sd_chain_t sd_iodone_chain[] = {
1840 
1841 	/* Chain for buf IO for disk drive targets (PM enabled) */
1842 	sd_buf_iodone,			/* Index: 0 */
1843 	sd_mapblockaddr_iodone,		/* Index: 1 */
1844 	sd_pm_iodone,			/* Index: 2 */
1845 
1846 	/* Chain for buf IO for disk drive targets (PM disabled) */
1847 	sd_buf_iodone,			/* Index: 3 */
1848 	sd_mapblockaddr_iodone,		/* Index: 4 */
1849 
1850 	/* Chain for buf IO for removable-media targets (PM enabled) */
1851 	sd_buf_iodone,			/* Index: 5 */
1852 	sd_mapblockaddr_iodone,		/* Index: 6 */
1853 	sd_mapblocksize_iodone,		/* Index: 7 */
1854 	sd_pm_iodone,			/* Index: 8 */
1855 
1856 	/* Chain for buf IO for removable-media targets (PM disabled) */
1857 	sd_buf_iodone,			/* Index: 9 */
1858 	sd_mapblockaddr_iodone,		/* Index: 10 */
1859 	sd_mapblocksize_iodone,		/* Index: 11 */
1860 
1861 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1862 	sd_buf_iodone,			/* Index: 12 */
1863 	sd_mapblockaddr_iodone,		/* Index: 13 */
1864 	sd_checksum_iodone,		/* Index: 14 */
1865 	sd_pm_iodone,			/* Index: 15 */
1866 
1867 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1868 	sd_buf_iodone,			/* Index: 16 */
1869 	sd_mapblockaddr_iodone,		/* Index: 17 */
1870 	sd_checksum_iodone,		/* Index: 18 */
1871 
1872 	/* Chain for USCSI commands (non-checksum targets) */
1873 	sd_uscsi_iodone,		/* Index: 19 */
1874 	sd_pm_iodone,			/* Index: 20 */
1875 
1876 	/* Chain for USCSI commands (checksum targets) */
1877 	sd_uscsi_iodone,		/* Index: 21 */
1878 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1879 	sd_pm_iodone,			/* Index: 22 */
1880 
1881 	/* Chain for "direct" USCSI commands (all targets) */
1882 	sd_uscsi_iodone,		/* Index: 24 */
1883 
1884 	/* Chain for "direct priority" USCSI commands (all targets) */
1885 	sd_uscsi_iodone,		/* Index: 25 */
1886 };
1887 
1888 
1889 /*
1890  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1891  * each iodone-side chain. These are located by the array index, but as the
1892  * iodone side functions are called in a decrementing-index order, the
1893  * highest index number in each chain must be specified (as these correspond
1894  * to the first function in the iodone chain that will be called by the core
1895  * at IO completion time).
1896  */
1897 
1898 #define	SD_CHAIN_DISK_IODONE			2
1899 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1900 #define	SD_CHAIN_RMMEDIA_IODONE			8
1901 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
1902 #define	SD_CHAIN_CHKSUM_IODONE			15
1903 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
1904 #define	SD_CHAIN_USCSI_CMD_IODONE		20
1905 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
1906 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
1907 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
1908 
1909 
1910 
1911 
1912 /*
1913  * Array to map a layering chain index to the appropriate initpkt routine.
1914  * The redundant entries are present so that the index used for accessing
1915  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1916  * with this table as well.
1917  */
1918 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
1919 
1920 static sd_initpkt_t	sd_initpkt_map[] = {
1921 
1922 	/* Chain for buf IO for disk drive targets (PM enabled) */
1923 	sd_initpkt_for_buf,		/* Index: 0 */
1924 	sd_initpkt_for_buf,		/* Index: 1 */
1925 	sd_initpkt_for_buf,		/* Index: 2 */
1926 
1927 	/* Chain for buf IO for disk drive targets (PM disabled) */
1928 	sd_initpkt_for_buf,		/* Index: 3 */
1929 	sd_initpkt_for_buf,		/* Index: 4 */
1930 
1931 	/* Chain for buf IO for removable-media targets (PM enabled) */
1932 	sd_initpkt_for_buf,		/* Index: 5 */
1933 	sd_initpkt_for_buf,		/* Index: 6 */
1934 	sd_initpkt_for_buf,		/* Index: 7 */
1935 	sd_initpkt_for_buf,		/* Index: 8 */
1936 
1937 	/* Chain for buf IO for removable-media targets (PM disabled) */
1938 	sd_initpkt_for_buf,		/* Index: 9 */
1939 	sd_initpkt_for_buf,		/* Index: 10 */
1940 	sd_initpkt_for_buf,		/* Index: 11 */
1941 
1942 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1943 	sd_initpkt_for_buf,		/* Index: 12 */
1944 	sd_initpkt_for_buf,		/* Index: 13 */
1945 	sd_initpkt_for_buf,		/* Index: 14 */
1946 	sd_initpkt_for_buf,		/* Index: 15 */
1947 
1948 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1949 	sd_initpkt_for_buf,		/* Index: 16 */
1950 	sd_initpkt_for_buf,		/* Index: 17 */
1951 	sd_initpkt_for_buf,		/* Index: 18 */
1952 
1953 	/* Chain for USCSI commands (non-checksum targets) */
1954 	sd_initpkt_for_uscsi,		/* Index: 19 */
1955 	sd_initpkt_for_uscsi,		/* Index: 20 */
1956 
1957 	/* Chain for USCSI commands (checksum targets) */
1958 	sd_initpkt_for_uscsi,		/* Index: 21 */
1959 	sd_initpkt_for_uscsi,		/* Index: 22 */
1960 	sd_initpkt_for_uscsi,		/* Index: 22 */
1961 
1962 	/* Chain for "direct" USCSI commands (all targets) */
1963 	sd_initpkt_for_uscsi,		/* Index: 24 */
1964 
1965 	/* Chain for "direct priority" USCSI commands (all targets) */
1966 	sd_initpkt_for_uscsi,		/* Index: 25 */
1967 
1968 };
1969 
1970 
1971 /*
1972  * Array to map a layering chain index to the appropriate destroypktpkt routine.
1973  * The redundant entries are present so that the index used for accessing
1974  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1975  * with this table as well.
1976  */
1977 typedef void (*sd_destroypkt_t)(struct buf *);
1978 
1979 static sd_destroypkt_t	sd_destroypkt_map[] = {
1980 
1981 	/* Chain for buf IO for disk drive targets (PM enabled) */
1982 	sd_destroypkt_for_buf,		/* Index: 0 */
1983 	sd_destroypkt_for_buf,		/* Index: 1 */
1984 	sd_destroypkt_for_buf,		/* Index: 2 */
1985 
1986 	/* Chain for buf IO for disk drive targets (PM disabled) */
1987 	sd_destroypkt_for_buf,		/* Index: 3 */
1988 	sd_destroypkt_for_buf,		/* Index: 4 */
1989 
1990 	/* Chain for buf IO for removable-media targets (PM enabled) */
1991 	sd_destroypkt_for_buf,		/* Index: 5 */
1992 	sd_destroypkt_for_buf,		/* Index: 6 */
1993 	sd_destroypkt_for_buf,		/* Index: 7 */
1994 	sd_destroypkt_for_buf,		/* Index: 8 */
1995 
1996 	/* Chain for buf IO for removable-media targets (PM disabled) */
1997 	sd_destroypkt_for_buf,		/* Index: 9 */
1998 	sd_destroypkt_for_buf,		/* Index: 10 */
1999 	sd_destroypkt_for_buf,		/* Index: 11 */
2000 
2001 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2002 	sd_destroypkt_for_buf,		/* Index: 12 */
2003 	sd_destroypkt_for_buf,		/* Index: 13 */
2004 	sd_destroypkt_for_buf,		/* Index: 14 */
2005 	sd_destroypkt_for_buf,		/* Index: 15 */
2006 
2007 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2008 	sd_destroypkt_for_buf,		/* Index: 16 */
2009 	sd_destroypkt_for_buf,		/* Index: 17 */
2010 	sd_destroypkt_for_buf,		/* Index: 18 */
2011 
2012 	/* Chain for USCSI commands (non-checksum targets) */
2013 	sd_destroypkt_for_uscsi,	/* Index: 19 */
2014 	sd_destroypkt_for_uscsi,	/* Index: 20 */
2015 
2016 	/* Chain for USCSI commands (checksum targets) */
2017 	sd_destroypkt_for_uscsi,	/* Index: 21 */
2018 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2019 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2020 
2021 	/* Chain for "direct" USCSI commands (all targets) */
2022 	sd_destroypkt_for_uscsi,	/* Index: 24 */
2023 
2024 	/* Chain for "direct priority" USCSI commands (all targets) */
2025 	sd_destroypkt_for_uscsi,	/* Index: 25 */
2026 
2027 };
2028 
2029 
2030 
2031 /*
2032  * Array to map a layering chain index to the appropriate chain "type".
2033  * The chain type indicates a specific property/usage of the chain.
2034  * The redundant entries are present so that the index used for accessing
2035  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2036  * with this table as well.
2037  */
2038 
2039 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2040 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2041 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2042 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2043 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2044 						/* (for error recovery) */
2045 
2046 static int sd_chain_type_map[] = {
2047 
2048 	/* Chain for buf IO for disk drive targets (PM enabled) */
2049 	SD_CHAIN_BUFIO,			/* Index: 0 */
2050 	SD_CHAIN_BUFIO,			/* Index: 1 */
2051 	SD_CHAIN_BUFIO,			/* Index: 2 */
2052 
2053 	/* Chain for buf IO for disk drive targets (PM disabled) */
2054 	SD_CHAIN_BUFIO,			/* Index: 3 */
2055 	SD_CHAIN_BUFIO,			/* Index: 4 */
2056 
2057 	/* Chain for buf IO for removable-media targets (PM enabled) */
2058 	SD_CHAIN_BUFIO,			/* Index: 5 */
2059 	SD_CHAIN_BUFIO,			/* Index: 6 */
2060 	SD_CHAIN_BUFIO,			/* Index: 7 */
2061 	SD_CHAIN_BUFIO,			/* Index: 8 */
2062 
2063 	/* Chain for buf IO for removable-media targets (PM disabled) */
2064 	SD_CHAIN_BUFIO,			/* Index: 9 */
2065 	SD_CHAIN_BUFIO,			/* Index: 10 */
2066 	SD_CHAIN_BUFIO,			/* Index: 11 */
2067 
2068 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2069 	SD_CHAIN_BUFIO,			/* Index: 12 */
2070 	SD_CHAIN_BUFIO,			/* Index: 13 */
2071 	SD_CHAIN_BUFIO,			/* Index: 14 */
2072 	SD_CHAIN_BUFIO,			/* Index: 15 */
2073 
2074 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2075 	SD_CHAIN_BUFIO,			/* Index: 16 */
2076 	SD_CHAIN_BUFIO,			/* Index: 17 */
2077 	SD_CHAIN_BUFIO,			/* Index: 18 */
2078 
2079 	/* Chain for USCSI commands (non-checksum targets) */
2080 	SD_CHAIN_USCSI,			/* Index: 19 */
2081 	SD_CHAIN_USCSI,			/* Index: 20 */
2082 
2083 	/* Chain for USCSI commands (checksum targets) */
2084 	SD_CHAIN_USCSI,			/* Index: 21 */
2085 	SD_CHAIN_USCSI,			/* Index: 22 */
2086 	SD_CHAIN_USCSI,			/* Index: 22 */
2087 
2088 	/* Chain for "direct" USCSI commands (all targets) */
2089 	SD_CHAIN_DIRECT,		/* Index: 24 */
2090 
2091 	/* Chain for "direct priority" USCSI commands (all targets) */
2092 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2093 };
2094 
2095 
2096 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2097 #define	SD_IS_BUFIO(xp)			\
2098 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2099 
2100 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2101 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2102 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2103 
2104 
2105 
2106 /*
2107  * Struct, array, and macros to map a specific chain to the appropriate
2108  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2109  *
2110  * The sd_chain_index_map[] array is used at attach time to set the various
2111  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2112  * chain to be used with the instance. This allows different instances to use
2113  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2114  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2115  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2116  * dynamically & without the use of locking; and (2) a layer may update the
2117  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2118  * to allow for deferred processing of an IO within the same chain from a
2119  * different execution context.
2120  */
2121 
2122 struct sd_chain_index {
2123 	int	sci_iostart_index;
2124 	int	sci_iodone_index;
2125 };
2126 
2127 static struct sd_chain_index	sd_chain_index_map[] = {
2128 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2129 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2130 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2131 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2132 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2133 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2134 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2135 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2136 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2137 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2138 };
2139 
2140 
2141 /*
2142  * The following are indexes into the sd_chain_index_map[] array.
2143  */
2144 
2145 /* un->un_buf_chain_type must be set to one of these */
2146 #define	SD_CHAIN_INFO_DISK		0
2147 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2148 #define	SD_CHAIN_INFO_RMMEDIA		2
2149 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2150 #define	SD_CHAIN_INFO_CHKSUM		4
2151 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2152 
2153 /* un->un_uscsi_chain_type must be set to one of these */
2154 #define	SD_CHAIN_INFO_USCSI_CMD		6
2155 /* USCSI with PM disabled is the same as DIRECT */
2156 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2157 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2158 
2159 /* un->un_direct_chain_type must be set to one of these */
2160 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2161 
2162 /* un->un_priority_chain_type must be set to one of these */
2163 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2164 
2165 /* size for devid inquiries */
2166 #define	MAX_INQUIRY_SIZE		0xF0
2167 
2168 /*
2169  * Macros used by functions to pass a given buf(9S) struct along to the
2170  * next function in the layering chain for further processing.
2171  *
2172  * In the following macros, passing more than three arguments to the called
2173  * routines causes the optimizer for the SPARC compiler to stop doing tail
2174  * call elimination which results in significant performance degradation.
2175  */
2176 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2177 	((*(sd_iostart_chain[index]))(index, un, bp))
2178 
2179 #define	SD_BEGIN_IODONE(index, un, bp)	\
2180 	((*(sd_iodone_chain[index]))(index, un, bp))
2181 
2182 #define	SD_NEXT_IOSTART(index, un, bp)				\
2183 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2184 
2185 #define	SD_NEXT_IODONE(index, un, bp)				\
2186 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2187 
2188 /*
2189  *    Function: _init
2190  *
2191  * Description: This is the driver _init(9E) entry point.
2192  *
2193  * Return Code: Returns the value from mod_install(9F) or
2194  *		ddi_soft_state_init(9F) as appropriate.
2195  *
2196  *     Context: Called when driver module loaded.
2197  */
2198 
2199 int
2200 _init(void)
2201 {
2202 	int	err;
2203 
2204 	/* establish driver name from module name */
2205 	sd_label = (char *)mod_modname(&modlinkage);
2206 
2207 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2208 	    SD_MAXUNIT);
2209 
2210 	if (err != 0) {
2211 		return (err);
2212 	}
2213 
2214 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2215 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2216 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2217 
2218 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2219 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2220 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2221 
2222 	/*
2223 	 * it's ok to init here even for fibre device
2224 	 */
2225 	sd_scsi_probe_cache_init();
2226 
2227 	sd_scsi_target_lun_init();
2228 
2229 	/*
2230 	 * Creating taskq before mod_install ensures that all callers (threads)
2231 	 * that enter the module after a successful mod_install encounter
2232 	 * a valid taskq.
2233 	 */
2234 	sd_taskq_create();
2235 
2236 	err = mod_install(&modlinkage);
2237 	if (err != 0) {
2238 		/* delete taskq if install fails */
2239 		sd_taskq_delete();
2240 
2241 		mutex_destroy(&sd_detach_mutex);
2242 		mutex_destroy(&sd_log_mutex);
2243 		mutex_destroy(&sd_label_mutex);
2244 
2245 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2246 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2247 		cv_destroy(&sd_tr.srq_inprocess_cv);
2248 
2249 		sd_scsi_probe_cache_fini();
2250 
2251 		sd_scsi_target_lun_fini();
2252 
2253 		ddi_soft_state_fini(&sd_state);
2254 		return (err);
2255 	}
2256 
2257 	return (err);
2258 }
2259 
2260 
2261 /*
2262  *    Function: _fini
2263  *
2264  * Description: This is the driver _fini(9E) entry point.
2265  *
2266  * Return Code: Returns the value from mod_remove(9F)
2267  *
2268  *     Context: Called when driver module is unloaded.
2269  */
2270 
2271 int
2272 _fini(void)
2273 {
2274 	int err;
2275 
2276 	if ((err = mod_remove(&modlinkage)) != 0) {
2277 		return (err);
2278 	}
2279 
2280 	sd_taskq_delete();
2281 
2282 	mutex_destroy(&sd_detach_mutex);
2283 	mutex_destroy(&sd_log_mutex);
2284 	mutex_destroy(&sd_label_mutex);
2285 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2286 
2287 	sd_scsi_probe_cache_fini();
2288 
2289 	sd_scsi_target_lun_fini();
2290 
2291 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2292 	cv_destroy(&sd_tr.srq_inprocess_cv);
2293 
2294 	ddi_soft_state_fini(&sd_state);
2295 
2296 	return (err);
2297 }
2298 
2299 
2300 /*
2301  *    Function: _info
2302  *
2303  * Description: This is the driver _info(9E) entry point.
2304  *
2305  *   Arguments: modinfop - pointer to the driver modinfo structure
2306  *
2307  * Return Code: Returns the value from mod_info(9F).
2308  *
2309  *     Context: Kernel thread context
2310  */
2311 
2312 int
2313 _info(struct modinfo *modinfop)
2314 {
2315 	return (mod_info(&modlinkage, modinfop));
2316 }
2317 
2318 
2319 /*
2320  * The following routines implement the driver message logging facility.
2321  * They provide component- and level- based debug output filtering.
2322  * Output may also be restricted to messages for a single instance by
2323  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2324  * to NULL, then messages for all instances are printed.
2325  *
2326  * These routines have been cloned from each other due to the language
2327  * constraints of macros and variable argument list processing.
2328  */
2329 
2330 
2331 /*
2332  *    Function: sd_log_err
2333  *
2334  * Description: This routine is called by the SD_ERROR macro for debug
2335  *		logging of error conditions.
2336  *
2337  *   Arguments: comp - driver component being logged
2338  *		dev  - pointer to driver info structure
2339  *		fmt  - error string and format to be logged
2340  */
2341 
2342 static void
2343 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2344 {
2345 	va_list		ap;
2346 	dev_info_t	*dev;
2347 
2348 	ASSERT(un != NULL);
2349 	dev = SD_DEVINFO(un);
2350 	ASSERT(dev != NULL);
2351 
2352 	/*
2353 	 * Filter messages based on the global component and level masks.
2354 	 * Also print if un matches the value of sd_debug_un, or if
2355 	 * sd_debug_un is set to NULL.
2356 	 */
2357 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2358 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2359 		mutex_enter(&sd_log_mutex);
2360 		va_start(ap, fmt);
2361 		(void) vsprintf(sd_log_buf, fmt, ap);
2362 		va_end(ap);
2363 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2364 		mutex_exit(&sd_log_mutex);
2365 	}
2366 #ifdef SD_FAULT_INJECTION
2367 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2368 	if (un->sd_injection_mask & comp) {
2369 		mutex_enter(&sd_log_mutex);
2370 		va_start(ap, fmt);
2371 		(void) vsprintf(sd_log_buf, fmt, ap);
2372 		va_end(ap);
2373 		sd_injection_log(sd_log_buf, un);
2374 		mutex_exit(&sd_log_mutex);
2375 	}
2376 #endif
2377 }
2378 
2379 
2380 /*
2381  *    Function: sd_log_info
2382  *
2383  * Description: This routine is called by the SD_INFO macro for debug
2384  *		logging of general purpose informational conditions.
2385  *
2386  *   Arguments: comp - driver component being logged
2387  *		dev  - pointer to driver info structure
2388  *		fmt  - info string and format to be logged
2389  */
2390 
2391 static void
2392 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2393 {
2394 	va_list		ap;
2395 	dev_info_t	*dev;
2396 
2397 	ASSERT(un != NULL);
2398 	dev = SD_DEVINFO(un);
2399 	ASSERT(dev != NULL);
2400 
2401 	/*
2402 	 * Filter messages based on the global component and level masks.
2403 	 * Also print if un matches the value of sd_debug_un, or if
2404 	 * sd_debug_un is set to NULL.
2405 	 */
2406 	if ((sd_component_mask & component) &&
2407 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2408 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2409 		mutex_enter(&sd_log_mutex);
2410 		va_start(ap, fmt);
2411 		(void) vsprintf(sd_log_buf, fmt, ap);
2412 		va_end(ap);
2413 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2414 		mutex_exit(&sd_log_mutex);
2415 	}
2416 #ifdef SD_FAULT_INJECTION
2417 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2418 	if (un->sd_injection_mask & component) {
2419 		mutex_enter(&sd_log_mutex);
2420 		va_start(ap, fmt);
2421 		(void) vsprintf(sd_log_buf, fmt, ap);
2422 		va_end(ap);
2423 		sd_injection_log(sd_log_buf, un);
2424 		mutex_exit(&sd_log_mutex);
2425 	}
2426 #endif
2427 }
2428 
2429 
2430 /*
2431  *    Function: sd_log_trace
2432  *
2433  * Description: This routine is called by the SD_TRACE macro for debug
2434  *		logging of trace conditions (i.e. function entry/exit).
2435  *
2436  *   Arguments: comp - driver component being logged
2437  *		dev  - pointer to driver info structure
2438  *		fmt  - trace string and format to be logged
2439  */
2440 
2441 static void
2442 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2443 {
2444 	va_list		ap;
2445 	dev_info_t	*dev;
2446 
2447 	ASSERT(un != NULL);
2448 	dev = SD_DEVINFO(un);
2449 	ASSERT(dev != NULL);
2450 
2451 	/*
2452 	 * Filter messages based on the global component and level masks.
2453 	 * Also print if un matches the value of sd_debug_un, or if
2454 	 * sd_debug_un is set to NULL.
2455 	 */
2456 	if ((sd_component_mask & component) &&
2457 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2458 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2459 		mutex_enter(&sd_log_mutex);
2460 		va_start(ap, fmt);
2461 		(void) vsprintf(sd_log_buf, fmt, ap);
2462 		va_end(ap);
2463 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2464 		mutex_exit(&sd_log_mutex);
2465 	}
2466 #ifdef SD_FAULT_INJECTION
2467 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2468 	if (un->sd_injection_mask & component) {
2469 		mutex_enter(&sd_log_mutex);
2470 		va_start(ap, fmt);
2471 		(void) vsprintf(sd_log_buf, fmt, ap);
2472 		va_end(ap);
2473 		sd_injection_log(sd_log_buf, un);
2474 		mutex_exit(&sd_log_mutex);
2475 	}
2476 #endif
2477 }
2478 
2479 
2480 /*
2481  *    Function: sdprobe
2482  *
2483  * Description: This is the driver probe(9e) entry point function.
2484  *
2485  *   Arguments: devi - opaque device info handle
2486  *
2487  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2488  *              DDI_PROBE_FAILURE: If the probe failed.
2489  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2490  *				   but may be present in the future.
2491  */
2492 
2493 static int
2494 sdprobe(dev_info_t *devi)
2495 {
2496 	struct scsi_device	*devp;
2497 	int			rval;
2498 	int			instance;
2499 
2500 	/*
2501 	 * if it wasn't for pln, sdprobe could actually be nulldev
2502 	 * in the "__fibre" case.
2503 	 */
2504 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2505 		return (DDI_PROBE_DONTCARE);
2506 	}
2507 
2508 	devp = ddi_get_driver_private(devi);
2509 
2510 	if (devp == NULL) {
2511 		/* Ooops... nexus driver is mis-configured... */
2512 		return (DDI_PROBE_FAILURE);
2513 	}
2514 
2515 	instance = ddi_get_instance(devi);
2516 
2517 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2518 		return (DDI_PROBE_PARTIAL);
2519 	}
2520 
2521 	/*
2522 	 * Call the SCSA utility probe routine to see if we actually
2523 	 * have a target at this SCSI nexus.
2524 	 */
2525 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2526 	case SCSIPROBE_EXISTS:
2527 		switch (devp->sd_inq->inq_dtype) {
2528 		case DTYPE_DIRECT:
2529 			rval = DDI_PROBE_SUCCESS;
2530 			break;
2531 		case DTYPE_RODIRECT:
2532 			/* CDs etc. Can be removable media */
2533 			rval = DDI_PROBE_SUCCESS;
2534 			break;
2535 		case DTYPE_OPTICAL:
2536 			/*
2537 			 * Rewritable optical driver HP115AA
2538 			 * Can also be removable media
2539 			 */
2540 
2541 			/*
2542 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2543 			 * pre solaris 9 sparc sd behavior is required
2544 			 *
2545 			 * If first time through and sd_dtype_optical_bind
2546 			 * has not been set in /etc/system check properties
2547 			 */
2548 
2549 			if (sd_dtype_optical_bind  < 0) {
2550 				sd_dtype_optical_bind = ddi_prop_get_int
2551 				    (DDI_DEV_T_ANY, devi, 0,
2552 				    "optical-device-bind", 1);
2553 			}
2554 
2555 			if (sd_dtype_optical_bind == 0) {
2556 				rval = DDI_PROBE_FAILURE;
2557 			} else {
2558 				rval = DDI_PROBE_SUCCESS;
2559 			}
2560 			break;
2561 
2562 		case DTYPE_NOTPRESENT:
2563 		default:
2564 			rval = DDI_PROBE_FAILURE;
2565 			break;
2566 		}
2567 		break;
2568 	default:
2569 		rval = DDI_PROBE_PARTIAL;
2570 		break;
2571 	}
2572 
2573 	/*
2574 	 * This routine checks for resource allocation prior to freeing,
2575 	 * so it will take care of the "smart probing" case where a
2576 	 * scsi_probe() may or may not have been issued and will *not*
2577 	 * free previously-freed resources.
2578 	 */
2579 	scsi_unprobe(devp);
2580 	return (rval);
2581 }
2582 
2583 
2584 /*
2585  *    Function: sdinfo
2586  *
2587  * Description: This is the driver getinfo(9e) entry point function.
2588  * 		Given the device number, return the devinfo pointer from
2589  *		the scsi_device structure or the instance number
2590  *		associated with the dev_t.
2591  *
2592  *   Arguments: dip     - pointer to device info structure
2593  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2594  *			  DDI_INFO_DEVT2INSTANCE)
2595  *		arg     - driver dev_t
2596  *		resultp - user buffer for request response
2597  *
2598  * Return Code: DDI_SUCCESS
2599  *              DDI_FAILURE
2600  */
2601 /* ARGSUSED */
2602 static int
2603 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2604 {
2605 	struct sd_lun	*un;
2606 	dev_t		dev;
2607 	int		instance;
2608 	int		error;
2609 
2610 	switch (infocmd) {
2611 	case DDI_INFO_DEVT2DEVINFO:
2612 		dev = (dev_t)arg;
2613 		instance = SDUNIT(dev);
2614 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2615 			return (DDI_FAILURE);
2616 		}
2617 		*result = (void *) SD_DEVINFO(un);
2618 		error = DDI_SUCCESS;
2619 		break;
2620 	case DDI_INFO_DEVT2INSTANCE:
2621 		dev = (dev_t)arg;
2622 		instance = SDUNIT(dev);
2623 		*result = (void *)(uintptr_t)instance;
2624 		error = DDI_SUCCESS;
2625 		break;
2626 	default:
2627 		error = DDI_FAILURE;
2628 	}
2629 	return (error);
2630 }
2631 
2632 /*
2633  *    Function: sd_prop_op
2634  *
2635  * Description: This is the driver prop_op(9e) entry point function.
2636  *		Return the number of blocks for the partition in question
2637  *		or forward the request to the property facilities.
2638  *
2639  *   Arguments: dev       - device number
2640  *		dip       - pointer to device info structure
2641  *		prop_op   - property operator
2642  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2643  *		name      - pointer to property name
2644  *		valuep    - pointer or address of the user buffer
2645  *		lengthp   - property length
2646  *
2647  * Return Code: DDI_PROP_SUCCESS
2648  *              DDI_PROP_NOT_FOUND
2649  *              DDI_PROP_UNDEFINED
2650  *              DDI_PROP_NO_MEMORY
2651  *              DDI_PROP_BUF_TOO_SMALL
2652  */
2653 
2654 static int
2655 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2656 	char *name, caddr_t valuep, int *lengthp)
2657 {
2658 	struct sd_lun	*un;
2659 
2660 	if ((un = ddi_get_soft_state(sd_state, ddi_get_instance(dip))) == NULL)
2661 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2662 		    name, valuep, lengthp));
2663 
2664 	return (cmlb_prop_op(un->un_cmlbhandle,
2665 	    dev, dip, prop_op, mod_flags, name, valuep, lengthp,
2666 	    SDPART(dev), (void *)SD_PATH_DIRECT));
2667 }
2668 
2669 /*
2670  * The following functions are for smart probing:
2671  * sd_scsi_probe_cache_init()
2672  * sd_scsi_probe_cache_fini()
2673  * sd_scsi_clear_probe_cache()
2674  * sd_scsi_probe_with_cache()
2675  */
2676 
2677 /*
2678  *    Function: sd_scsi_probe_cache_init
2679  *
2680  * Description: Initializes the probe response cache mutex and head pointer.
2681  *
2682  *     Context: Kernel thread context
2683  */
2684 
2685 static void
2686 sd_scsi_probe_cache_init(void)
2687 {
2688 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2689 	sd_scsi_probe_cache_head = NULL;
2690 }
2691 
2692 
2693 /*
2694  *    Function: sd_scsi_probe_cache_fini
2695  *
2696  * Description: Frees all resources associated with the probe response cache.
2697  *
2698  *     Context: Kernel thread context
2699  */
2700 
2701 static void
2702 sd_scsi_probe_cache_fini(void)
2703 {
2704 	struct sd_scsi_probe_cache *cp;
2705 	struct sd_scsi_probe_cache *ncp;
2706 
2707 	/* Clean up our smart probing linked list */
2708 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2709 		ncp = cp->next;
2710 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2711 	}
2712 	sd_scsi_probe_cache_head = NULL;
2713 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2714 }
2715 
2716 
2717 /*
2718  *    Function: sd_scsi_clear_probe_cache
2719  *
2720  * Description: This routine clears the probe response cache. This is
2721  *		done when open() returns ENXIO so that when deferred
2722  *		attach is attempted (possibly after a device has been
2723  *		turned on) we will retry the probe. Since we don't know
2724  *		which target we failed to open, we just clear the
2725  *		entire cache.
2726  *
2727  *     Context: Kernel thread context
2728  */
2729 
2730 static void
2731 sd_scsi_clear_probe_cache(void)
2732 {
2733 	struct sd_scsi_probe_cache	*cp;
2734 	int				i;
2735 
2736 	mutex_enter(&sd_scsi_probe_cache_mutex);
2737 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2738 		/*
2739 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2740 		 * force probing to be performed the next time
2741 		 * sd_scsi_probe_with_cache is called.
2742 		 */
2743 		for (i = 0; i < NTARGETS_WIDE; i++) {
2744 			cp->cache[i] = SCSIPROBE_EXISTS;
2745 		}
2746 	}
2747 	mutex_exit(&sd_scsi_probe_cache_mutex);
2748 }
2749 
2750 
2751 /*
2752  *    Function: sd_scsi_probe_with_cache
2753  *
2754  * Description: This routine implements support for a scsi device probe
2755  *		with cache. The driver maintains a cache of the target
2756  *		responses to scsi probes. If we get no response from a
2757  *		target during a probe inquiry, we remember that, and we
2758  *		avoid additional calls to scsi_probe on non-zero LUNs
2759  *		on the same target until the cache is cleared. By doing
2760  *		so we avoid the 1/4 sec selection timeout for nonzero
2761  *		LUNs. lun0 of a target is always probed.
2762  *
2763  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2764  *              waitfunc - indicates what the allocator routines should
2765  *			   do when resources are not available. This value
2766  *			   is passed on to scsi_probe() when that routine
2767  *			   is called.
2768  *
2769  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2770  *		otherwise the value returned by scsi_probe(9F).
2771  *
2772  *     Context: Kernel thread context
2773  */
2774 
2775 static int
2776 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2777 {
2778 	struct sd_scsi_probe_cache	*cp;
2779 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2780 	int		lun, tgt;
2781 
2782 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2783 	    SCSI_ADDR_PROP_LUN, 0);
2784 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2785 	    SCSI_ADDR_PROP_TARGET, -1);
2786 
2787 	/* Make sure caching enabled and target in range */
2788 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2789 		/* do it the old way (no cache) */
2790 		return (scsi_probe(devp, waitfn));
2791 	}
2792 
2793 	mutex_enter(&sd_scsi_probe_cache_mutex);
2794 
2795 	/* Find the cache for this scsi bus instance */
2796 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2797 		if (cp->pdip == pdip) {
2798 			break;
2799 		}
2800 	}
2801 
2802 	/* If we can't find a cache for this pdip, create one */
2803 	if (cp == NULL) {
2804 		int i;
2805 
2806 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2807 		    KM_SLEEP);
2808 		cp->pdip = pdip;
2809 		cp->next = sd_scsi_probe_cache_head;
2810 		sd_scsi_probe_cache_head = cp;
2811 		for (i = 0; i < NTARGETS_WIDE; i++) {
2812 			cp->cache[i] = SCSIPROBE_EXISTS;
2813 		}
2814 	}
2815 
2816 	mutex_exit(&sd_scsi_probe_cache_mutex);
2817 
2818 	/* Recompute the cache for this target if LUN zero */
2819 	if (lun == 0) {
2820 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2821 	}
2822 
2823 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2824 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2825 		return (SCSIPROBE_NORESP);
2826 	}
2827 
2828 	/* Do the actual probe; save & return the result */
2829 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
2830 }
2831 
2832 
2833 /*
2834  *    Function: sd_scsi_target_lun_init
2835  *
2836  * Description: Initializes the attached lun chain mutex and head pointer.
2837  *
2838  *     Context: Kernel thread context
2839  */
2840 
2841 static void
2842 sd_scsi_target_lun_init(void)
2843 {
2844 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
2845 	sd_scsi_target_lun_head = NULL;
2846 }
2847 
2848 
2849 /*
2850  *    Function: sd_scsi_target_lun_fini
2851  *
2852  * Description: Frees all resources associated with the attached lun
2853  *              chain
2854  *
2855  *     Context: Kernel thread context
2856  */
2857 
2858 static void
2859 sd_scsi_target_lun_fini(void)
2860 {
2861 	struct sd_scsi_hba_tgt_lun	*cp;
2862 	struct sd_scsi_hba_tgt_lun	*ncp;
2863 
2864 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
2865 		ncp = cp->next;
2866 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
2867 	}
2868 	sd_scsi_target_lun_head = NULL;
2869 	mutex_destroy(&sd_scsi_target_lun_mutex);
2870 }
2871 
2872 
2873 /*
2874  *    Function: sd_scsi_get_target_lun_count
2875  *
2876  * Description: This routine will check in the attached lun chain to see
2877  * 		how many luns are attached on the required SCSI controller
2878  * 		and target. Currently, some capabilities like tagged queue
2879  *		are supported per target based by HBA. So all luns in a
2880  *		target have the same capabilities. Based on this assumption,
2881  * 		sd should only set these capabilities once per target. This
2882  *		function is called when sd needs to decide how many luns
2883  *		already attached on a target.
2884  *
2885  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
2886  *			  controller device.
2887  *              target	- The target ID on the controller's SCSI bus.
2888  *
2889  * Return Code: The number of luns attached on the required target and
2890  *		controller.
2891  *		-1 if target ID is not in parallel SCSI scope or the given
2892  * 		dip is not in the chain.
2893  *
2894  *     Context: Kernel thread context
2895  */
2896 
2897 static int
2898 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
2899 {
2900 	struct sd_scsi_hba_tgt_lun	*cp;
2901 
2902 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
2903 		return (-1);
2904 	}
2905 
2906 	mutex_enter(&sd_scsi_target_lun_mutex);
2907 
2908 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2909 		if (cp->pdip == dip) {
2910 			break;
2911 		}
2912 	}
2913 
2914 	mutex_exit(&sd_scsi_target_lun_mutex);
2915 
2916 	if (cp == NULL) {
2917 		return (-1);
2918 	}
2919 
2920 	return (cp->nlun[target]);
2921 }
2922 
2923 
2924 /*
2925  *    Function: sd_scsi_update_lun_on_target
2926  *
2927  * Description: This routine is used to update the attached lun chain when a
2928  *		lun is attached or detached on a target.
2929  *
2930  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
2931  *                        controller device.
2932  *              target  - The target ID on the controller's SCSI bus.
2933  *		flag	- Indicate the lun is attached or detached.
2934  *
2935  *     Context: Kernel thread context
2936  */
2937 
2938 static void
2939 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
2940 {
2941 	struct sd_scsi_hba_tgt_lun	*cp;
2942 
2943 	mutex_enter(&sd_scsi_target_lun_mutex);
2944 
2945 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2946 		if (cp->pdip == dip) {
2947 			break;
2948 		}
2949 	}
2950 
2951 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
2952 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
2953 		    KM_SLEEP);
2954 		cp->pdip = dip;
2955 		cp->next = sd_scsi_target_lun_head;
2956 		sd_scsi_target_lun_head = cp;
2957 	}
2958 
2959 	mutex_exit(&sd_scsi_target_lun_mutex);
2960 
2961 	if (cp != NULL) {
2962 		if (flag == SD_SCSI_LUN_ATTACH) {
2963 			cp->nlun[target] ++;
2964 		} else {
2965 			cp->nlun[target] --;
2966 		}
2967 	}
2968 }
2969 
2970 
2971 /*
2972  *    Function: sd_spin_up_unit
2973  *
2974  * Description: Issues the following commands to spin-up the device:
2975  *		START STOP UNIT, and INQUIRY.
2976  *
2977  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
2978  *                      structure for this target.
2979  *
2980  * Return Code: 0 - success
2981  *		EIO - failure
2982  *		EACCES - reservation conflict
2983  *
2984  *     Context: Kernel thread context
2985  */
2986 
2987 static int
2988 sd_spin_up_unit(sd_ssc_t *ssc)
2989 {
2990 	size_t	resid		= 0;
2991 	int	has_conflict	= FALSE;
2992 	uchar_t *bufaddr;
2993 	int 	status;
2994 	struct sd_lun	*un;
2995 
2996 	ASSERT(ssc != NULL);
2997 	un = ssc->ssc_un;
2998 	ASSERT(un != NULL);
2999 
3000 	/*
3001 	 * Send a throwaway START UNIT command.
3002 	 *
3003 	 * If we fail on this, we don't care presently what precisely
3004 	 * is wrong.  EMC's arrays will also fail this with a check
3005 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
3006 	 * we don't want to fail the attach because it may become
3007 	 * "active" later.
3008 	 */
3009 	status = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_START,
3010 	    SD_PATH_DIRECT);
3011 
3012 	if (status != 0) {
3013 		if (status == EACCES)
3014 			has_conflict = TRUE;
3015 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3016 	}
3017 
3018 	/*
3019 	 * Send another INQUIRY command to the target. This is necessary for
3020 	 * non-removable media direct access devices because their INQUIRY data
3021 	 * may not be fully qualified until they are spun up (perhaps via the
3022 	 * START command above).  Note: This seems to be needed for some
3023 	 * legacy devices only.) The INQUIRY command should succeed even if a
3024 	 * Reservation Conflict is present.
3025 	 */
3026 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
3027 
3028 	if (sd_send_scsi_INQUIRY(ssc, bufaddr, SUN_INQSIZE, 0, 0, &resid)
3029 	    != 0) {
3030 		kmem_free(bufaddr, SUN_INQSIZE);
3031 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
3032 		return (EIO);
3033 	}
3034 
3035 	/*
3036 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
3037 	 * Note that this routine does not return a failure here even if the
3038 	 * INQUIRY command did not return any data.  This is a legacy behavior.
3039 	 */
3040 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
3041 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
3042 	}
3043 
3044 	kmem_free(bufaddr, SUN_INQSIZE);
3045 
3046 	/* If we hit a reservation conflict above, tell the caller. */
3047 	if (has_conflict == TRUE) {
3048 		return (EACCES);
3049 	}
3050 
3051 	return (0);
3052 }
3053 
3054 #ifdef _LP64
3055 /*
3056  *    Function: sd_enable_descr_sense
3057  *
3058  * Description: This routine attempts to select descriptor sense format
3059  *		using the Control mode page.  Devices that support 64 bit
3060  *		LBAs (for >2TB luns) should also implement descriptor
3061  *		sense data so we will call this function whenever we see
3062  *		a lun larger than 2TB.  If for some reason the device
3063  *		supports 64 bit LBAs but doesn't support descriptor sense
3064  *		presumably the mode select will fail.  Everything will
3065  *		continue to work normally except that we will not get
3066  *		complete sense data for commands that fail with an LBA
3067  *		larger than 32 bits.
3068  *
3069  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3070  *                      structure for this target.
3071  *
3072  *     Context: Kernel thread context only
3073  */
3074 
3075 static void
3076 sd_enable_descr_sense(sd_ssc_t *ssc)
3077 {
3078 	uchar_t			*header;
3079 	struct mode_control_scsi3 *ctrl_bufp;
3080 	size_t			buflen;
3081 	size_t			bd_len;
3082 	int			status;
3083 	struct sd_lun		*un;
3084 
3085 	ASSERT(ssc != NULL);
3086 	un = ssc->ssc_un;
3087 	ASSERT(un != NULL);
3088 
3089 	/*
3090 	 * Read MODE SENSE page 0xA, Control Mode Page
3091 	 */
3092 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3093 	    sizeof (struct mode_control_scsi3);
3094 	header = kmem_zalloc(buflen, KM_SLEEP);
3095 
3096 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
3097 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT);
3098 
3099 	if (status != 0) {
3100 		SD_ERROR(SD_LOG_COMMON, un,
3101 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3102 		goto eds_exit;
3103 	}
3104 
3105 	/*
3106 	 * Determine size of Block Descriptors in order to locate
3107 	 * the mode page data. ATAPI devices return 0, SCSI devices
3108 	 * should return MODE_BLK_DESC_LENGTH.
3109 	 */
3110 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3111 
3112 	/* Clear the mode data length field for MODE SELECT */
3113 	((struct mode_header *)header)->length = 0;
3114 
3115 	ctrl_bufp = (struct mode_control_scsi3 *)
3116 	    (header + MODE_HEADER_LENGTH + bd_len);
3117 
3118 	/*
3119 	 * If the page length is smaller than the expected value,
3120 	 * the target device doesn't support D_SENSE. Bail out here.
3121 	 */
3122 	if (ctrl_bufp->mode_page.length <
3123 	    sizeof (struct mode_control_scsi3) - 2) {
3124 		SD_ERROR(SD_LOG_COMMON, un,
3125 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3126 		goto eds_exit;
3127 	}
3128 
3129 	/*
3130 	 * Clear PS bit for MODE SELECT
3131 	 */
3132 	ctrl_bufp->mode_page.ps = 0;
3133 
3134 	/*
3135 	 * Set D_SENSE to enable descriptor sense format.
3136 	 */
3137 	ctrl_bufp->d_sense = 1;
3138 
3139 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3140 
3141 	/*
3142 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3143 	 */
3144 	status = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
3145 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT);
3146 
3147 	if (status != 0) {
3148 		SD_INFO(SD_LOG_COMMON, un,
3149 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3150 	} else {
3151 		kmem_free(header, buflen);
3152 		return;
3153 	}
3154 
3155 eds_exit:
3156 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3157 	kmem_free(header, buflen);
3158 }
3159 
3160 /*
3161  *    Function: sd_reenable_dsense_task
3162  *
3163  * Description: Re-enable descriptor sense after device or bus reset
3164  *
3165  *     Context: Executes in a taskq() thread context
3166  */
3167 static void
3168 sd_reenable_dsense_task(void *arg)
3169 {
3170 	struct	sd_lun	*un = arg;
3171 	sd_ssc_t	*ssc;
3172 
3173 	ASSERT(un != NULL);
3174 
3175 	ssc = sd_ssc_init(un);
3176 	sd_enable_descr_sense(ssc);
3177 	sd_ssc_fini(ssc);
3178 }
3179 #endif /* _LP64 */
3180 
3181 /*
3182  *    Function: sd_set_mmc_caps
3183  *
3184  * Description: This routine determines if the device is MMC compliant and if
3185  *		the device supports CDDA via a mode sense of the CDVD
3186  *		capabilities mode page. Also checks if the device is a
3187  *		dvdram writable device.
3188  *
3189  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3190  *                      structure for this target.
3191  *
3192  *     Context: Kernel thread context only
3193  */
3194 
3195 static void
3196 sd_set_mmc_caps(sd_ssc_t *ssc)
3197 {
3198 	struct mode_header_grp2		*sense_mhp;
3199 	uchar_t				*sense_page;
3200 	caddr_t				buf;
3201 	int				bd_len;
3202 	int				status;
3203 	struct uscsi_cmd		com;
3204 	int				rtn;
3205 	uchar_t				*out_data_rw, *out_data_hd;
3206 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3207 	struct sd_lun			*un;
3208 
3209 	ASSERT(ssc != NULL);
3210 	un = ssc->ssc_un;
3211 	ASSERT(un != NULL);
3212 
3213 	/*
3214 	 * The flags which will be set in this function are - mmc compliant,
3215 	 * dvdram writable device, cdda support. Initialize them to FALSE
3216 	 * and if a capability is detected - it will be set to TRUE.
3217 	 */
3218 	un->un_f_mmc_cap = FALSE;
3219 	un->un_f_dvdram_writable_device = FALSE;
3220 	un->un_f_cfg_cdda = FALSE;
3221 
3222 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3223 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3224 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3225 
3226 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3227 
3228 	if (status != 0) {
3229 		/* command failed; just return */
3230 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3231 		return;
3232 	}
3233 	/*
3234 	 * If the mode sense request for the CDROM CAPABILITIES
3235 	 * page (0x2A) succeeds the device is assumed to be MMC.
3236 	 */
3237 	un->un_f_mmc_cap = TRUE;
3238 
3239 	/* Get to the page data */
3240 	sense_mhp = (struct mode_header_grp2 *)buf;
3241 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3242 	    sense_mhp->bdesc_length_lo;
3243 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3244 		/*
3245 		 * We did not get back the expected block descriptor
3246 		 * length so we cannot determine if the device supports
3247 		 * CDDA. However, we still indicate the device is MMC
3248 		 * according to the successful response to the page
3249 		 * 0x2A mode sense request.
3250 		 */
3251 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3252 		    "sd_set_mmc_caps: Mode Sense returned "
3253 		    "invalid block descriptor length\n");
3254 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3255 		return;
3256 	}
3257 
3258 	/* See if read CDDA is supported */
3259 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3260 	    bd_len);
3261 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3262 
3263 	/* See if writing DVD RAM is supported. */
3264 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3265 	if (un->un_f_dvdram_writable_device == TRUE) {
3266 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3267 		return;
3268 	}
3269 
3270 	/*
3271 	 * If the device presents DVD or CD capabilities in the mode
3272 	 * page, we can return here since a RRD will not have
3273 	 * these capabilities.
3274 	 */
3275 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3276 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3277 		return;
3278 	}
3279 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3280 
3281 	/*
3282 	 * If un->un_f_dvdram_writable_device is still FALSE,
3283 	 * check for a Removable Rigid Disk (RRD).  A RRD
3284 	 * device is identified by the features RANDOM_WRITABLE and
3285 	 * HARDWARE_DEFECT_MANAGEMENT.
3286 	 */
3287 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3288 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3289 
3290 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3291 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3292 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3293 
3294 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3295 
3296 	if (rtn != 0) {
3297 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3298 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3299 		return;
3300 	}
3301 
3302 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3303 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3304 
3305 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3306 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3307 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3308 
3309 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3310 
3311 	if (rtn == 0) {
3312 		/*
3313 		 * We have good information, check for random writable
3314 		 * and hardware defect features.
3315 		 */
3316 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3317 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3318 			un->un_f_dvdram_writable_device = TRUE;
3319 		}
3320 	}
3321 
3322 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3323 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3324 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3325 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3326 }
3327 
3328 /*
3329  *    Function: sd_check_for_writable_cd
3330  *
3331  * Description: This routine determines if the media in the device is
3332  *		writable or not. It uses the get configuration command (0x46)
3333  *		to determine if the media is writable
3334  *
3335  *   Arguments: un - driver soft state (unit) structure
3336  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3337  *                           chain and the normal command waitq, or
3338  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3339  *                           "direct" chain and bypass the normal command
3340  *                           waitq.
3341  *
3342  *     Context: Never called at interrupt context.
3343  */
3344 
3345 static void
3346 sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag)
3347 {
3348 	struct uscsi_cmd		com;
3349 	uchar_t				*out_data;
3350 	uchar_t				*rqbuf;
3351 	int				rtn;
3352 	uchar_t				*out_data_rw, *out_data_hd;
3353 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3354 	struct mode_header_grp2		*sense_mhp;
3355 	uchar_t				*sense_page;
3356 	caddr_t				buf;
3357 	int				bd_len;
3358 	int				status;
3359 	struct sd_lun			*un;
3360 
3361 	ASSERT(ssc != NULL);
3362 	un = ssc->ssc_un;
3363 	ASSERT(un != NULL);
3364 	ASSERT(mutex_owned(SD_MUTEX(un)));
3365 
3366 	/*
3367 	 * Initialize the writable media to false, if configuration info.
3368 	 * tells us otherwise then only we will set it.
3369 	 */
3370 	un->un_f_mmc_writable_media = FALSE;
3371 	mutex_exit(SD_MUTEX(un));
3372 
3373 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3374 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3375 
3376 	rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf, SENSE_LENGTH,
3377 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3378 
3379 	if (rtn != 0)
3380 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3381 
3382 	mutex_enter(SD_MUTEX(un));
3383 	if (rtn == 0) {
3384 		/*
3385 		 * We have good information, check for writable DVD.
3386 		 */
3387 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3388 			un->un_f_mmc_writable_media = TRUE;
3389 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3390 			kmem_free(rqbuf, SENSE_LENGTH);
3391 			return;
3392 		}
3393 	}
3394 
3395 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3396 	kmem_free(rqbuf, SENSE_LENGTH);
3397 
3398 	/*
3399 	 * Determine if this is a RRD type device.
3400 	 */
3401 	mutex_exit(SD_MUTEX(un));
3402 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3403 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3404 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3405 
3406 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3407 
3408 	mutex_enter(SD_MUTEX(un));
3409 	if (status != 0) {
3410 		/* command failed; just return */
3411 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3412 		return;
3413 	}
3414 
3415 	/* Get to the page data */
3416 	sense_mhp = (struct mode_header_grp2 *)buf;
3417 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3418 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3419 		/*
3420 		 * We did not get back the expected block descriptor length so
3421 		 * we cannot check the mode page.
3422 		 */
3423 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3424 		    "sd_check_for_writable_cd: Mode Sense returned "
3425 		    "invalid block descriptor length\n");
3426 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3427 		return;
3428 	}
3429 
3430 	/*
3431 	 * If the device presents DVD or CD capabilities in the mode
3432 	 * page, we can return here since a RRD device will not have
3433 	 * these capabilities.
3434 	 */
3435 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3436 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3437 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3438 		return;
3439 	}
3440 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3441 
3442 	/*
3443 	 * If un->un_f_mmc_writable_media is still FALSE,
3444 	 * check for RRD type media.  A RRD device is identified
3445 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3446 	 */
3447 	mutex_exit(SD_MUTEX(un));
3448 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3449 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3450 
3451 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3452 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3453 	    RANDOM_WRITABLE, path_flag);
3454 
3455 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3456 	if (rtn != 0) {
3457 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3458 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3459 		mutex_enter(SD_MUTEX(un));
3460 		return;
3461 	}
3462 
3463 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3464 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3465 
3466 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3467 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3468 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3469 
3470 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3471 	mutex_enter(SD_MUTEX(un));
3472 	if (rtn == 0) {
3473 		/*
3474 		 * We have good information, check for random writable
3475 		 * and hardware defect features as current.
3476 		 */
3477 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3478 		    (out_data_rw[10] & 0x1) &&
3479 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3480 		    (out_data_hd[10] & 0x1)) {
3481 			un->un_f_mmc_writable_media = TRUE;
3482 		}
3483 	}
3484 
3485 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3486 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3487 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3488 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3489 }
3490 
3491 /*
3492  *    Function: sd_read_unit_properties
3493  *
3494  * Description: The following implements a property lookup mechanism.
3495  *		Properties for particular disks (keyed on vendor, model
3496  *		and rev numbers) are sought in the sd.conf file via
3497  *		sd_process_sdconf_file(), and if not found there, are
3498  *		looked for in a list hardcoded in this driver via
3499  *		sd_process_sdconf_table() Once located the properties
3500  *		are used to update the driver unit structure.
3501  *
3502  *   Arguments: un - driver soft state (unit) structure
3503  */
3504 
3505 static void
3506 sd_read_unit_properties(struct sd_lun *un)
3507 {
3508 	/*
3509 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3510 	 * the "sd-config-list" property (from the sd.conf file) or if
3511 	 * there was not a match for the inquiry vid/pid. If this event
3512 	 * occurs the static driver configuration table is searched for
3513 	 * a match.
3514 	 */
3515 	ASSERT(un != NULL);
3516 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3517 		sd_process_sdconf_table(un);
3518 	}
3519 
3520 	/* check for LSI device */
3521 	sd_is_lsi(un);
3522 
3523 
3524 }
3525 
3526 
3527 /*
3528  *    Function: sd_process_sdconf_file
3529  *
3530  * Description: Use ddi_prop_lookup(9F) to obtain the properties from the
3531  *		driver's config file (ie, sd.conf) and update the driver
3532  *		soft state structure accordingly.
3533  *
3534  *   Arguments: un - driver soft state (unit) structure
3535  *
3536  * Return Code: SD_SUCCESS - The properties were successfully set according
3537  *			     to the driver configuration file.
3538  *		SD_FAILURE - The driver config list was not obtained or
3539  *			     there was no vid/pid match. This indicates that
3540  *			     the static config table should be used.
3541  *
3542  * The config file has a property, "sd-config-list". Currently we support
3543  * two kinds of formats. For both formats, the value of this property
3544  * is a list of duplets:
3545  *
3546  *  sd-config-list=
3547  *	<duplet>,
3548  *	[,<duplet>]*;
3549  *
3550  * For the improved format, where
3551  *
3552  *     <duplet>:= "<vid+pid>","<tunable-list>"
3553  *
3554  * and
3555  *
3556  *     <tunable-list>:=   <tunable> [, <tunable> ]*;
3557  *     <tunable> =        <name> : <value>
3558  *
3559  * The <vid+pid> is the string that is returned by the target device on a
3560  * SCSI inquiry command, the <tunable-list> contains one or more tunables
3561  * to apply to all target devices with the specified <vid+pid>.
3562  *
3563  * Each <tunable> is a "<name> : <value>" pair.
3564  *
3565  * For the old format, the structure of each duplet is as follows:
3566  *
3567  *  <duplet>:= "<vid+pid>","<data-property-name_list>"
3568  *
3569  * The first entry of the duplet is the device ID string (the concatenated
3570  * vid & pid; not to be confused with a device_id).  This is defined in
3571  * the same way as in the sd_disk_table.
3572  *
3573  * The second part of the duplet is a string that identifies a
3574  * data-property-name-list. The data-property-name-list is defined as
3575  * follows:
3576  *
3577  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3578  *
3579  * The syntax of <data-property-name> depends on the <version> field.
3580  *
3581  * If version = SD_CONF_VERSION_1 we have the following syntax:
3582  *
3583  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3584  *
3585  * where the prop0 value will be used to set prop0 if bit0 set in the
3586  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3587  *
3588  */
3589 
3590 static int
3591 sd_process_sdconf_file(struct sd_lun *un)
3592 {
3593 	char	**config_list = NULL;
3594 	uint_t	nelements;
3595 	char	*vidptr;
3596 	int	vidlen;
3597 	char	*dnlist_ptr;
3598 	char	*dataname_ptr;
3599 	char	*dataname_lasts;
3600 	int	*data_list = NULL;
3601 	uint_t	data_list_len;
3602 	int	rval = SD_FAILURE;
3603 	int	i;
3604 
3605 	ASSERT(un != NULL);
3606 
3607 	/* Obtain the configuration list associated with the .conf file */
3608 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, SD_DEVINFO(un),
3609 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, sd_config_list,
3610 	    &config_list, &nelements) != DDI_PROP_SUCCESS) {
3611 		return (SD_FAILURE);
3612 	}
3613 
3614 	/*
3615 	 * Compare vids in each duplet to the inquiry vid - if a match is
3616 	 * made, get the data value and update the soft state structure
3617 	 * accordingly.
3618 	 *
3619 	 * Each duplet should show as a pair of strings, return SD_FAILURE
3620 	 * otherwise.
3621 	 */
3622 	if (nelements & 1) {
3623 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3624 		    "sd-config-list should show as pairs of strings.\n");
3625 		if (config_list)
3626 			ddi_prop_free(config_list);
3627 		return (SD_FAILURE);
3628 	}
3629 
3630 	for (i = 0; i < nelements; i += 2) {
3631 		/*
3632 		 * Note: The assumption here is that each vid entry is on
3633 		 * a unique line from its associated duplet.
3634 		 */
3635 		vidptr = config_list[i];
3636 		vidlen = (int)strlen(vidptr);
3637 		if ((vidlen == 0) ||
3638 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3639 			continue;
3640 		}
3641 
3642 		/*
3643 		 * dnlist contains 1 or more blank separated
3644 		 * data-property-name entries
3645 		 */
3646 		dnlist_ptr = config_list[i + 1];
3647 
3648 		if (strchr(dnlist_ptr, ':') != NULL) {
3649 			/*
3650 			 * Decode the improved format sd-config-list.
3651 			 */
3652 			sd_nvpair_str_decode(un, dnlist_ptr);
3653 		} else {
3654 			/*
3655 			 * The old format sd-config-list, loop through all
3656 			 * data-property-name entries in the
3657 			 * data-property-name-list
3658 			 * setting the properties for each.
3659 			 */
3660 			for (dataname_ptr = sd_strtok_r(dnlist_ptr, " \t",
3661 			    &dataname_lasts); dataname_ptr != NULL;
3662 			    dataname_ptr = sd_strtok_r(NULL, " \t",
3663 			    &dataname_lasts)) {
3664 				int version;
3665 
3666 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3667 				    "sd_process_sdconf_file: disk:%s, "
3668 				    "data:%s\n", vidptr, dataname_ptr);
3669 
3670 				/* Get the data list */
3671 				if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY,
3672 				    SD_DEVINFO(un), 0, dataname_ptr, &data_list,
3673 				    &data_list_len) != DDI_PROP_SUCCESS) {
3674 					SD_INFO(SD_LOG_ATTACH_DETACH, un,
3675 					    "sd_process_sdconf_file: data "
3676 					    "property (%s) has no value\n",
3677 					    dataname_ptr);
3678 					continue;
3679 				}
3680 
3681 				version = data_list[0];
3682 
3683 				if (version == SD_CONF_VERSION_1) {
3684 					sd_tunables values;
3685 
3686 					/* Set the properties */
3687 					if (sd_chk_vers1_data(un, data_list[1],
3688 					    &data_list[2], data_list_len,
3689 					    dataname_ptr) == SD_SUCCESS) {
3690 						sd_get_tunables_from_conf(un,
3691 						    data_list[1], &data_list[2],
3692 						    &values);
3693 						sd_set_vers1_properties(un,
3694 						    data_list[1], &values);
3695 						rval = SD_SUCCESS;
3696 					} else {
3697 						rval = SD_FAILURE;
3698 					}
3699 				} else {
3700 					scsi_log(SD_DEVINFO(un), sd_label,
3701 					    CE_WARN, "data property %s version "
3702 					    "0x%x is invalid.",
3703 					    dataname_ptr, version);
3704 					rval = SD_FAILURE;
3705 				}
3706 				if (data_list)
3707 					ddi_prop_free(data_list);
3708 			}
3709 		}
3710 	}
3711 
3712 	/* free up the memory allocated by ddi_prop_lookup_string_array(). */
3713 	if (config_list) {
3714 		ddi_prop_free(config_list);
3715 	}
3716 
3717 	return (rval);
3718 }
3719 
3720 /*
3721  *    Function: sd_nvpair_str_decode()
3722  *
3723  * Description: Parse the improved format sd-config-list to get
3724  *    each entry of tunable, which includes a name-value pair.
3725  *    Then call sd_set_properties() to set the property.
3726  *
3727  *   Arguments: un - driver soft state (unit) structure
3728  *    nvpair_str - the tunable list
3729  */
3730 static void
3731 sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str)
3732 {
3733 	char	*nv, *name, *value, *token;
3734 	char	*nv_lasts, *v_lasts, *x_lasts;
3735 
3736 	for (nv = sd_strtok_r(nvpair_str, ",", &nv_lasts); nv != NULL;
3737 	    nv = sd_strtok_r(NULL, ",", &nv_lasts)) {
3738 		token = sd_strtok_r(nv, ":", &v_lasts);
3739 		name  = sd_strtok_r(token, " \t", &x_lasts);
3740 		token = sd_strtok_r(NULL, ":", &v_lasts);
3741 		value = sd_strtok_r(token, " \t", &x_lasts);
3742 		if (name == NULL || value == NULL) {
3743 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3744 			    "sd_nvpair_str_decode: "
3745 			    "name or value is not valid!\n");
3746 		} else {
3747 			sd_set_properties(un, name, value);
3748 		}
3749 	}
3750 }
3751 
3752 /*
3753  *    Function: sd_strtok_r()
3754  *
3755  * Description: This function uses strpbrk and strspn to break
3756  *    string into tokens on sequentially subsequent calls. Return
3757  *    NULL when no non-separator characters remain. The first
3758  *    argument is NULL for subsequent calls.
3759  */
3760 static char *
3761 sd_strtok_r(char *string, const char *sepset, char **lasts)
3762 {
3763 	char	*q, *r;
3764 
3765 	/* First or subsequent call */
3766 	if (string == NULL)
3767 		string = *lasts;
3768 
3769 	if (string == NULL)
3770 		return (NULL);
3771 
3772 	/* Skip leading separators */
3773 	q = string + strspn(string, sepset);
3774 
3775 	if (*q == '\0')
3776 		return (NULL);
3777 
3778 	if ((r = strpbrk(q, sepset)) == NULL)
3779 		*lasts = NULL;
3780 	else {
3781 		*r = '\0';
3782 		*lasts = r + 1;
3783 	}
3784 	return (q);
3785 }
3786 
3787 /*
3788  *    Function: sd_set_properties()
3789  *
3790  * Description: Set device properties based on the improved
3791  *    format sd-config-list.
3792  *
3793  *   Arguments: un - driver soft state (unit) structure
3794  *    name  - supported tunable name
3795  *    value - tunable value
3796  */
3797 static void
3798 sd_set_properties(struct sd_lun *un, char *name, char *value)
3799 {
3800 	char	*endptr = NULL;
3801 	long	val = 0;
3802 
3803 	if (strcasecmp(name, "cache-nonvolatile") == 0) {
3804 		if (strcasecmp(value, "true") == 0) {
3805 			un->un_f_suppress_cache_flush = TRUE;
3806 		} else if (strcasecmp(value, "false") == 0) {
3807 			un->un_f_suppress_cache_flush = FALSE;
3808 		} else {
3809 			goto value_invalid;
3810 		}
3811 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3812 		    "suppress_cache_flush flag set to %d\n",
3813 		    un->un_f_suppress_cache_flush);
3814 		return;
3815 	}
3816 
3817 	if (strcasecmp(name, "controller-type") == 0) {
3818 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3819 			un->un_ctype = val;
3820 		} else {
3821 			goto value_invalid;
3822 		}
3823 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3824 		    "ctype set to %d\n", un->un_ctype);
3825 		return;
3826 	}
3827 
3828 	if (strcasecmp(name, "delay-busy") == 0) {
3829 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3830 			un->un_busy_timeout = drv_usectohz(val / 1000);
3831 		} else {
3832 			goto value_invalid;
3833 		}
3834 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3835 		    "busy_timeout set to %d\n", un->un_busy_timeout);
3836 		return;
3837 	}
3838 
3839 	if (strcasecmp(name, "disksort") == 0) {
3840 		if (strcasecmp(value, "true") == 0) {
3841 			un->un_f_disksort_disabled = FALSE;
3842 		} else if (strcasecmp(value, "false") == 0) {
3843 			un->un_f_disksort_disabled = TRUE;
3844 		} else {
3845 			goto value_invalid;
3846 		}
3847 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3848 		    "disksort disabled flag set to %d\n",
3849 		    un->un_f_disksort_disabled);
3850 		return;
3851 	}
3852 
3853 	if (strcasecmp(name, "timeout-releasereservation") == 0) {
3854 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3855 			un->un_reserve_release_time = val;
3856 		} else {
3857 			goto value_invalid;
3858 		}
3859 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3860 		    "reservation release timeout set to %d\n",
3861 		    un->un_reserve_release_time);
3862 		return;
3863 	}
3864 
3865 	if (strcasecmp(name, "reset-lun") == 0) {
3866 		if (strcasecmp(value, "true") == 0) {
3867 			un->un_f_lun_reset_enabled = TRUE;
3868 		} else if (strcasecmp(value, "false") == 0) {
3869 			un->un_f_lun_reset_enabled = FALSE;
3870 		} else {
3871 			goto value_invalid;
3872 		}
3873 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3874 		    "lun reset enabled flag set to %d\n",
3875 		    un->un_f_lun_reset_enabled);
3876 		return;
3877 	}
3878 
3879 	if (strcasecmp(name, "retries-busy") == 0) {
3880 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3881 			un->un_busy_retry_count = val;
3882 		} else {
3883 			goto value_invalid;
3884 		}
3885 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3886 		    "busy retry count set to %d\n", un->un_busy_retry_count);
3887 		return;
3888 	}
3889 
3890 	if (strcasecmp(name, "retries-timeout") == 0) {
3891 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3892 			un->un_retry_count = val;
3893 		} else {
3894 			goto value_invalid;
3895 		}
3896 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3897 		    "timeout retry count set to %d\n", un->un_retry_count);
3898 		return;
3899 	}
3900 
3901 	if (strcasecmp(name, "retries-notready") == 0) {
3902 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3903 			un->un_notready_retry_count = val;
3904 		} else {
3905 			goto value_invalid;
3906 		}
3907 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3908 		    "notready retry count set to %d\n",
3909 		    un->un_notready_retry_count);
3910 		return;
3911 	}
3912 
3913 	if (strcasecmp(name, "retries-reset") == 0) {
3914 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3915 			un->un_reset_retry_count = val;
3916 		} else {
3917 			goto value_invalid;
3918 		}
3919 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3920 		    "reset retry count set to %d\n",
3921 		    un->un_reset_retry_count);
3922 		return;
3923 	}
3924 
3925 	if (strcasecmp(name, "throttle-max") == 0) {
3926 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3927 			un->un_saved_throttle = un->un_throttle = val;
3928 		} else {
3929 			goto value_invalid;
3930 		}
3931 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3932 		    "throttle set to %d\n", un->un_throttle);
3933 	}
3934 
3935 	if (strcasecmp(name, "throttle-min") == 0) {
3936 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3937 			un->un_min_throttle = val;
3938 		} else {
3939 			goto value_invalid;
3940 		}
3941 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3942 		    "min throttle set to %d\n", un->un_min_throttle);
3943 	}
3944 
3945 	/*
3946 	 * Validate the throttle values.
3947 	 * If any of the numbers are invalid, set everything to defaults.
3948 	 */
3949 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
3950 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
3951 	    (un->un_min_throttle > un->un_throttle)) {
3952 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
3953 		un->un_min_throttle = sd_min_throttle;
3954 	}
3955 	return;
3956 
3957 value_invalid:
3958 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3959 	    "value of prop %s is invalid\n", name);
3960 }
3961 
3962 /*
3963  *    Function: sd_get_tunables_from_conf()
3964  *
3965  *
3966  *    This function reads the data list from the sd.conf file and pulls
3967  *    the values that can have numeric values as arguments and places
3968  *    the values in the appropriate sd_tunables member.
3969  *    Since the order of the data list members varies across platforms
3970  *    This function reads them from the data list in a platform specific
3971  *    order and places them into the correct sd_tunable member that is
3972  *    consistent across all platforms.
3973  */
3974 static void
3975 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
3976     sd_tunables *values)
3977 {
3978 	int i;
3979 	int mask;
3980 
3981 	bzero(values, sizeof (sd_tunables));
3982 
3983 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3984 
3985 		mask = 1 << i;
3986 		if (mask > flags) {
3987 			break;
3988 		}
3989 
3990 		switch (mask & flags) {
3991 		case 0:	/* This mask bit not set in flags */
3992 			continue;
3993 		case SD_CONF_BSET_THROTTLE:
3994 			values->sdt_throttle = data_list[i];
3995 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3996 			    "sd_get_tunables_from_conf: throttle = %d\n",
3997 			    values->sdt_throttle);
3998 			break;
3999 		case SD_CONF_BSET_CTYPE:
4000 			values->sdt_ctype = data_list[i];
4001 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4002 			    "sd_get_tunables_from_conf: ctype = %d\n",
4003 			    values->sdt_ctype);
4004 			break;
4005 		case SD_CONF_BSET_NRR_COUNT:
4006 			values->sdt_not_rdy_retries = data_list[i];
4007 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4008 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
4009 			    values->sdt_not_rdy_retries);
4010 			break;
4011 		case SD_CONF_BSET_BSY_RETRY_COUNT:
4012 			values->sdt_busy_retries = data_list[i];
4013 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4014 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
4015 			    values->sdt_busy_retries);
4016 			break;
4017 		case SD_CONF_BSET_RST_RETRIES:
4018 			values->sdt_reset_retries = data_list[i];
4019 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4020 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
4021 			    values->sdt_reset_retries);
4022 			break;
4023 		case SD_CONF_BSET_RSV_REL_TIME:
4024 			values->sdt_reserv_rel_time = data_list[i];
4025 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4026 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
4027 			    values->sdt_reserv_rel_time);
4028 			break;
4029 		case SD_CONF_BSET_MIN_THROTTLE:
4030 			values->sdt_min_throttle = data_list[i];
4031 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4032 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
4033 			    values->sdt_min_throttle);
4034 			break;
4035 		case SD_CONF_BSET_DISKSORT_DISABLED:
4036 			values->sdt_disk_sort_dis = data_list[i];
4037 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4038 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
4039 			    values->sdt_disk_sort_dis);
4040 			break;
4041 		case SD_CONF_BSET_LUN_RESET_ENABLED:
4042 			values->sdt_lun_reset_enable = data_list[i];
4043 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4044 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
4045 			    "\n", values->sdt_lun_reset_enable);
4046 			break;
4047 		case SD_CONF_BSET_CACHE_IS_NV:
4048 			values->sdt_suppress_cache_flush = data_list[i];
4049 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4050 			    "sd_get_tunables_from_conf: \
4051 			    suppress_cache_flush = %d"
4052 			    "\n", values->sdt_suppress_cache_flush);
4053 			break;
4054 		}
4055 	}
4056 }
4057 
4058 /*
4059  *    Function: sd_process_sdconf_table
4060  *
4061  * Description: Search the static configuration table for a match on the
4062  *		inquiry vid/pid and update the driver soft state structure
4063  *		according to the table property values for the device.
4064  *
4065  *		The form of a configuration table entry is:
4066  *		  <vid+pid>,<flags>,<property-data>
4067  *		  "SEAGATE ST42400N",1,0x40000,
4068  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
4069  *
4070  *   Arguments: un - driver soft state (unit) structure
4071  */
4072 
4073 static void
4074 sd_process_sdconf_table(struct sd_lun *un)
4075 {
4076 	char	*id = NULL;
4077 	int	table_index;
4078 	int	idlen;
4079 
4080 	ASSERT(un != NULL);
4081 	for (table_index = 0; table_index < sd_disk_table_size;
4082 	    table_index++) {
4083 		id = sd_disk_table[table_index].device_id;
4084 		idlen = strlen(id);
4085 		if (idlen == 0) {
4086 			continue;
4087 		}
4088 
4089 		/*
4090 		 * The static configuration table currently does not
4091 		 * implement version 10 properties. Additionally,
4092 		 * multiple data-property-name entries are not
4093 		 * implemented in the static configuration table.
4094 		 */
4095 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4096 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4097 			    "sd_process_sdconf_table: disk %s\n", id);
4098 			sd_set_vers1_properties(un,
4099 			    sd_disk_table[table_index].flags,
4100 			    sd_disk_table[table_index].properties);
4101 			break;
4102 		}
4103 	}
4104 }
4105 
4106 
4107 /*
4108  *    Function: sd_sdconf_id_match
4109  *
4110  * Description: This local function implements a case sensitive vid/pid
4111  *		comparison as well as the boundary cases of wild card and
4112  *		multiple blanks.
4113  *
4114  *		Note: An implicit assumption made here is that the scsi
4115  *		inquiry structure will always keep the vid, pid and
4116  *		revision strings in consecutive sequence, so they can be
4117  *		read as a single string. If this assumption is not the
4118  *		case, a separate string, to be used for the check, needs
4119  *		to be built with these strings concatenated.
4120  *
4121  *   Arguments: un - driver soft state (unit) structure
4122  *		id - table or config file vid/pid
4123  *		idlen  - length of the vid/pid (bytes)
4124  *
4125  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4126  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4127  */
4128 
4129 static int
4130 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
4131 {
4132 	struct scsi_inquiry	*sd_inq;
4133 	int 			rval = SD_SUCCESS;
4134 
4135 	ASSERT(un != NULL);
4136 	sd_inq = un->un_sd->sd_inq;
4137 	ASSERT(id != NULL);
4138 
4139 	/*
4140 	 * We use the inq_vid as a pointer to a buffer containing the
4141 	 * vid and pid and use the entire vid/pid length of the table
4142 	 * entry for the comparison. This works because the inq_pid
4143 	 * data member follows inq_vid in the scsi_inquiry structure.
4144 	 */
4145 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
4146 		/*
4147 		 * The user id string is compared to the inquiry vid/pid
4148 		 * using a case insensitive comparison and ignoring
4149 		 * multiple spaces.
4150 		 */
4151 		rval = sd_blank_cmp(un, id, idlen);
4152 		if (rval != SD_SUCCESS) {
4153 			/*
4154 			 * User id strings that start and end with a "*"
4155 			 * are a special case. These do not have a
4156 			 * specific vendor, and the product string can
4157 			 * appear anywhere in the 16 byte PID portion of
4158 			 * the inquiry data. This is a simple strstr()
4159 			 * type search for the user id in the inquiry data.
4160 			 */
4161 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
4162 				char	*pidptr = &id[1];
4163 				int	i;
4164 				int	j;
4165 				int	pidstrlen = idlen - 2;
4166 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
4167 				    pidstrlen;
4168 
4169 				if (j < 0) {
4170 					return (SD_FAILURE);
4171 				}
4172 				for (i = 0; i < j; i++) {
4173 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
4174 					    pidptr, pidstrlen) == 0) {
4175 						rval = SD_SUCCESS;
4176 						break;
4177 					}
4178 				}
4179 			}
4180 		}
4181 	}
4182 	return (rval);
4183 }
4184 
4185 
4186 /*
4187  *    Function: sd_blank_cmp
4188  *
4189  * Description: If the id string starts and ends with a space, treat
4190  *		multiple consecutive spaces as equivalent to a single
4191  *		space. For example, this causes a sd_disk_table entry
4192  *		of " NEC CDROM " to match a device's id string of
4193  *		"NEC       CDROM".
4194  *
4195  *		Note: The success exit condition for this routine is if
4196  *		the pointer to the table entry is '\0' and the cnt of
4197  *		the inquiry length is zero. This will happen if the inquiry
4198  *		string returned by the device is padded with spaces to be
4199  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
4200  *		SCSI spec states that the inquiry string is to be padded with
4201  *		spaces.
4202  *
4203  *   Arguments: un - driver soft state (unit) structure
4204  *		id - table or config file vid/pid
4205  *		idlen  - length of the vid/pid (bytes)
4206  *
4207  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4208  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4209  */
4210 
4211 static int
4212 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
4213 {
4214 	char		*p1;
4215 	char		*p2;
4216 	int		cnt;
4217 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
4218 	    sizeof (SD_INQUIRY(un)->inq_pid);
4219 
4220 	ASSERT(un != NULL);
4221 	p2 = un->un_sd->sd_inq->inq_vid;
4222 	ASSERT(id != NULL);
4223 	p1 = id;
4224 
4225 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
4226 		/*
4227 		 * Note: string p1 is terminated by a NUL but string p2
4228 		 * isn't.  The end of p2 is determined by cnt.
4229 		 */
4230 		for (;;) {
4231 			/* skip over any extra blanks in both strings */
4232 			while ((*p1 != '\0') && (*p1 == ' ')) {
4233 				p1++;
4234 			}
4235 			while ((cnt != 0) && (*p2 == ' ')) {
4236 				p2++;
4237 				cnt--;
4238 			}
4239 
4240 			/* compare the two strings */
4241 			if ((cnt == 0) ||
4242 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
4243 				break;
4244 			}
4245 			while ((cnt > 0) &&
4246 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
4247 				p1++;
4248 				p2++;
4249 				cnt--;
4250 			}
4251 		}
4252 	}
4253 
4254 	/* return SD_SUCCESS if both strings match */
4255 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
4256 }
4257 
4258 
4259 /*
4260  *    Function: sd_chk_vers1_data
4261  *
4262  * Description: Verify the version 1 device properties provided by the
4263  *		user via the configuration file
4264  *
4265  *   Arguments: un	     - driver soft state (unit) structure
4266  *		flags	     - integer mask indicating properties to be set
4267  *		prop_list    - integer list of property values
4268  *		list_len     - number of the elements
4269  *
4270  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
4271  *		SD_FAILURE - Indicates the user provided data is invalid
4272  */
4273 
4274 static int
4275 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
4276     int list_len, char *dataname_ptr)
4277 {
4278 	int i;
4279 	int mask = 1;
4280 	int index = 0;
4281 
4282 	ASSERT(un != NULL);
4283 
4284 	/* Check for a NULL property name and list */
4285 	if (dataname_ptr == NULL) {
4286 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4287 		    "sd_chk_vers1_data: NULL data property name.");
4288 		return (SD_FAILURE);
4289 	}
4290 	if (prop_list == NULL) {
4291 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4292 		    "sd_chk_vers1_data: %s NULL data property list.",
4293 		    dataname_ptr);
4294 		return (SD_FAILURE);
4295 	}
4296 
4297 	/* Display a warning if undefined bits are set in the flags */
4298 	if (flags & ~SD_CONF_BIT_MASK) {
4299 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4300 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
4301 		    "Properties not set.",
4302 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
4303 		return (SD_FAILURE);
4304 	}
4305 
4306 	/*
4307 	 * Verify the length of the list by identifying the highest bit set
4308 	 * in the flags and validating that the property list has a length
4309 	 * up to the index of this bit.
4310 	 */
4311 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4312 		if (flags & mask) {
4313 			index++;
4314 		}
4315 		mask = 1 << i;
4316 	}
4317 	if (list_len < (index + 2)) {
4318 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4319 		    "sd_chk_vers1_data: "
4320 		    "Data property list %s size is incorrect. "
4321 		    "Properties not set.", dataname_ptr);
4322 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
4323 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
4324 		return (SD_FAILURE);
4325 	}
4326 	return (SD_SUCCESS);
4327 }
4328 
4329 
4330 /*
4331  *    Function: sd_set_vers1_properties
4332  *
4333  * Description: Set version 1 device properties based on a property list
4334  *		retrieved from the driver configuration file or static
4335  *		configuration table. Version 1 properties have the format:
4336  *
4337  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
4338  *
4339  *		where the prop0 value will be used to set prop0 if bit0
4340  *		is set in the flags
4341  *
4342  *   Arguments: un	     - driver soft state (unit) structure
4343  *		flags	     - integer mask indicating properties to be set
4344  *		prop_list    - integer list of property values
4345  */
4346 
4347 static void
4348 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4349 {
4350 	ASSERT(un != NULL);
4351 
4352 	/*
4353 	 * Set the flag to indicate cache is to be disabled. An attempt
4354 	 * to disable the cache via sd_cache_control() will be made
4355 	 * later during attach once the basic initialization is complete.
4356 	 */
4357 	if (flags & SD_CONF_BSET_NOCACHE) {
4358 		un->un_f_opt_disable_cache = TRUE;
4359 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4360 		    "sd_set_vers1_properties: caching disabled flag set\n");
4361 	}
4362 
4363 	/* CD-specific configuration parameters */
4364 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4365 		un->un_f_cfg_playmsf_bcd = TRUE;
4366 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4367 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4368 	}
4369 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4370 		un->un_f_cfg_readsub_bcd = TRUE;
4371 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4372 		    "sd_set_vers1_properties: readsub_bcd set\n");
4373 	}
4374 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4375 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4376 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4377 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4378 	}
4379 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4380 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4381 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4382 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4383 	}
4384 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4385 		un->un_f_cfg_no_read_header = TRUE;
4386 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4387 		    "sd_set_vers1_properties: no_read_header set\n");
4388 	}
4389 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4390 		un->un_f_cfg_read_cd_xd4 = TRUE;
4391 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4392 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4393 	}
4394 
4395 	/* Support for devices which do not have valid/unique serial numbers */
4396 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4397 		un->un_f_opt_fab_devid = TRUE;
4398 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4399 		    "sd_set_vers1_properties: fab_devid bit set\n");
4400 	}
4401 
4402 	/* Support for user throttle configuration */
4403 	if (flags & SD_CONF_BSET_THROTTLE) {
4404 		ASSERT(prop_list != NULL);
4405 		un->un_saved_throttle = un->un_throttle =
4406 		    prop_list->sdt_throttle;
4407 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4408 		    "sd_set_vers1_properties: throttle set to %d\n",
4409 		    prop_list->sdt_throttle);
4410 	}
4411 
4412 	/* Set the per disk retry count according to the conf file or table. */
4413 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4414 		ASSERT(prop_list != NULL);
4415 		if (prop_list->sdt_not_rdy_retries) {
4416 			un->un_notready_retry_count =
4417 			    prop_list->sdt_not_rdy_retries;
4418 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4419 			    "sd_set_vers1_properties: not ready retry count"
4420 			    " set to %d\n", un->un_notready_retry_count);
4421 		}
4422 	}
4423 
4424 	/* The controller type is reported for generic disk driver ioctls */
4425 	if (flags & SD_CONF_BSET_CTYPE) {
4426 		ASSERT(prop_list != NULL);
4427 		switch (prop_list->sdt_ctype) {
4428 		case CTYPE_CDROM:
4429 			un->un_ctype = prop_list->sdt_ctype;
4430 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4431 			    "sd_set_vers1_properties: ctype set to "
4432 			    "CTYPE_CDROM\n");
4433 			break;
4434 		case CTYPE_CCS:
4435 			un->un_ctype = prop_list->sdt_ctype;
4436 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4437 			    "sd_set_vers1_properties: ctype set to "
4438 			    "CTYPE_CCS\n");
4439 			break;
4440 		case CTYPE_ROD:		/* RW optical */
4441 			un->un_ctype = prop_list->sdt_ctype;
4442 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4443 			    "sd_set_vers1_properties: ctype set to "
4444 			    "CTYPE_ROD\n");
4445 			break;
4446 		default:
4447 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4448 			    "sd_set_vers1_properties: Could not set "
4449 			    "invalid ctype value (%d)",
4450 			    prop_list->sdt_ctype);
4451 		}
4452 	}
4453 
4454 	/* Purple failover timeout */
4455 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4456 		ASSERT(prop_list != NULL);
4457 		un->un_busy_retry_count =
4458 		    prop_list->sdt_busy_retries;
4459 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4460 		    "sd_set_vers1_properties: "
4461 		    "busy retry count set to %d\n",
4462 		    un->un_busy_retry_count);
4463 	}
4464 
4465 	/* Purple reset retry count */
4466 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4467 		ASSERT(prop_list != NULL);
4468 		un->un_reset_retry_count =
4469 		    prop_list->sdt_reset_retries;
4470 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4471 		    "sd_set_vers1_properties: "
4472 		    "reset retry count set to %d\n",
4473 		    un->un_reset_retry_count);
4474 	}
4475 
4476 	/* Purple reservation release timeout */
4477 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4478 		ASSERT(prop_list != NULL);
4479 		un->un_reserve_release_time =
4480 		    prop_list->sdt_reserv_rel_time;
4481 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4482 		    "sd_set_vers1_properties: "
4483 		    "reservation release timeout set to %d\n",
4484 		    un->un_reserve_release_time);
4485 	}
4486 
4487 	/*
4488 	 * Driver flag telling the driver to verify that no commands are pending
4489 	 * for a device before issuing a Test Unit Ready. This is a workaround
4490 	 * for a firmware bug in some Seagate eliteI drives.
4491 	 */
4492 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4493 		un->un_f_cfg_tur_check = TRUE;
4494 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4495 		    "sd_set_vers1_properties: tur queue check set\n");
4496 	}
4497 
4498 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4499 		un->un_min_throttle = prop_list->sdt_min_throttle;
4500 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4501 		    "sd_set_vers1_properties: min throttle set to %d\n",
4502 		    un->un_min_throttle);
4503 	}
4504 
4505 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4506 		un->un_f_disksort_disabled =
4507 		    (prop_list->sdt_disk_sort_dis != 0) ?
4508 		    TRUE : FALSE;
4509 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4510 		    "sd_set_vers1_properties: disksort disabled "
4511 		    "flag set to %d\n",
4512 		    prop_list->sdt_disk_sort_dis);
4513 	}
4514 
4515 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4516 		un->un_f_lun_reset_enabled =
4517 		    (prop_list->sdt_lun_reset_enable != 0) ?
4518 		    TRUE : FALSE;
4519 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4520 		    "sd_set_vers1_properties: lun reset enabled "
4521 		    "flag set to %d\n",
4522 		    prop_list->sdt_lun_reset_enable);
4523 	}
4524 
4525 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4526 		un->un_f_suppress_cache_flush =
4527 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4528 		    TRUE : FALSE;
4529 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4530 		    "sd_set_vers1_properties: suppress_cache_flush "
4531 		    "flag set to %d\n",
4532 		    prop_list->sdt_suppress_cache_flush);
4533 	}
4534 
4535 	/*
4536 	 * Validate the throttle values.
4537 	 * If any of the numbers are invalid, set everything to defaults.
4538 	 */
4539 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4540 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4541 	    (un->un_min_throttle > un->un_throttle)) {
4542 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4543 		un->un_min_throttle = sd_min_throttle;
4544 	}
4545 }
4546 
4547 /*
4548  *   Function: sd_is_lsi()
4549  *
4550  *   Description: Check for lsi devices, step through the static device
4551  *	table to match vid/pid.
4552  *
4553  *   Args: un - ptr to sd_lun
4554  *
4555  *   Notes:  When creating new LSI property, need to add the new LSI property
4556  *		to this function.
4557  */
4558 static void
4559 sd_is_lsi(struct sd_lun *un)
4560 {
4561 	char	*id = NULL;
4562 	int	table_index;
4563 	int	idlen;
4564 	void	*prop;
4565 
4566 	ASSERT(un != NULL);
4567 	for (table_index = 0; table_index < sd_disk_table_size;
4568 	    table_index++) {
4569 		id = sd_disk_table[table_index].device_id;
4570 		idlen = strlen(id);
4571 		if (idlen == 0) {
4572 			continue;
4573 		}
4574 
4575 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4576 			prop = sd_disk_table[table_index].properties;
4577 			if (prop == &lsi_properties ||
4578 			    prop == &lsi_oem_properties ||
4579 			    prop == &lsi_properties_scsi ||
4580 			    prop == &symbios_properties) {
4581 				un->un_f_cfg_is_lsi = TRUE;
4582 			}
4583 			break;
4584 		}
4585 	}
4586 }
4587 
4588 /*
4589  *    Function: sd_get_physical_geometry
4590  *
4591  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4592  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4593  *		target, and use this information to initialize the physical
4594  *		geometry cache specified by pgeom_p.
4595  *
4596  *		MODE SENSE is an optional command, so failure in this case
4597  *		does not necessarily denote an error. We want to use the
4598  *		MODE SENSE commands to derive the physical geometry of the
4599  *		device, but if either command fails, the logical geometry is
4600  *		used as the fallback for disk label geometry in cmlb.
4601  *
4602  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4603  *		have already been initialized for the current target and
4604  *		that the current values be passed as args so that we don't
4605  *		end up ever trying to use -1 as a valid value. This could
4606  *		happen if either value is reset while we're not holding
4607  *		the mutex.
4608  *
4609  *   Arguments: un - driver soft state (unit) structure
4610  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4611  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4612  *			to use the USCSI "direct" chain and bypass the normal
4613  *			command waitq.
4614  *
4615  *     Context: Kernel thread only (can sleep).
4616  */
4617 
4618 static int
4619 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4620 	diskaddr_t capacity, int lbasize, int path_flag)
4621 {
4622 	struct	mode_format	*page3p;
4623 	struct	mode_geometry	*page4p;
4624 	struct	mode_header	*headerp;
4625 	int	sector_size;
4626 	int	nsect;
4627 	int	nhead;
4628 	int	ncyl;
4629 	int	intrlv;
4630 	int	spc;
4631 	diskaddr_t	modesense_capacity;
4632 	int	rpm;
4633 	int	bd_len;
4634 	int	mode_header_length;
4635 	uchar_t	*p3bufp;
4636 	uchar_t	*p4bufp;
4637 	int	cdbsize;
4638 	int 	ret = EIO;
4639 	sd_ssc_t *ssc;
4640 	int	status;
4641 
4642 	ASSERT(un != NULL);
4643 
4644 	if (lbasize == 0) {
4645 		if (ISCD(un)) {
4646 			lbasize = 2048;
4647 		} else {
4648 			lbasize = un->un_sys_blocksize;
4649 		}
4650 	}
4651 	pgeom_p->g_secsize = (unsigned short)lbasize;
4652 
4653 	/*
4654 	 * If the unit is a cd/dvd drive MODE SENSE page three
4655 	 * and MODE SENSE page four are reserved (see SBC spec
4656 	 * and MMC spec). To prevent soft errors just return
4657 	 * using the default LBA size.
4658 	 */
4659 	if (ISCD(un))
4660 		return (ret);
4661 
4662 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4663 
4664 	/*
4665 	 * Retrieve MODE SENSE page 3 - Format Device Page
4666 	 */
4667 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4668 	ssc = sd_ssc_init(un);
4669 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p3bufp,
4670 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag);
4671 	if (status != 0) {
4672 		SD_ERROR(SD_LOG_COMMON, un,
4673 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4674 		goto page3_exit;
4675 	}
4676 
4677 	/*
4678 	 * Determine size of Block Descriptors in order to locate the mode
4679 	 * page data.  ATAPI devices return 0, SCSI devices should return
4680 	 * MODE_BLK_DESC_LENGTH.
4681 	 */
4682 	headerp = (struct mode_header *)p3bufp;
4683 	if (un->un_f_cfg_is_atapi == TRUE) {
4684 		struct mode_header_grp2 *mhp =
4685 		    (struct mode_header_grp2 *)headerp;
4686 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4687 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4688 	} else {
4689 		mode_header_length = MODE_HEADER_LENGTH;
4690 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4691 	}
4692 
4693 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4694 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4695 		    "sd_get_physical_geometry: received unexpected bd_len "
4696 		    "of %d, page3\n", bd_len);
4697 		status = EIO;
4698 		goto page3_exit;
4699 	}
4700 
4701 	page3p = (struct mode_format *)
4702 	    ((caddr_t)headerp + mode_header_length + bd_len);
4703 
4704 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4705 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4706 		    "sd_get_physical_geometry: mode sense pg3 code mismatch "
4707 		    "%d\n", page3p->mode_page.code);
4708 		status = EIO;
4709 		goto page3_exit;
4710 	}
4711 
4712 	/*
4713 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4714 	 * complete successfully; otherwise, revert to the logical geometry.
4715 	 * So, we need to save everything in temporary variables.
4716 	 */
4717 	sector_size = BE_16(page3p->data_bytes_sect);
4718 
4719 	/*
4720 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4721 	 */
4722 	if (sector_size == 0) {
4723 		sector_size = un->un_sys_blocksize;
4724 	} else {
4725 		sector_size &= ~(un->un_sys_blocksize - 1);
4726 	}
4727 
4728 	nsect  = BE_16(page3p->sect_track);
4729 	intrlv = BE_16(page3p->interleave);
4730 
4731 	SD_INFO(SD_LOG_COMMON, un,
4732 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4733 	SD_INFO(SD_LOG_COMMON, un,
4734 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4735 	    page3p->mode_page.code, nsect, sector_size);
4736 	SD_INFO(SD_LOG_COMMON, un,
4737 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4738 	    BE_16(page3p->track_skew),
4739 	    BE_16(page3p->cylinder_skew));
4740 
4741 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
4742 
4743 	/*
4744 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4745 	 */
4746 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4747 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p4bufp,
4748 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag);
4749 	if (status != 0) {
4750 		SD_ERROR(SD_LOG_COMMON, un,
4751 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4752 		goto page4_exit;
4753 	}
4754 
4755 	/*
4756 	 * Determine size of Block Descriptors in order to locate the mode
4757 	 * page data.  ATAPI devices return 0, SCSI devices should return
4758 	 * MODE_BLK_DESC_LENGTH.
4759 	 */
4760 	headerp = (struct mode_header *)p4bufp;
4761 	if (un->un_f_cfg_is_atapi == TRUE) {
4762 		struct mode_header_grp2 *mhp =
4763 		    (struct mode_header_grp2 *)headerp;
4764 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4765 	} else {
4766 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4767 	}
4768 
4769 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4770 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4771 		    "sd_get_physical_geometry: received unexpected bd_len of "
4772 		    "%d, page4\n", bd_len);
4773 		status = EIO;
4774 		goto page4_exit;
4775 	}
4776 
4777 	page4p = (struct mode_geometry *)
4778 	    ((caddr_t)headerp + mode_header_length + bd_len);
4779 
4780 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4781 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4782 		    "sd_get_physical_geometry: mode sense pg4 code mismatch "
4783 		    "%d\n", page4p->mode_page.code);
4784 		status = EIO;
4785 		goto page4_exit;
4786 	}
4787 
4788 	/*
4789 	 * Stash the data now, after we know that both commands completed.
4790 	 */
4791 
4792 
4793 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4794 	spc   = nhead * nsect;
4795 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4796 	rpm   = BE_16(page4p->rpm);
4797 
4798 	modesense_capacity = spc * ncyl;
4799 
4800 	SD_INFO(SD_LOG_COMMON, un,
4801 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
4802 	SD_INFO(SD_LOG_COMMON, un,
4803 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
4804 	SD_INFO(SD_LOG_COMMON, un,
4805 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
4806 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
4807 	    (void *)pgeom_p, capacity);
4808 
4809 	/*
4810 	 * Compensate if the drive's geometry is not rectangular, i.e.,
4811 	 * the product of C * H * S returned by MODE SENSE >= that returned
4812 	 * by read capacity. This is an idiosyncrasy of the original x86
4813 	 * disk subsystem.
4814 	 */
4815 	if (modesense_capacity >= capacity) {
4816 		SD_INFO(SD_LOG_COMMON, un,
4817 		    "sd_get_physical_geometry: adjusting acyl; "
4818 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
4819 		    (modesense_capacity - capacity + spc - 1) / spc);
4820 		if (sector_size != 0) {
4821 			/* 1243403: NEC D38x7 drives don't support sec size */
4822 			pgeom_p->g_secsize = (unsigned short)sector_size;
4823 		}
4824 		pgeom_p->g_nsect    = (unsigned short)nsect;
4825 		pgeom_p->g_nhead    = (unsigned short)nhead;
4826 		pgeom_p->g_capacity = capacity;
4827 		pgeom_p->g_acyl	    =
4828 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
4829 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
4830 	}
4831 
4832 	pgeom_p->g_rpm    = (unsigned short)rpm;
4833 	pgeom_p->g_intrlv = (unsigned short)intrlv;
4834 	ret = 0;
4835 
4836 	SD_INFO(SD_LOG_COMMON, un,
4837 	    "sd_get_physical_geometry: mode sense geometry:\n");
4838 	SD_INFO(SD_LOG_COMMON, un,
4839 	    "   nsect: %d; sector size: %d; interlv: %d\n",
4840 	    nsect, sector_size, intrlv);
4841 	SD_INFO(SD_LOG_COMMON, un,
4842 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
4843 	    nhead, ncyl, rpm, modesense_capacity);
4844 	SD_INFO(SD_LOG_COMMON, un,
4845 	    "sd_get_physical_geometry: (cached)\n");
4846 	SD_INFO(SD_LOG_COMMON, un,
4847 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
4848 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
4849 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
4850 	SD_INFO(SD_LOG_COMMON, un,
4851 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
4852 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
4853 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
4854 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
4855 
4856 page4_exit:
4857 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
4858 
4859 page3_exit:
4860 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
4861 
4862 	if (status != 0) {
4863 		if (status == EIO) {
4864 			/*
4865 			 * Some disks do not support mode sense(6), we
4866 			 * should ignore this kind of error(sense key is
4867 			 * 0x5 - illegal request).
4868 			 */
4869 			uint8_t *sensep;
4870 			int senlen;
4871 
4872 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
4873 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
4874 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
4875 
4876 			if (senlen > 0 &&
4877 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
4878 				sd_ssc_assessment(ssc,
4879 				    SD_FMT_IGNORE_COMPROMISE);
4880 			} else {
4881 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
4882 			}
4883 		} else {
4884 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
4885 		}
4886 	}
4887 	sd_ssc_fini(ssc);
4888 	return (ret);
4889 }
4890 
4891 /*
4892  *    Function: sd_get_virtual_geometry
4893  *
4894  * Description: Ask the controller to tell us about the target device.
4895  *
4896  *   Arguments: un - pointer to softstate
4897  *		capacity - disk capacity in #blocks
4898  *		lbasize - disk block size in bytes
4899  *
4900  *     Context: Kernel thread only
4901  */
4902 
4903 static int
4904 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
4905     diskaddr_t capacity, int lbasize)
4906 {
4907 	uint_t	geombuf;
4908 	int	spc;
4909 
4910 	ASSERT(un != NULL);
4911 
4912 	/* Set sector size, and total number of sectors */
4913 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
4914 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
4915 
4916 	/* Let the HBA tell us its geometry */
4917 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
4918 
4919 	/* A value of -1 indicates an undefined "geometry" property */
4920 	if (geombuf == (-1)) {
4921 		return (EINVAL);
4922 	}
4923 
4924 	/* Initialize the logical geometry cache. */
4925 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
4926 	lgeom_p->g_nsect   = geombuf & 0xffff;
4927 	lgeom_p->g_secsize = un->un_sys_blocksize;
4928 
4929 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
4930 
4931 	/*
4932 	 * Note: The driver originally converted the capacity value from
4933 	 * target blocks to system blocks. However, the capacity value passed
4934 	 * to this routine is already in terms of system blocks (this scaling
4935 	 * is done when the READ CAPACITY command is issued and processed).
4936 	 * This 'error' may have gone undetected because the usage of g_ncyl
4937 	 * (which is based upon g_capacity) is very limited within the driver
4938 	 */
4939 	lgeom_p->g_capacity = capacity;
4940 
4941 	/*
4942 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
4943 	 * hba may return zero values if the device has been removed.
4944 	 */
4945 	if (spc == 0) {
4946 		lgeom_p->g_ncyl = 0;
4947 	} else {
4948 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
4949 	}
4950 	lgeom_p->g_acyl = 0;
4951 
4952 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
4953 	return (0);
4954 
4955 }
4956 /*
4957  *    Function: sd_update_block_info
4958  *
4959  * Description: Calculate a byte count to sector count bitshift value
4960  *		from sector size.
4961  *
4962  *   Arguments: un: unit struct.
4963  *		lbasize: new target sector size
4964  *		capacity: new target capacity, ie. block count
4965  *
4966  *     Context: Kernel thread context
4967  */
4968 
4969 static void
4970 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
4971 {
4972 	if (lbasize != 0) {
4973 		un->un_tgt_blocksize = lbasize;
4974 		un->un_f_tgt_blocksize_is_valid	= TRUE;
4975 	}
4976 
4977 	if (capacity != 0) {
4978 		un->un_blockcount		= capacity;
4979 		un->un_f_blockcount_is_valid	= TRUE;
4980 	}
4981 }
4982 
4983 
4984 /*
4985  *    Function: sd_register_devid
4986  *
4987  * Description: This routine will obtain the device id information from the
4988  *		target, obtain the serial number, and register the device
4989  *		id with the ddi framework.
4990  *
4991  *   Arguments: devi - the system's dev_info_t for the device.
4992  *		un - driver soft state (unit) structure
4993  *		reservation_flag - indicates if a reservation conflict
4994  *		occurred during attach
4995  *
4996  *     Context: Kernel Thread
4997  */
4998 static void
4999 sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi, int reservation_flag)
5000 {
5001 	int		rval		= 0;
5002 	uchar_t		*inq80		= NULL;
5003 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5004 	size_t		inq80_resid	= 0;
5005 	uchar_t		*inq83		= NULL;
5006 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5007 	size_t		inq83_resid	= 0;
5008 	int		dlen, len;
5009 	char		*sn;
5010 	struct sd_lun	*un;
5011 
5012 	ASSERT(ssc != NULL);
5013 	un = ssc->ssc_un;
5014 	ASSERT(un != NULL);
5015 	ASSERT(mutex_owned(SD_MUTEX(un)));
5016 	ASSERT((SD_DEVINFO(un)) == devi);
5017 
5018 	/*
5019 	 * If transport has already registered a devid for this target
5020 	 * then that takes precedence over the driver's determination
5021 	 * of the devid.
5022 	 */
5023 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
5024 		ASSERT(un->un_devid);
5025 		return; /* use devid registered by the transport */
5026 	}
5027 
5028 	/*
5029 	 * This is the case of antiquated Sun disk drives that have the
5030 	 * FAB_DEVID property set in the disk_table.  These drives
5031 	 * manage the devid's by storing them in last 2 available sectors
5032 	 * on the drive and have them fabricated by the ddi layer by calling
5033 	 * ddi_devid_init and passing the DEVID_FAB flag.
5034 	 */
5035 	if (un->un_f_opt_fab_devid == TRUE) {
5036 		/*
5037 		 * Depending on EINVAL isn't reliable, since a reserved disk
5038 		 * may result in invalid geometry, so check to make sure a
5039 		 * reservation conflict did not occur during attach.
5040 		 */
5041 		if ((sd_get_devid(ssc) == EINVAL) &&
5042 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5043 			/*
5044 			 * The devid is invalid AND there is no reservation
5045 			 * conflict.  Fabricate a new devid.
5046 			 */
5047 			(void) sd_create_devid(ssc);
5048 		}
5049 
5050 		/* Register the devid if it exists */
5051 		if (un->un_devid != NULL) {
5052 			(void) ddi_devid_register(SD_DEVINFO(un),
5053 			    un->un_devid);
5054 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5055 			    "sd_register_devid: Devid Fabricated\n");
5056 		}
5057 		return;
5058 	}
5059 
5060 	/*
5061 	 * We check the availability of the World Wide Name (0x83) and Unit
5062 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5063 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5064 	 * 0x83 is available, that is the best choice.  Our next choice is
5065 	 * 0x80.  If neither are available, we munge the devid from the device
5066 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5067 	 * to fabricate a devid for non-Sun qualified disks.
5068 	 */
5069 	if (sd_check_vpd_page_support(ssc) == 0) {
5070 		/* collect page 80 data if available */
5071 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5072 
5073 			mutex_exit(SD_MUTEX(un));
5074 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5075 
5076 			rval = sd_send_scsi_INQUIRY(ssc, inq80, inq80_len,
5077 			    0x01, 0x80, &inq80_resid);
5078 
5079 			if (rval != 0) {
5080 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5081 				kmem_free(inq80, inq80_len);
5082 				inq80 = NULL;
5083 				inq80_len = 0;
5084 			} else if (ddi_prop_exists(
5085 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
5086 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
5087 			    INQUIRY_SERIAL_NO) == 0) {
5088 				/*
5089 				 * If we don't already have a serial number
5090 				 * property, do quick verify of data returned
5091 				 * and define property.
5092 				 */
5093 				dlen = inq80_len - inq80_resid;
5094 				len = (size_t)inq80[3];
5095 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
5096 					/*
5097 					 * Ensure sn termination, skip leading
5098 					 * blanks, and create property
5099 					 * 'inquiry-serial-no'.
5100 					 */
5101 					sn = (char *)&inq80[4];
5102 					sn[len] = 0;
5103 					while (*sn && (*sn == ' '))
5104 						sn++;
5105 					if (*sn) {
5106 						(void) ddi_prop_update_string(
5107 						    DDI_DEV_T_NONE,
5108 						    SD_DEVINFO(un),
5109 						    INQUIRY_SERIAL_NO, sn);
5110 					}
5111 				}
5112 			}
5113 			mutex_enter(SD_MUTEX(un));
5114 		}
5115 
5116 		/* collect page 83 data if available */
5117 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5118 			mutex_exit(SD_MUTEX(un));
5119 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
5120 
5121 			rval = sd_send_scsi_INQUIRY(ssc, inq83, inq83_len,
5122 			    0x01, 0x83, &inq83_resid);
5123 
5124 			if (rval != 0) {
5125 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5126 				kmem_free(inq83, inq83_len);
5127 				inq83 = NULL;
5128 				inq83_len = 0;
5129 			}
5130 			mutex_enter(SD_MUTEX(un));
5131 		}
5132 	}
5133 
5134 	/* encode best devid possible based on data available */
5135 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
5136 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
5137 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
5138 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
5139 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
5140 
5141 		/* devid successfully encoded, register devid */
5142 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
5143 
5144 	} else {
5145 		/*
5146 		 * Unable to encode a devid based on data available.
5147 		 * This is not a Sun qualified disk.  Older Sun disk
5148 		 * drives that have the SD_FAB_DEVID property
5149 		 * set in the disk_table and non Sun qualified
5150 		 * disks are treated in the same manner.  These
5151 		 * drives manage the devid's by storing them in
5152 		 * last 2 available sectors on the drive and
5153 		 * have them fabricated by the ddi layer by
5154 		 * calling ddi_devid_init and passing the
5155 		 * DEVID_FAB flag.
5156 		 * Create a fabricate devid only if there's no
5157 		 * fabricate devid existed.
5158 		 */
5159 		if (sd_get_devid(ssc) == EINVAL) {
5160 			(void) sd_create_devid(ssc);
5161 		}
5162 		un->un_f_opt_fab_devid = TRUE;
5163 
5164 		/* Register the devid if it exists */
5165 		if (un->un_devid != NULL) {
5166 			(void) ddi_devid_register(SD_DEVINFO(un),
5167 			    un->un_devid);
5168 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5169 			    "sd_register_devid: devid fabricated using "
5170 			    "ddi framework\n");
5171 		}
5172 	}
5173 
5174 	/* clean up resources */
5175 	if (inq80 != NULL) {
5176 		kmem_free(inq80, inq80_len);
5177 	}
5178 	if (inq83 != NULL) {
5179 		kmem_free(inq83, inq83_len);
5180 	}
5181 }
5182 
5183 
5184 
5185 /*
5186  *    Function: sd_get_devid
5187  *
5188  * Description: This routine will return 0 if a valid device id has been
5189  *		obtained from the target and stored in the soft state. If a
5190  *		valid device id has not been previously read and stored, a
5191  *		read attempt will be made.
5192  *
5193  *   Arguments: un - driver soft state (unit) structure
5194  *
5195  * Return Code: 0 if we successfully get the device id
5196  *
5197  *     Context: Kernel Thread
5198  */
5199 
5200 static int
5201 sd_get_devid(sd_ssc_t *ssc)
5202 {
5203 	struct dk_devid		*dkdevid;
5204 	ddi_devid_t		tmpid;
5205 	uint_t			*ip;
5206 	size_t			sz;
5207 	diskaddr_t		blk;
5208 	int			status;
5209 	int			chksum;
5210 	int			i;
5211 	size_t			buffer_size;
5212 	struct sd_lun		*un;
5213 
5214 	ASSERT(ssc != NULL);
5215 	un = ssc->ssc_un;
5216 	ASSERT(un != NULL);
5217 	ASSERT(mutex_owned(SD_MUTEX(un)));
5218 
5219 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
5220 	    un);
5221 
5222 	if (un->un_devid != NULL) {
5223 		return (0);
5224 	}
5225 
5226 	mutex_exit(SD_MUTEX(un));
5227 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5228 	    (void *)SD_PATH_DIRECT) != 0) {
5229 		mutex_enter(SD_MUTEX(un));
5230 		return (EINVAL);
5231 	}
5232 
5233 	/*
5234 	 * Read and verify device id, stored in the reserved cylinders at the
5235 	 * end of the disk. Backup label is on the odd sectors of the last
5236 	 * track of the last cylinder. Device id will be on track of the next
5237 	 * to last cylinder.
5238 	 */
5239 	mutex_enter(SD_MUTEX(un));
5240 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
5241 	mutex_exit(SD_MUTEX(un));
5242 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
5243 	status = sd_send_scsi_READ(ssc, dkdevid, buffer_size, blk,
5244 	    SD_PATH_DIRECT);
5245 
5246 	if (status != 0) {
5247 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5248 		goto error;
5249 	}
5250 
5251 	/* Validate the revision */
5252 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
5253 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
5254 		status = EINVAL;
5255 		goto error;
5256 	}
5257 
5258 	/* Calculate the checksum */
5259 	chksum = 0;
5260 	ip = (uint_t *)dkdevid;
5261 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
5262 	    i++) {
5263 		chksum ^= ip[i];
5264 	}
5265 
5266 	/* Compare the checksums */
5267 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
5268 		status = EINVAL;
5269 		goto error;
5270 	}
5271 
5272 	/* Validate the device id */
5273 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
5274 		status = EINVAL;
5275 		goto error;
5276 	}
5277 
5278 	/*
5279 	 * Store the device id in the driver soft state
5280 	 */
5281 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
5282 	tmpid = kmem_alloc(sz, KM_SLEEP);
5283 
5284 	mutex_enter(SD_MUTEX(un));
5285 
5286 	un->un_devid = tmpid;
5287 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
5288 
5289 	kmem_free(dkdevid, buffer_size);
5290 
5291 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
5292 
5293 	return (status);
5294 error:
5295 	mutex_enter(SD_MUTEX(un));
5296 	kmem_free(dkdevid, buffer_size);
5297 	return (status);
5298 }
5299 
5300 
5301 /*
5302  *    Function: sd_create_devid
5303  *
5304  * Description: This routine will fabricate the device id and write it
5305  *		to the disk.
5306  *
5307  *   Arguments: un - driver soft state (unit) structure
5308  *
5309  * Return Code: value of the fabricated device id
5310  *
5311  *     Context: Kernel Thread
5312  */
5313 
5314 static ddi_devid_t
5315 sd_create_devid(sd_ssc_t *ssc)
5316 {
5317 	struct sd_lun	*un;
5318 
5319 	ASSERT(ssc != NULL);
5320 	un = ssc->ssc_un;
5321 	ASSERT(un != NULL);
5322 
5323 	/* Fabricate the devid */
5324 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
5325 	    == DDI_FAILURE) {
5326 		return (NULL);
5327 	}
5328 
5329 	/* Write the devid to disk */
5330 	if (sd_write_deviceid(ssc) != 0) {
5331 		ddi_devid_free(un->un_devid);
5332 		un->un_devid = NULL;
5333 	}
5334 
5335 	return (un->un_devid);
5336 }
5337 
5338 
5339 /*
5340  *    Function: sd_write_deviceid
5341  *
5342  * Description: This routine will write the device id to the disk
5343  *		reserved sector.
5344  *
5345  *   Arguments: un - driver soft state (unit) structure
5346  *
5347  * Return Code: EINVAL
5348  *		value returned by sd_send_scsi_cmd
5349  *
5350  *     Context: Kernel Thread
5351  */
5352 
5353 static int
5354 sd_write_deviceid(sd_ssc_t *ssc)
5355 {
5356 	struct dk_devid		*dkdevid;
5357 	diskaddr_t		blk;
5358 	uint_t			*ip, chksum;
5359 	int			status;
5360 	int			i;
5361 	struct sd_lun		*un;
5362 
5363 	ASSERT(ssc != NULL);
5364 	un = ssc->ssc_un;
5365 	ASSERT(un != NULL);
5366 	ASSERT(mutex_owned(SD_MUTEX(un)));
5367 
5368 	mutex_exit(SD_MUTEX(un));
5369 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5370 	    (void *)SD_PATH_DIRECT) != 0) {
5371 		mutex_enter(SD_MUTEX(un));
5372 		return (-1);
5373 	}
5374 
5375 
5376 	/* Allocate the buffer */
5377 	dkdevid = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5378 
5379 	/* Fill in the revision */
5380 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5381 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5382 
5383 	/* Copy in the device id */
5384 	mutex_enter(SD_MUTEX(un));
5385 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5386 	    ddi_devid_sizeof(un->un_devid));
5387 	mutex_exit(SD_MUTEX(un));
5388 
5389 	/* Calculate the checksum */
5390 	chksum = 0;
5391 	ip = (uint_t *)dkdevid;
5392 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
5393 	    i++) {
5394 		chksum ^= ip[i];
5395 	}
5396 
5397 	/* Fill-in checksum */
5398 	DKD_FORMCHKSUM(chksum, dkdevid);
5399 
5400 	/* Write the reserved sector */
5401 	status = sd_send_scsi_WRITE(ssc, dkdevid, un->un_sys_blocksize, blk,
5402 	    SD_PATH_DIRECT);
5403 	if (status != 0)
5404 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5405 
5406 	kmem_free(dkdevid, un->un_sys_blocksize);
5407 
5408 	mutex_enter(SD_MUTEX(un));
5409 	return (status);
5410 }
5411 
5412 
5413 /*
5414  *    Function: sd_check_vpd_page_support
5415  *
5416  * Description: This routine sends an inquiry command with the EVPD bit set and
5417  *		a page code of 0x00 to the device. It is used to determine which
5418  *		vital product pages are available to find the devid. We are
5419  *		looking for pages 0x83 or 0x80.  If we return a negative 1, the
5420  *		device does not support that command.
5421  *
5422  *   Arguments: un  - driver soft state (unit) structure
5423  *
5424  * Return Code: 0 - success
5425  *		1 - check condition
5426  *
5427  *     Context: This routine can sleep.
5428  */
5429 
5430 static int
5431 sd_check_vpd_page_support(sd_ssc_t *ssc)
5432 {
5433 	uchar_t	*page_list	= NULL;
5434 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5435 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5436 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5437 	int    	rval		= 0;
5438 	int	counter;
5439 	struct sd_lun		*un;
5440 
5441 	ASSERT(ssc != NULL);
5442 	un = ssc->ssc_un;
5443 	ASSERT(un != NULL);
5444 	ASSERT(mutex_owned(SD_MUTEX(un)));
5445 
5446 	mutex_exit(SD_MUTEX(un));
5447 
5448 	/*
5449 	 * We'll set the page length to the maximum to save figuring it out
5450 	 * with an additional call.
5451 	 */
5452 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5453 
5454 	rval = sd_send_scsi_INQUIRY(ssc, page_list, page_length, evpd,
5455 	    page_code, NULL);
5456 
5457 	if (rval != 0)
5458 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5459 
5460 	mutex_enter(SD_MUTEX(un));
5461 
5462 	/*
5463 	 * Now we must validate that the device accepted the command, as some
5464 	 * drives do not support it.  If the drive does support it, we will
5465 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5466 	 * not, we return -1.
5467 	 */
5468 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5469 		/* Loop to find one of the 2 pages we need */
5470 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5471 
5472 		/*
5473 		 * Pages are returned in ascending order, and 0x83 is what we
5474 		 * are hoping for.
5475 		 */
5476 		while ((page_list[counter] <= 0x86) &&
5477 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5478 		    VPD_HEAD_OFFSET))) {
5479 			/*
5480 			 * Add 3 because page_list[3] is the number of
5481 			 * pages minus 3
5482 			 */
5483 
5484 			switch (page_list[counter]) {
5485 			case 0x00:
5486 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5487 				break;
5488 			case 0x80:
5489 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5490 				break;
5491 			case 0x81:
5492 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5493 				break;
5494 			case 0x82:
5495 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5496 				break;
5497 			case 0x83:
5498 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5499 				break;
5500 			case 0x86:
5501 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5502 				break;
5503 			}
5504 			counter++;
5505 		}
5506 
5507 	} else {
5508 		rval = -1;
5509 
5510 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5511 		    "sd_check_vpd_page_support: This drive does not implement "
5512 		    "VPD pages.\n");
5513 	}
5514 
5515 	kmem_free(page_list, page_length);
5516 
5517 	return (rval);
5518 }
5519 
5520 
5521 /*
5522  *    Function: sd_setup_pm
5523  *
5524  * Description: Initialize Power Management on the device
5525  *
5526  *     Context: Kernel Thread
5527  */
5528 
5529 static void
5530 sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi)
5531 {
5532 	uint_t		log_page_size;
5533 	uchar_t		*log_page_data;
5534 	int		rval = 0;
5535 	struct sd_lun	*un;
5536 
5537 	ASSERT(ssc != NULL);
5538 	un = ssc->ssc_un;
5539 	ASSERT(un != NULL);
5540 
5541 	/*
5542 	 * Since we are called from attach, holding a mutex for
5543 	 * un is unnecessary. Because some of the routines called
5544 	 * from here require SD_MUTEX to not be held, assert this
5545 	 * right up front.
5546 	 */
5547 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5548 	/*
5549 	 * Since the sd device does not have the 'reg' property,
5550 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5551 	 * The following code is to tell cpr that this device
5552 	 * DOES need to be suspended and resumed.
5553 	 */
5554 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5555 	    "pm-hardware-state", "needs-suspend-resume");
5556 
5557 	/*
5558 	 * This complies with the new power management framework
5559 	 * for certain desktop machines. Create the pm_components
5560 	 * property as a string array property.
5561 	 */
5562 	if (un->un_f_pm_supported) {
5563 		/*
5564 		 * not all devices have a motor, try it first.
5565 		 * some devices may return ILLEGAL REQUEST, some
5566 		 * will hang
5567 		 * The following START_STOP_UNIT is used to check if target
5568 		 * device has a motor.
5569 		 */
5570 		un->un_f_start_stop_supported = TRUE;
5571 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_START,
5572 		    SD_PATH_DIRECT);
5573 
5574 		if (rval != 0) {
5575 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5576 			un->un_f_start_stop_supported = FALSE;
5577 		}
5578 
5579 		/*
5580 		 * create pm properties anyways otherwise the parent can't
5581 		 * go to sleep
5582 		 */
5583 		(void) sd_create_pm_components(devi, un);
5584 		un->un_f_pm_is_enabled = TRUE;
5585 		return;
5586 	}
5587 
5588 	if (!un->un_f_log_sense_supported) {
5589 		un->un_power_level = SD_SPINDLE_ON;
5590 		un->un_f_pm_is_enabled = FALSE;
5591 		return;
5592 	}
5593 
5594 	rval = sd_log_page_supported(ssc, START_STOP_CYCLE_PAGE);
5595 
5596 #ifdef	SDDEBUG
5597 	if (sd_force_pm_supported) {
5598 		/* Force a successful result */
5599 		rval = 1;
5600 	}
5601 #endif
5602 
5603 	/*
5604 	 * If the start-stop cycle counter log page is not supported
5605 	 * or if the pm-capable property is SD_PM_CAPABLE_FALSE (0)
5606 	 * then we should not create the pm_components property.
5607 	 */
5608 	if (rval == -1) {
5609 		/*
5610 		 * Error.
5611 		 * Reading log sense failed, most likely this is
5612 		 * an older drive that does not support log sense.
5613 		 * If this fails auto-pm is not supported.
5614 		 */
5615 		un->un_power_level = SD_SPINDLE_ON;
5616 		un->un_f_pm_is_enabled = FALSE;
5617 
5618 	} else if (rval == 0) {
5619 		/*
5620 		 * Page not found.
5621 		 * The start stop cycle counter is implemented as page
5622 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5623 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5624 		 */
5625 		if (sd_log_page_supported(ssc, START_STOP_CYCLE_VU_PAGE) == 1) {
5626 			/*
5627 			 * Page found, use this one.
5628 			 */
5629 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5630 			un->un_f_pm_is_enabled = TRUE;
5631 		} else {
5632 			/*
5633 			 * Error or page not found.
5634 			 * auto-pm is not supported for this device.
5635 			 */
5636 			un->un_power_level = SD_SPINDLE_ON;
5637 			un->un_f_pm_is_enabled = FALSE;
5638 		}
5639 	} else {
5640 		/*
5641 		 * Page found, use it.
5642 		 */
5643 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
5644 		un->un_f_pm_is_enabled = TRUE;
5645 	}
5646 
5647 
5648 	if (un->un_f_pm_is_enabled == TRUE) {
5649 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5650 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5651 
5652 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
5653 		    log_page_size, un->un_start_stop_cycle_page,
5654 		    0x01, 0, SD_PATH_DIRECT);
5655 
5656 		if (rval != 0) {
5657 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5658 		}
5659 
5660 #ifdef	SDDEBUG
5661 		if (sd_force_pm_supported) {
5662 			/* Force a successful result */
5663 			rval = 0;
5664 		}
5665 #endif
5666 
5667 		/*
5668 		 * If the Log sense for Page( Start/stop cycle counter page)
5669 		 * succeeds, then power management is supported and we can
5670 		 * enable auto-pm.
5671 		 */
5672 		if (rval == 0)  {
5673 			(void) sd_create_pm_components(devi, un);
5674 		} else {
5675 			un->un_power_level = SD_SPINDLE_ON;
5676 			un->un_f_pm_is_enabled = FALSE;
5677 		}
5678 
5679 		kmem_free(log_page_data, log_page_size);
5680 	}
5681 }
5682 
5683 
5684 /*
5685  *    Function: sd_create_pm_components
5686  *
5687  * Description: Initialize PM property.
5688  *
5689  *     Context: Kernel thread context
5690  */
5691 
5692 static void
5693 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
5694 {
5695 	char *pm_comp[] = { "NAME=spindle-motor", "0=off", "1=on", NULL };
5696 
5697 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5698 
5699 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
5700 	    "pm-components", pm_comp, 3) == DDI_PROP_SUCCESS) {
5701 		/*
5702 		 * When components are initially created they are idle,
5703 		 * power up any non-removables.
5704 		 * Note: the return value of pm_raise_power can't be used
5705 		 * for determining if PM should be enabled for this device.
5706 		 * Even if you check the return values and remove this
5707 		 * property created above, the PM framework will not honor the
5708 		 * change after the first call to pm_raise_power. Hence,
5709 		 * removal of that property does not help if pm_raise_power
5710 		 * fails. In the case of removable media, the start/stop
5711 		 * will fail if the media is not present.
5712 		 */
5713 		if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
5714 		    SD_SPINDLE_ON) == DDI_SUCCESS)) {
5715 			mutex_enter(SD_MUTEX(un));
5716 			un->un_power_level = SD_SPINDLE_ON;
5717 			mutex_enter(&un->un_pm_mutex);
5718 			/* Set to on and not busy. */
5719 			un->un_pm_count = 0;
5720 		} else {
5721 			mutex_enter(SD_MUTEX(un));
5722 			un->un_power_level = SD_SPINDLE_OFF;
5723 			mutex_enter(&un->un_pm_mutex);
5724 			/* Set to off. */
5725 			un->un_pm_count = -1;
5726 		}
5727 		mutex_exit(&un->un_pm_mutex);
5728 		mutex_exit(SD_MUTEX(un));
5729 	} else {
5730 		un->un_power_level = SD_SPINDLE_ON;
5731 		un->un_f_pm_is_enabled = FALSE;
5732 	}
5733 }
5734 
5735 
5736 /*
5737  *    Function: sd_ddi_suspend
5738  *
5739  * Description: Performs system power-down operations. This includes
5740  *		setting the drive state to indicate its suspended so
5741  *		that no new commands will be accepted. Also, wait for
5742  *		all commands that are in transport or queued to a timer
5743  *		for retry to complete. All timeout threads are cancelled.
5744  *
5745  * Return Code: DDI_FAILURE or DDI_SUCCESS
5746  *
5747  *     Context: Kernel thread context
5748  */
5749 
5750 static int
5751 sd_ddi_suspend(dev_info_t *devi)
5752 {
5753 	struct	sd_lun	*un;
5754 	clock_t		wait_cmds_complete;
5755 
5756 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5757 	if (un == NULL) {
5758 		return (DDI_FAILURE);
5759 	}
5760 
5761 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
5762 
5763 	mutex_enter(SD_MUTEX(un));
5764 
5765 	/* Return success if the device is already suspended. */
5766 	if (un->un_state == SD_STATE_SUSPENDED) {
5767 		mutex_exit(SD_MUTEX(un));
5768 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5769 		    "device already suspended, exiting\n");
5770 		return (DDI_SUCCESS);
5771 	}
5772 
5773 	/* Return failure if the device is being used by HA */
5774 	if (un->un_resvd_status &
5775 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
5776 		mutex_exit(SD_MUTEX(un));
5777 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5778 		    "device in use by HA, exiting\n");
5779 		return (DDI_FAILURE);
5780 	}
5781 
5782 	/*
5783 	 * Return failure if the device is in a resource wait
5784 	 * or power changing state.
5785 	 */
5786 	if ((un->un_state == SD_STATE_RWAIT) ||
5787 	    (un->un_state == SD_STATE_PM_CHANGING)) {
5788 		mutex_exit(SD_MUTEX(un));
5789 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5790 		    "device in resource wait state, exiting\n");
5791 		return (DDI_FAILURE);
5792 	}
5793 
5794 
5795 	un->un_save_state = un->un_last_state;
5796 	New_state(un, SD_STATE_SUSPENDED);
5797 
5798 	/*
5799 	 * Wait for all commands that are in transport or queued to a timer
5800 	 * for retry to complete.
5801 	 *
5802 	 * While waiting, no new commands will be accepted or sent because of
5803 	 * the new state we set above.
5804 	 *
5805 	 * Wait till current operation has completed. If we are in the resource
5806 	 * wait state (with an intr outstanding) then we need to wait till the
5807 	 * intr completes and starts the next cmd. We want to wait for
5808 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
5809 	 */
5810 	wait_cmds_complete = ddi_get_lbolt() +
5811 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
5812 
5813 	while (un->un_ncmds_in_transport != 0) {
5814 		/*
5815 		 * Fail if commands do not finish in the specified time.
5816 		 */
5817 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
5818 		    wait_cmds_complete) == -1) {
5819 			/*
5820 			 * Undo the state changes made above. Everything
5821 			 * must go back to it's original value.
5822 			 */
5823 			Restore_state(un);
5824 			un->un_last_state = un->un_save_state;
5825 			/* Wake up any threads that might be waiting. */
5826 			cv_broadcast(&un->un_suspend_cv);
5827 			mutex_exit(SD_MUTEX(un));
5828 			SD_ERROR(SD_LOG_IO_PM, un,
5829 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
5830 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
5831 			return (DDI_FAILURE);
5832 		}
5833 	}
5834 
5835 	/*
5836 	 * Cancel SCSI watch thread and timeouts, if any are active
5837 	 */
5838 
5839 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
5840 		opaque_t temp_token = un->un_swr_token;
5841 		mutex_exit(SD_MUTEX(un));
5842 		scsi_watch_suspend(temp_token);
5843 		mutex_enter(SD_MUTEX(un));
5844 	}
5845 
5846 	if (un->un_reset_throttle_timeid != NULL) {
5847 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
5848 		un->un_reset_throttle_timeid = NULL;
5849 		mutex_exit(SD_MUTEX(un));
5850 		(void) untimeout(temp_id);
5851 		mutex_enter(SD_MUTEX(un));
5852 	}
5853 
5854 	if (un->un_dcvb_timeid != NULL) {
5855 		timeout_id_t temp_id = un->un_dcvb_timeid;
5856 		un->un_dcvb_timeid = NULL;
5857 		mutex_exit(SD_MUTEX(un));
5858 		(void) untimeout(temp_id);
5859 		mutex_enter(SD_MUTEX(un));
5860 	}
5861 
5862 	mutex_enter(&un->un_pm_mutex);
5863 	if (un->un_pm_timeid != NULL) {
5864 		timeout_id_t temp_id = un->un_pm_timeid;
5865 		un->un_pm_timeid = NULL;
5866 		mutex_exit(&un->un_pm_mutex);
5867 		mutex_exit(SD_MUTEX(un));
5868 		(void) untimeout(temp_id);
5869 		mutex_enter(SD_MUTEX(un));
5870 	} else {
5871 		mutex_exit(&un->un_pm_mutex);
5872 	}
5873 
5874 	if (un->un_retry_timeid != NULL) {
5875 		timeout_id_t temp_id = un->un_retry_timeid;
5876 		un->un_retry_timeid = NULL;
5877 		mutex_exit(SD_MUTEX(un));
5878 		(void) untimeout(temp_id);
5879 		mutex_enter(SD_MUTEX(un));
5880 
5881 		if (un->un_retry_bp != NULL) {
5882 			un->un_retry_bp->av_forw = un->un_waitq_headp;
5883 			un->un_waitq_headp = un->un_retry_bp;
5884 			if (un->un_waitq_tailp == NULL) {
5885 				un->un_waitq_tailp = un->un_retry_bp;
5886 			}
5887 			un->un_retry_bp = NULL;
5888 			un->un_retry_statp = NULL;
5889 		}
5890 	}
5891 
5892 	if (un->un_direct_priority_timeid != NULL) {
5893 		timeout_id_t temp_id = un->un_direct_priority_timeid;
5894 		un->un_direct_priority_timeid = NULL;
5895 		mutex_exit(SD_MUTEX(un));
5896 		(void) untimeout(temp_id);
5897 		mutex_enter(SD_MUTEX(un));
5898 	}
5899 
5900 	if (un->un_f_is_fibre == TRUE) {
5901 		/*
5902 		 * Remove callbacks for insert and remove events
5903 		 */
5904 		if (un->un_insert_event != NULL) {
5905 			mutex_exit(SD_MUTEX(un));
5906 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
5907 			mutex_enter(SD_MUTEX(un));
5908 			un->un_insert_event = NULL;
5909 		}
5910 
5911 		if (un->un_remove_event != NULL) {
5912 			mutex_exit(SD_MUTEX(un));
5913 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
5914 			mutex_enter(SD_MUTEX(un));
5915 			un->un_remove_event = NULL;
5916 		}
5917 	}
5918 
5919 	mutex_exit(SD_MUTEX(un));
5920 
5921 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
5922 
5923 	return (DDI_SUCCESS);
5924 }
5925 
5926 
5927 /*
5928  *    Function: sd_ddi_pm_suspend
5929  *
5930  * Description: Set the drive state to low power.
5931  *		Someone else is required to actually change the drive
5932  *		power level.
5933  *
5934  *   Arguments: un - driver soft state (unit) structure
5935  *
5936  * Return Code: DDI_FAILURE or DDI_SUCCESS
5937  *
5938  *     Context: Kernel thread context
5939  */
5940 
5941 static int
5942 sd_ddi_pm_suspend(struct sd_lun *un)
5943 {
5944 	ASSERT(un != NULL);
5945 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: entry\n");
5946 
5947 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5948 	mutex_enter(SD_MUTEX(un));
5949 
5950 	/*
5951 	 * Exit if power management is not enabled for this device, or if
5952 	 * the device is being used by HA.
5953 	 */
5954 	if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
5955 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
5956 		mutex_exit(SD_MUTEX(un));
5957 		SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exiting\n");
5958 		return (DDI_SUCCESS);
5959 	}
5960 
5961 	SD_INFO(SD_LOG_POWER, un, "sd_ddi_pm_suspend: un_ncmds_in_driver=%ld\n",
5962 	    un->un_ncmds_in_driver);
5963 
5964 	/*
5965 	 * See if the device is not busy, ie.:
5966 	 *    - we have no commands in the driver for this device
5967 	 *    - not waiting for resources
5968 	 */
5969 	if ((un->un_ncmds_in_driver == 0) &&
5970 	    (un->un_state != SD_STATE_RWAIT)) {
5971 		/*
5972 		 * The device is not busy, so it is OK to go to low power state.
5973 		 * Indicate low power, but rely on someone else to actually
5974 		 * change it.
5975 		 */
5976 		mutex_enter(&un->un_pm_mutex);
5977 		un->un_pm_count = -1;
5978 		mutex_exit(&un->un_pm_mutex);
5979 		un->un_power_level = SD_SPINDLE_OFF;
5980 	}
5981 
5982 	mutex_exit(SD_MUTEX(un));
5983 
5984 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exit\n");
5985 
5986 	return (DDI_SUCCESS);
5987 }
5988 
5989 
5990 /*
5991  *    Function: sd_ddi_resume
5992  *
5993  * Description: Performs system power-up operations..
5994  *
5995  * Return Code: DDI_SUCCESS
5996  *		DDI_FAILURE
5997  *
5998  *     Context: Kernel thread context
5999  */
6000 
6001 static int
6002 sd_ddi_resume(dev_info_t *devi)
6003 {
6004 	struct	sd_lun	*un;
6005 
6006 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6007 	if (un == NULL) {
6008 		return (DDI_FAILURE);
6009 	}
6010 
6011 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6012 
6013 	mutex_enter(SD_MUTEX(un));
6014 	Restore_state(un);
6015 
6016 	/*
6017 	 * Restore the state which was saved to give the
6018 	 * the right state in un_last_state
6019 	 */
6020 	un->un_last_state = un->un_save_state;
6021 	/*
6022 	 * Note: throttle comes back at full.
6023 	 * Also note: this MUST be done before calling pm_raise_power
6024 	 * otherwise the system can get hung in biowait. The scenario where
6025 	 * this'll happen is under cpr suspend. Writing of the system
6026 	 * state goes through sddump, which writes 0 to un_throttle. If
6027 	 * writing the system state then fails, example if the partition is
6028 	 * too small, then cpr attempts a resume. If throttle isn't restored
6029 	 * from the saved value until after calling pm_raise_power then
6030 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6031 	 * in biowait.
6032 	 */
6033 	un->un_throttle = un->un_saved_throttle;
6034 
6035 	/*
6036 	 * The chance of failure is very rare as the only command done in power
6037 	 * entry point is START command when you transition from 0->1 or
6038 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6039 	 * which suspend was done. Ignore the return value as the resume should
6040 	 * not be failed. In the case of removable media the media need not be
6041 	 * inserted and hence there is a chance that raise power will fail with
6042 	 * media not present.
6043 	 */
6044 	if (un->un_f_attach_spinup) {
6045 		mutex_exit(SD_MUTEX(un));
6046 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
6047 		mutex_enter(SD_MUTEX(un));
6048 	}
6049 
6050 	/*
6051 	 * Don't broadcast to the suspend cv and therefore possibly
6052 	 * start I/O until after power has been restored.
6053 	 */
6054 	cv_broadcast(&un->un_suspend_cv);
6055 	cv_broadcast(&un->un_state_cv);
6056 
6057 	/* restart thread */
6058 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6059 		scsi_watch_resume(un->un_swr_token);
6060 	}
6061 
6062 #if (defined(__fibre))
6063 	if (un->un_f_is_fibre == TRUE) {
6064 		/*
6065 		 * Add callbacks for insert and remove events
6066 		 */
6067 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6068 			sd_init_event_callbacks(un);
6069 		}
6070 	}
6071 #endif
6072 
6073 	/*
6074 	 * Transport any pending commands to the target.
6075 	 *
6076 	 * If this is a low-activity device commands in queue will have to wait
6077 	 * until new commands come in, which may take awhile. Also, we
6078 	 * specifically don't check un_ncmds_in_transport because we know that
6079 	 * there really are no commands in progress after the unit was
6080 	 * suspended and we could have reached the throttle level, been
6081 	 * suspended, and have no new commands coming in for awhile. Highly
6082 	 * unlikely, but so is the low-activity disk scenario.
6083 	 */
6084 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6085 
6086 	sd_start_cmds(un, NULL);
6087 	mutex_exit(SD_MUTEX(un));
6088 
6089 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6090 
6091 	return (DDI_SUCCESS);
6092 }
6093 
6094 
6095 /*
6096  *    Function: sd_ddi_pm_resume
6097  *
6098  * Description: Set the drive state to powered on.
6099  *		Someone else is required to actually change the drive
6100  *		power level.
6101  *
6102  *   Arguments: un - driver soft state (unit) structure
6103  *
6104  * Return Code: DDI_SUCCESS
6105  *
6106  *     Context: Kernel thread context
6107  */
6108 
6109 static int
6110 sd_ddi_pm_resume(struct sd_lun *un)
6111 {
6112 	ASSERT(un != NULL);
6113 
6114 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6115 	mutex_enter(SD_MUTEX(un));
6116 	un->un_power_level = SD_SPINDLE_ON;
6117 
6118 	ASSERT(!mutex_owned(&un->un_pm_mutex));
6119 	mutex_enter(&un->un_pm_mutex);
6120 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6121 		un->un_pm_count++;
6122 		ASSERT(un->un_pm_count == 0);
6123 		/*
6124 		 * Note: no longer do the cv_broadcast on un_suspend_cv. The
6125 		 * un_suspend_cv is for a system resume, not a power management
6126 		 * device resume. (4297749)
6127 		 *	 cv_broadcast(&un->un_suspend_cv);
6128 		 */
6129 	}
6130 	mutex_exit(&un->un_pm_mutex);
6131 	mutex_exit(SD_MUTEX(un));
6132 
6133 	return (DDI_SUCCESS);
6134 }
6135 
6136 
6137 /*
6138  *    Function: sd_pm_idletimeout_handler
6139  *
6140  * Description: A timer routine that's active only while a device is busy.
6141  *		The purpose is to extend slightly the pm framework's busy
6142  *		view of the device to prevent busy/idle thrashing for
6143  *		back-to-back commands. Do this by comparing the current time
6144  *		to the time at which the last command completed and when the
6145  *		difference is greater than sd_pm_idletime, call
6146  *		pm_idle_component. In addition to indicating idle to the pm
6147  *		framework, update the chain type to again use the internal pm
6148  *		layers of the driver.
6149  *
6150  *   Arguments: arg - driver soft state (unit) structure
6151  *
6152  *     Context: Executes in a timeout(9F) thread context
6153  */
6154 
6155 static void
6156 sd_pm_idletimeout_handler(void *arg)
6157 {
6158 	struct sd_lun *un = arg;
6159 
6160 	time_t	now;
6161 
6162 	mutex_enter(&sd_detach_mutex);
6163 	if (un->un_detach_count != 0) {
6164 		/* Abort if the instance is detaching */
6165 		mutex_exit(&sd_detach_mutex);
6166 		return;
6167 	}
6168 	mutex_exit(&sd_detach_mutex);
6169 
6170 	now = ddi_get_time();
6171 	/*
6172 	 * Grab both mutexes, in the proper order, since we're accessing
6173 	 * both PM and softstate variables.
6174 	 */
6175 	mutex_enter(SD_MUTEX(un));
6176 	mutex_enter(&un->un_pm_mutex);
6177 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
6178 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
6179 		/*
6180 		 * Update the chain types.
6181 		 * This takes affect on the next new command received.
6182 		 */
6183 		if (un->un_f_non_devbsize_supported) {
6184 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6185 		} else {
6186 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6187 		}
6188 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
6189 
6190 		SD_TRACE(SD_LOG_IO_PM, un,
6191 		    "sd_pm_idletimeout_handler: idling device\n");
6192 		(void) pm_idle_component(SD_DEVINFO(un), 0);
6193 		un->un_pm_idle_timeid = NULL;
6194 	} else {
6195 		un->un_pm_idle_timeid =
6196 		    timeout(sd_pm_idletimeout_handler, un,
6197 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
6198 	}
6199 	mutex_exit(&un->un_pm_mutex);
6200 	mutex_exit(SD_MUTEX(un));
6201 }
6202 
6203 
6204 /*
6205  *    Function: sd_pm_timeout_handler
6206  *
6207  * Description: Callback to tell framework we are idle.
6208  *
6209  *     Context: timeout(9f) thread context.
6210  */
6211 
6212 static void
6213 sd_pm_timeout_handler(void *arg)
6214 {
6215 	struct sd_lun *un = arg;
6216 
6217 	(void) pm_idle_component(SD_DEVINFO(un), 0);
6218 	mutex_enter(&un->un_pm_mutex);
6219 	un->un_pm_timeid = NULL;
6220 	mutex_exit(&un->un_pm_mutex);
6221 }
6222 
6223 
6224 /*
6225  *    Function: sdpower
6226  *
6227  * Description: PM entry point.
6228  *
6229  * Return Code: DDI_SUCCESS
6230  *		DDI_FAILURE
6231  *
6232  *     Context: Kernel thread context
6233  */
6234 
6235 static int
6236 sdpower(dev_info_t *devi, int component, int level)
6237 {
6238 	struct sd_lun	*un;
6239 	int		instance;
6240 	int		rval = DDI_SUCCESS;
6241 	uint_t		i, log_page_size, maxcycles, ncycles;
6242 	uchar_t		*log_page_data;
6243 	int		log_sense_page;
6244 	int		medium_present;
6245 	time_t		intvlp;
6246 	dev_t		dev;
6247 	struct pm_trans_data	sd_pm_tran_data;
6248 	uchar_t		save_state;
6249 	int		sval;
6250 	uchar_t		state_before_pm;
6251 	int		got_semaphore_here;
6252 	sd_ssc_t	*ssc;
6253 
6254 	instance = ddi_get_instance(devi);
6255 
6256 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
6257 	    (SD_SPINDLE_OFF > level) || (level > SD_SPINDLE_ON) ||
6258 	    component != 0) {
6259 		return (DDI_FAILURE);
6260 	}
6261 
6262 	dev = sd_make_device(SD_DEVINFO(un));
6263 	ssc = sd_ssc_init(un);
6264 
6265 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
6266 
6267 	/*
6268 	 * Must synchronize power down with close.
6269 	 * Attempt to decrement/acquire the open/close semaphore,
6270 	 * but do NOT wait on it. If it's not greater than zero,
6271 	 * ie. it can't be decremented without waiting, then
6272 	 * someone else, either open or close, already has it
6273 	 * and the try returns 0. Use that knowledge here to determine
6274 	 * if it's OK to change the device power level.
6275 	 * Also, only increment it on exit if it was decremented, ie. gotten,
6276 	 * here.
6277 	 */
6278 	got_semaphore_here = sema_tryp(&un->un_semoclose);
6279 
6280 	mutex_enter(SD_MUTEX(un));
6281 
6282 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
6283 	    un->un_ncmds_in_driver);
6284 
6285 	/*
6286 	 * If un_ncmds_in_driver is non-zero it indicates commands are
6287 	 * already being processed in the driver, or if the semaphore was
6288 	 * not gotten here it indicates an open or close is being processed.
6289 	 * At the same time somebody is requesting to go low power which
6290 	 * can't happen, therefore we need to return failure.
6291 	 */
6292 	if ((level == SD_SPINDLE_OFF) &&
6293 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
6294 		mutex_exit(SD_MUTEX(un));
6295 
6296 		if (got_semaphore_here != 0) {
6297 			sema_v(&un->un_semoclose);
6298 		}
6299 		SD_TRACE(SD_LOG_IO_PM, un,
6300 		    "sdpower: exit, device has queued cmds.\n");
6301 
6302 		goto sdpower_failed;
6303 	}
6304 
6305 	/*
6306 	 * if it is OFFLINE that means the disk is completely dead
6307 	 * in our case we have to put the disk in on or off by sending commands
6308 	 * Of course that will fail anyway so return back here.
6309 	 *
6310 	 * Power changes to a device that's OFFLINE or SUSPENDED
6311 	 * are not allowed.
6312 	 */
6313 	if ((un->un_state == SD_STATE_OFFLINE) ||
6314 	    (un->un_state == SD_STATE_SUSPENDED)) {
6315 		mutex_exit(SD_MUTEX(un));
6316 
6317 		if (got_semaphore_here != 0) {
6318 			sema_v(&un->un_semoclose);
6319 		}
6320 		SD_TRACE(SD_LOG_IO_PM, un,
6321 		    "sdpower: exit, device is off-line.\n");
6322 
6323 		goto sdpower_failed;
6324 	}
6325 
6326 	/*
6327 	 * Change the device's state to indicate it's power level
6328 	 * is being changed. Do this to prevent a power off in the
6329 	 * middle of commands, which is especially bad on devices
6330 	 * that are really powered off instead of just spun down.
6331 	 */
6332 	state_before_pm = un->un_state;
6333 	un->un_state = SD_STATE_PM_CHANGING;
6334 
6335 	mutex_exit(SD_MUTEX(un));
6336 
6337 	/*
6338 	 * If "pm-capable" property is set to TRUE by HBA drivers,
6339 	 * bypass the following checking, otherwise, check the log
6340 	 * sense information for this device
6341 	 */
6342 	if ((level == SD_SPINDLE_OFF) && un->un_f_log_sense_supported) {
6343 		/*
6344 		 * Get the log sense information to understand whether the
6345 		 * the powercycle counts have gone beyond the threshhold.
6346 		 */
6347 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6348 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6349 
6350 		mutex_enter(SD_MUTEX(un));
6351 		log_sense_page = un->un_start_stop_cycle_page;
6352 		mutex_exit(SD_MUTEX(un));
6353 
6354 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6355 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
6356 
6357 		if (rval != 0) {
6358 			if (rval == EIO)
6359 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6360 			else
6361 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6362 		}
6363 
6364 #ifdef	SDDEBUG
6365 		if (sd_force_pm_supported) {
6366 			/* Force a successful result */
6367 			rval = 0;
6368 		}
6369 #endif
6370 		if (rval != 0) {
6371 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
6372 			    "Log Sense Failed\n");
6373 
6374 			kmem_free(log_page_data, log_page_size);
6375 			/* Cannot support power management on those drives */
6376 
6377 			if (got_semaphore_here != 0) {
6378 				sema_v(&un->un_semoclose);
6379 			}
6380 			/*
6381 			 * On exit put the state back to it's original value
6382 			 * and broadcast to anyone waiting for the power
6383 			 * change completion.
6384 			 */
6385 			mutex_enter(SD_MUTEX(un));
6386 			un->un_state = state_before_pm;
6387 			cv_broadcast(&un->un_suspend_cv);
6388 			mutex_exit(SD_MUTEX(un));
6389 			SD_TRACE(SD_LOG_IO_PM, un,
6390 			    "sdpower: exit, Log Sense Failed.\n");
6391 
6392 			goto sdpower_failed;
6393 		}
6394 
6395 		/*
6396 		 * From the page data - Convert the essential information to
6397 		 * pm_trans_data
6398 		 */
6399 		maxcycles =
6400 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
6401 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
6402 
6403 		sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6404 
6405 		ncycles =
6406 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6407 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6408 
6409 		sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6410 
6411 		for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6412 			sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6413 			    log_page_data[8+i];
6414 		}
6415 
6416 		kmem_free(log_page_data, log_page_size);
6417 
6418 		/*
6419 		 * Call pm_trans_check routine to get the Ok from
6420 		 * the global policy
6421 		 */
6422 
6423 		sd_pm_tran_data.format = DC_SCSI_FORMAT;
6424 		sd_pm_tran_data.un.scsi_cycles.flag = 0;
6425 
6426 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6427 #ifdef	SDDEBUG
6428 		if (sd_force_pm_supported) {
6429 			/* Force a successful result */
6430 			rval = 1;
6431 		}
6432 #endif
6433 		switch (rval) {
6434 		case 0:
6435 			/*
6436 			 * Not Ok to Power cycle or error in parameters passed
6437 			 * Would have given the advised time to consider power
6438 			 * cycle. Based on the new intvlp parameter we are
6439 			 * supposed to pretend we are busy so that pm framework
6440 			 * will never call our power entry point. Because of
6441 			 * that install a timeout handler and wait for the
6442 			 * recommended time to elapse so that power management
6443 			 * can be effective again.
6444 			 *
6445 			 * To effect this behavior, call pm_busy_component to
6446 			 * indicate to the framework this device is busy.
6447 			 * By not adjusting un_pm_count the rest of PM in
6448 			 * the driver will function normally, and independent
6449 			 * of this but because the framework is told the device
6450 			 * is busy it won't attempt powering down until it gets
6451 			 * a matching idle. The timeout handler sends this.
6452 			 * Note: sd_pm_entry can't be called here to do this
6453 			 * because sdpower may have been called as a result
6454 			 * of a call to pm_raise_power from within sd_pm_entry.
6455 			 *
6456 			 * If a timeout handler is already active then
6457 			 * don't install another.
6458 			 */
6459 			mutex_enter(&un->un_pm_mutex);
6460 			if (un->un_pm_timeid == NULL) {
6461 				un->un_pm_timeid =
6462 				    timeout(sd_pm_timeout_handler,
6463 				    un, intvlp * drv_usectohz(1000000));
6464 				mutex_exit(&un->un_pm_mutex);
6465 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6466 			} else {
6467 				mutex_exit(&un->un_pm_mutex);
6468 			}
6469 			if (got_semaphore_here != 0) {
6470 				sema_v(&un->un_semoclose);
6471 			}
6472 			/*
6473 			 * On exit put the state back to it's original value
6474 			 * and broadcast to anyone waiting for the power
6475 			 * change completion.
6476 			 */
6477 			mutex_enter(SD_MUTEX(un));
6478 			un->un_state = state_before_pm;
6479 			cv_broadcast(&un->un_suspend_cv);
6480 			mutex_exit(SD_MUTEX(un));
6481 
6482 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6483 			    "trans check Failed, not ok to power cycle.\n");
6484 
6485 			goto sdpower_failed;
6486 		case -1:
6487 			if (got_semaphore_here != 0) {
6488 				sema_v(&un->un_semoclose);
6489 			}
6490 			/*
6491 			 * On exit put the state back to it's original value
6492 			 * and broadcast to anyone waiting for the power
6493 			 * change completion.
6494 			 */
6495 			mutex_enter(SD_MUTEX(un));
6496 			un->un_state = state_before_pm;
6497 			cv_broadcast(&un->un_suspend_cv);
6498 			mutex_exit(SD_MUTEX(un));
6499 			SD_TRACE(SD_LOG_IO_PM, un,
6500 			    "sdpower: exit, trans check command Failed.\n");
6501 
6502 			goto sdpower_failed;
6503 		}
6504 	}
6505 
6506 	if (level == SD_SPINDLE_OFF) {
6507 		/*
6508 		 * Save the last state... if the STOP FAILS we need it
6509 		 * for restoring
6510 		 */
6511 		mutex_enter(SD_MUTEX(un));
6512 		save_state = un->un_last_state;
6513 		/*
6514 		 * There must not be any cmds. getting processed
6515 		 * in the driver when we get here. Power to the
6516 		 * device is potentially going off.
6517 		 */
6518 		ASSERT(un->un_ncmds_in_driver == 0);
6519 		mutex_exit(SD_MUTEX(un));
6520 
6521 		/*
6522 		 * For now suspend the device completely before spindle is
6523 		 * turned off
6524 		 */
6525 		if ((rval = sd_ddi_pm_suspend(un)) == DDI_FAILURE) {
6526 			if (got_semaphore_here != 0) {
6527 				sema_v(&un->un_semoclose);
6528 			}
6529 			/*
6530 			 * On exit put the state back to it's original value
6531 			 * and broadcast to anyone waiting for the power
6532 			 * change completion.
6533 			 */
6534 			mutex_enter(SD_MUTEX(un));
6535 			un->un_state = state_before_pm;
6536 			cv_broadcast(&un->un_suspend_cv);
6537 			mutex_exit(SD_MUTEX(un));
6538 			SD_TRACE(SD_LOG_IO_PM, un,
6539 			    "sdpower: exit, PM suspend Failed.\n");
6540 
6541 			goto sdpower_failed;
6542 		}
6543 	}
6544 
6545 	/*
6546 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6547 	 * close, or strategy. Dump no long uses this routine, it uses it's
6548 	 * own code so it can be done in polled mode.
6549 	 */
6550 
6551 	medium_present = TRUE;
6552 
6553 	/*
6554 	 * When powering up, issue a TUR in case the device is at unit
6555 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6556 	 * a deadlock on un_pm_busy_cv will occur.
6557 	 */
6558 	if (level == SD_SPINDLE_ON) {
6559 		sval = sd_send_scsi_TEST_UNIT_READY(ssc,
6560 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6561 		if (sval != 0)
6562 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6563 	}
6564 
6565 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6566 	    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6567 
6568 	sval = sd_send_scsi_START_STOP_UNIT(ssc,
6569 	    ((level == SD_SPINDLE_ON) ? SD_TARGET_START : SD_TARGET_STOP),
6570 	    SD_PATH_DIRECT);
6571 	if (sval != 0) {
6572 		if (sval == EIO)
6573 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6574 		else
6575 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6576 	}
6577 
6578 	/* Command failed, check for media present. */
6579 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6580 		medium_present = FALSE;
6581 	}
6582 
6583 	/*
6584 	 * The conditions of interest here are:
6585 	 *   if a spindle off with media present fails,
6586 	 *	then restore the state and return an error.
6587 	 *   else if a spindle on fails,
6588 	 *	then return an error (there's no state to restore).
6589 	 * In all other cases we setup for the new state
6590 	 * and return success.
6591 	 */
6592 	switch (level) {
6593 	case SD_SPINDLE_OFF:
6594 		if ((medium_present == TRUE) && (sval != 0)) {
6595 			/* The stop command from above failed */
6596 			rval = DDI_FAILURE;
6597 			/*
6598 			 * The stop command failed, and we have media
6599 			 * present. Put the level back by calling the
6600 			 * sd_pm_resume() and set the state back to
6601 			 * it's previous value.
6602 			 */
6603 			(void) sd_ddi_pm_resume(un);
6604 			mutex_enter(SD_MUTEX(un));
6605 			un->un_last_state = save_state;
6606 			mutex_exit(SD_MUTEX(un));
6607 			break;
6608 		}
6609 		/*
6610 		 * The stop command from above succeeded.
6611 		 */
6612 		if (un->un_f_monitor_media_state) {
6613 			/*
6614 			 * Terminate watch thread in case of removable media
6615 			 * devices going into low power state. This is as per
6616 			 * the requirements of pm framework, otherwise commands
6617 			 * will be generated for the device (through watch
6618 			 * thread), even when the device is in low power state.
6619 			 */
6620 			mutex_enter(SD_MUTEX(un));
6621 			un->un_f_watcht_stopped = FALSE;
6622 			if (un->un_swr_token != NULL) {
6623 				opaque_t temp_token = un->un_swr_token;
6624 				un->un_f_watcht_stopped = TRUE;
6625 				un->un_swr_token = NULL;
6626 				mutex_exit(SD_MUTEX(un));
6627 				(void) scsi_watch_request_terminate(temp_token,
6628 				    SCSI_WATCH_TERMINATE_ALL_WAIT);
6629 			} else {
6630 				mutex_exit(SD_MUTEX(un));
6631 			}
6632 		}
6633 		break;
6634 
6635 	default:	/* The level requested is spindle on... */
6636 		/*
6637 		 * Legacy behavior: return success on a failed spinup
6638 		 * if there is no media in the drive.
6639 		 * Do this by looking at medium_present here.
6640 		 */
6641 		if ((sval != 0) && medium_present) {
6642 			/* The start command from above failed */
6643 			rval = DDI_FAILURE;
6644 			break;
6645 		}
6646 		/*
6647 		 * The start command from above succeeded
6648 		 * Resume the devices now that we have
6649 		 * started the disks
6650 		 */
6651 		(void) sd_ddi_pm_resume(un);
6652 
6653 		/*
6654 		 * Resume the watch thread since it was suspended
6655 		 * when the device went into low power mode.
6656 		 */
6657 		if (un->un_f_monitor_media_state) {
6658 			mutex_enter(SD_MUTEX(un));
6659 			if (un->un_f_watcht_stopped == TRUE) {
6660 				opaque_t temp_token;
6661 
6662 				un->un_f_watcht_stopped = FALSE;
6663 				mutex_exit(SD_MUTEX(un));
6664 				temp_token = scsi_watch_request_submit(
6665 				    SD_SCSI_DEVP(un),
6666 				    sd_check_media_time,
6667 				    SENSE_LENGTH, sd_media_watch_cb,
6668 				    (caddr_t)dev);
6669 				mutex_enter(SD_MUTEX(un));
6670 				un->un_swr_token = temp_token;
6671 			}
6672 			mutex_exit(SD_MUTEX(un));
6673 		}
6674 	}
6675 	if (got_semaphore_here != 0) {
6676 		sema_v(&un->un_semoclose);
6677 	}
6678 	/*
6679 	 * On exit put the state back to it's original value
6680 	 * and broadcast to anyone waiting for the power
6681 	 * change completion.
6682 	 */
6683 	mutex_enter(SD_MUTEX(un));
6684 	un->un_state = state_before_pm;
6685 	cv_broadcast(&un->un_suspend_cv);
6686 	mutex_exit(SD_MUTEX(un));
6687 
6688 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
6689 
6690 	sd_ssc_fini(ssc);
6691 	return (rval);
6692 
6693 sdpower_failed:
6694 
6695 	sd_ssc_fini(ssc);
6696 	return (DDI_FAILURE);
6697 }
6698 
6699 
6700 
6701 /*
6702  *    Function: sdattach
6703  *
6704  * Description: Driver's attach(9e) entry point function.
6705  *
6706  *   Arguments: devi - opaque device info handle
6707  *		cmd  - attach  type
6708  *
6709  * Return Code: DDI_SUCCESS
6710  *		DDI_FAILURE
6711  *
6712  *     Context: Kernel thread context
6713  */
6714 
6715 static int
6716 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
6717 {
6718 	switch (cmd) {
6719 	case DDI_ATTACH:
6720 		return (sd_unit_attach(devi));
6721 	case DDI_RESUME:
6722 		return (sd_ddi_resume(devi));
6723 	default:
6724 		break;
6725 	}
6726 	return (DDI_FAILURE);
6727 }
6728 
6729 
6730 /*
6731  *    Function: sddetach
6732  *
6733  * Description: Driver's detach(9E) entry point function.
6734  *
6735  *   Arguments: devi - opaque device info handle
6736  *		cmd  - detach  type
6737  *
6738  * Return Code: DDI_SUCCESS
6739  *		DDI_FAILURE
6740  *
6741  *     Context: Kernel thread context
6742  */
6743 
6744 static int
6745 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
6746 {
6747 	switch (cmd) {
6748 	case DDI_DETACH:
6749 		return (sd_unit_detach(devi));
6750 	case DDI_SUSPEND:
6751 		return (sd_ddi_suspend(devi));
6752 	default:
6753 		break;
6754 	}
6755 	return (DDI_FAILURE);
6756 }
6757 
6758 
6759 /*
6760  *     Function: sd_sync_with_callback
6761  *
6762  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
6763  *		 state while the callback routine is active.
6764  *
6765  *    Arguments: un: softstate structure for the instance
6766  *
6767  *	Context: Kernel thread context
6768  */
6769 
6770 static void
6771 sd_sync_with_callback(struct sd_lun *un)
6772 {
6773 	ASSERT(un != NULL);
6774 
6775 	mutex_enter(SD_MUTEX(un));
6776 
6777 	ASSERT(un->un_in_callback >= 0);
6778 
6779 	while (un->un_in_callback > 0) {
6780 		mutex_exit(SD_MUTEX(un));
6781 		delay(2);
6782 		mutex_enter(SD_MUTEX(un));
6783 	}
6784 
6785 	mutex_exit(SD_MUTEX(un));
6786 }
6787 
6788 /*
6789  *    Function: sd_unit_attach
6790  *
6791  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
6792  *		the soft state structure for the device and performs
6793  *		all necessary structure and device initializations.
6794  *
6795  *   Arguments: devi: the system's dev_info_t for the device.
6796  *
6797  * Return Code: DDI_SUCCESS if attach is successful.
6798  *		DDI_FAILURE if any part of the attach fails.
6799  *
6800  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
6801  *		Kernel thread context only.  Can sleep.
6802  */
6803 
6804 static int
6805 sd_unit_attach(dev_info_t *devi)
6806 {
6807 	struct	scsi_device	*devp;
6808 	struct	sd_lun		*un;
6809 	char			*variantp;
6810 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
6811 	int	instance;
6812 	int	rval;
6813 	int	wc_enabled;
6814 	int	tgt;
6815 	uint64_t	capacity;
6816 	uint_t		lbasize = 0;
6817 	dev_info_t	*pdip = ddi_get_parent(devi);
6818 	int		offbyone = 0;
6819 	int		geom_label_valid = 0;
6820 	sd_ssc_t	*ssc;
6821 	int		status;
6822 	struct sd_fm_internal	*sfip = NULL;
6823 #if defined(__sparc)
6824 	int		max_xfer_size;
6825 #endif
6826 
6827 	/*
6828 	 * Retrieve the target driver's private data area. This was set
6829 	 * up by the HBA.
6830 	 */
6831 	devp = ddi_get_driver_private(devi);
6832 
6833 	/*
6834 	 * Retrieve the target ID of the device.
6835 	 */
6836 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6837 	    SCSI_ADDR_PROP_TARGET, -1);
6838 
6839 	/*
6840 	 * Since we have no idea what state things were left in by the last
6841 	 * user of the device, set up some 'default' settings, ie. turn 'em
6842 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
6843 	 * Do this before the scsi_probe, which sends an inquiry.
6844 	 * This is a fix for bug (4430280).
6845 	 * Of special importance is wide-xfer. The drive could have been left
6846 	 * in wide transfer mode by the last driver to communicate with it,
6847 	 * this includes us. If that's the case, and if the following is not
6848 	 * setup properly or we don't re-negotiate with the drive prior to
6849 	 * transferring data to/from the drive, it causes bus parity errors,
6850 	 * data overruns, and unexpected interrupts. This first occurred when
6851 	 * the fix for bug (4378686) was made.
6852 	 */
6853 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
6854 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
6855 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
6856 
6857 	/*
6858 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
6859 	 * on a target. Setting it per lun instance actually sets the
6860 	 * capability of this target, which affects those luns already
6861 	 * attached on the same target. So during attach, we can only disable
6862 	 * this capability only when no other lun has been attached on this
6863 	 * target. By doing this, we assume a target has the same tagged-qing
6864 	 * capability for every lun. The condition can be removed when HBA
6865 	 * is changed to support per lun based tagged-qing capability.
6866 	 */
6867 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
6868 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
6869 	}
6870 
6871 	/*
6872 	 * Use scsi_probe() to issue an INQUIRY command to the device.
6873 	 * This call will allocate and fill in the scsi_inquiry structure
6874 	 * and point the sd_inq member of the scsi_device structure to it.
6875 	 * If the attach succeeds, then this memory will not be de-allocated
6876 	 * (via scsi_unprobe()) until the instance is detached.
6877 	 */
6878 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
6879 		goto probe_failed;
6880 	}
6881 
6882 	/*
6883 	 * Check the device type as specified in the inquiry data and
6884 	 * claim it if it is of a type that we support.
6885 	 */
6886 	switch (devp->sd_inq->inq_dtype) {
6887 	case DTYPE_DIRECT:
6888 		break;
6889 	case DTYPE_RODIRECT:
6890 		break;
6891 	case DTYPE_OPTICAL:
6892 		break;
6893 	case DTYPE_NOTPRESENT:
6894 	default:
6895 		/* Unsupported device type; fail the attach. */
6896 		goto probe_failed;
6897 	}
6898 
6899 	/*
6900 	 * Allocate the soft state structure for this unit.
6901 	 *
6902 	 * We rely upon this memory being set to all zeroes by
6903 	 * ddi_soft_state_zalloc().  We assume that any member of the
6904 	 * soft state structure that is not explicitly initialized by
6905 	 * this routine will have a value of zero.
6906 	 */
6907 	instance = ddi_get_instance(devp->sd_dev);
6908 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
6909 		goto probe_failed;
6910 	}
6911 
6912 	/*
6913 	 * Retrieve a pointer to the newly-allocated soft state.
6914 	 *
6915 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
6916 	 * was successful, unless something has gone horribly wrong and the
6917 	 * ddi's soft state internals are corrupt (in which case it is
6918 	 * probably better to halt here than just fail the attach....)
6919 	 */
6920 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
6921 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
6922 		    instance);
6923 		/*NOTREACHED*/
6924 	}
6925 
6926 	/*
6927 	 * Link the back ptr of the driver soft state to the scsi_device
6928 	 * struct for this lun.
6929 	 * Save a pointer to the softstate in the driver-private area of
6930 	 * the scsi_device struct.
6931 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
6932 	 * we first set un->un_sd below.
6933 	 */
6934 	un->un_sd = devp;
6935 	devp->sd_private = (opaque_t)un;
6936 
6937 	/*
6938 	 * The following must be after devp is stored in the soft state struct.
6939 	 */
6940 #ifdef SDDEBUG
6941 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6942 	    "%s_unit_attach: un:0x%p instance:%d\n",
6943 	    ddi_driver_name(devi), un, instance);
6944 #endif
6945 
6946 	/*
6947 	 * Set up the device type and node type (for the minor nodes).
6948 	 * By default we assume that the device can at least support the
6949 	 * Common Command Set. Call it a CD-ROM if it reports itself
6950 	 * as a RODIRECT device.
6951 	 */
6952 	switch (devp->sd_inq->inq_dtype) {
6953 	case DTYPE_RODIRECT:
6954 		un->un_node_type = DDI_NT_CD_CHAN;
6955 		un->un_ctype	 = CTYPE_CDROM;
6956 		break;
6957 	case DTYPE_OPTICAL:
6958 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6959 		un->un_ctype	 = CTYPE_ROD;
6960 		break;
6961 	default:
6962 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6963 		un->un_ctype	 = CTYPE_CCS;
6964 		break;
6965 	}
6966 
6967 	/*
6968 	 * Try to read the interconnect type from the HBA.
6969 	 *
6970 	 * Note: This driver is currently compiled as two binaries, a parallel
6971 	 * scsi version (sd) and a fibre channel version (ssd). All functional
6972 	 * differences are determined at compile time. In the future a single
6973 	 * binary will be provided and the interconnect type will be used to
6974 	 * differentiate between fibre and parallel scsi behaviors. At that time
6975 	 * it will be necessary for all fibre channel HBAs to support this
6976 	 * property.
6977 	 *
6978 	 * set un_f_is_fiber to TRUE ( default fiber )
6979 	 */
6980 	un->un_f_is_fibre = TRUE;
6981 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
6982 	case INTERCONNECT_SSA:
6983 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
6984 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6985 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
6986 		break;
6987 	case INTERCONNECT_PARALLEL:
6988 		un->un_f_is_fibre = FALSE;
6989 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6990 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6991 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
6992 		break;
6993 	case INTERCONNECT_SATA:
6994 		un->un_f_is_fibre = FALSE;
6995 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
6996 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6997 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
6998 		break;
6999 	case INTERCONNECT_FIBRE:
7000 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7001 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7002 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7003 		break;
7004 	case INTERCONNECT_FABRIC:
7005 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7006 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7007 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7008 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7009 		break;
7010 	default:
7011 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7012 		/*
7013 		 * The HBA does not support the "interconnect-type" property
7014 		 * (or did not provide a recognized type).
7015 		 *
7016 		 * Note: This will be obsoleted when a single fibre channel
7017 		 * and parallel scsi driver is delivered. In the meantime the
7018 		 * interconnect type will be set to the platform default.If that
7019 		 * type is not parallel SCSI, it means that we should be
7020 		 * assuming "ssd" semantics. However, here this also means that
7021 		 * the FC HBA is not supporting the "interconnect-type" property
7022 		 * like we expect it to, so log this occurrence.
7023 		 */
7024 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7025 		if (!SD_IS_PARALLEL_SCSI(un)) {
7026 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7027 			    "sd_unit_attach: un:0x%p Assuming "
7028 			    "INTERCONNECT_FIBRE\n", un);
7029 		} else {
7030 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7031 			    "sd_unit_attach: un:0x%p Assuming "
7032 			    "INTERCONNECT_PARALLEL\n", un);
7033 			un->un_f_is_fibre = FALSE;
7034 		}
7035 #else
7036 		/*
7037 		 * Note: This source will be implemented when a single fibre
7038 		 * channel and parallel scsi driver is delivered. The default
7039 		 * will be to assume that if a device does not support the
7040 		 * "interconnect-type" property it is a parallel SCSI HBA and
7041 		 * we will set the interconnect type for parallel scsi.
7042 		 */
7043 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7044 		un->un_f_is_fibre = FALSE;
7045 #endif
7046 		break;
7047 	}
7048 
7049 	if (un->un_f_is_fibre == TRUE) {
7050 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7051 		    SCSI_VERSION_3) {
7052 			switch (un->un_interconnect_type) {
7053 			case SD_INTERCONNECT_FIBRE:
7054 			case SD_INTERCONNECT_SSA:
7055 				un->un_node_type = DDI_NT_BLOCK_WWN;
7056 				break;
7057 			default:
7058 				break;
7059 			}
7060 		}
7061 	}
7062 
7063 	/*
7064 	 * Initialize the Request Sense command for the target
7065 	 */
7066 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7067 		goto alloc_rqs_failed;
7068 	}
7069 
7070 	/*
7071 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7072 	 * with separate binary for sd and ssd.
7073 	 *
7074 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7075 	 * The hardcoded values will go away when Sparc uses 1 binary
7076 	 * for sd and ssd.  This hardcoded values need to match
7077 	 * SD_RETRY_COUNT in sddef.h
7078 	 * The value used is base on interconnect type.
7079 	 * fibre = 3, parallel = 5
7080 	 */
7081 #if defined(__i386) || defined(__amd64)
7082 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7083 #else
7084 	un->un_retry_count = SD_RETRY_COUNT;
7085 #endif
7086 
7087 	/*
7088 	 * Set the per disk retry count to the default number of retries
7089 	 * for disks and CDROMs. This value can be overridden by the
7090 	 * disk property list or an entry in sd.conf.
7091 	 */
7092 	un->un_notready_retry_count =
7093 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7094 	    : DISK_NOT_READY_RETRY_COUNT(un);
7095 
7096 	/*
7097 	 * Set the busy retry count to the default value of un_retry_count.
7098 	 * This can be overridden by entries in sd.conf or the device
7099 	 * config table.
7100 	 */
7101 	un->un_busy_retry_count = un->un_retry_count;
7102 
7103 	/*
7104 	 * Init the reset threshold for retries.  This number determines
7105 	 * how many retries must be performed before a reset can be issued
7106 	 * (for certain error conditions). This can be overridden by entries
7107 	 * in sd.conf or the device config table.
7108 	 */
7109 	un->un_reset_retry_count = (un->un_retry_count / 2);
7110 
7111 	/*
7112 	 * Set the victim_retry_count to the default un_retry_count
7113 	 */
7114 	un->un_victim_retry_count = (2 * un->un_retry_count);
7115 
7116 	/*
7117 	 * Set the reservation release timeout to the default value of
7118 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7119 	 * device config table.
7120 	 */
7121 	un->un_reserve_release_time = 5;
7122 
7123 	/*
7124 	 * Set up the default maximum transfer size. Note that this may
7125 	 * get updated later in the attach, when setting up default wide
7126 	 * operations for disks.
7127 	 */
7128 #if defined(__i386) || defined(__amd64)
7129 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7130 	un->un_partial_dma_supported = 1;
7131 #else
7132 	un->un_max_xfer_size = (uint_t)maxphys;
7133 #endif
7134 
7135 	/*
7136 	 * Get "allow bus device reset" property (defaults to "enabled" if
7137 	 * the property was not defined). This is to disable bus resets for
7138 	 * certain kinds of error recovery. Note: In the future when a run-time
7139 	 * fibre check is available the soft state flag should default to
7140 	 * enabled.
7141 	 */
7142 	if (un->un_f_is_fibre == TRUE) {
7143 		un->un_f_allow_bus_device_reset = TRUE;
7144 	} else {
7145 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7146 		    "allow-bus-device-reset", 1) != 0) {
7147 			un->un_f_allow_bus_device_reset = TRUE;
7148 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7149 			    "sd_unit_attach: un:0x%p Bus device reset "
7150 			    "enabled\n", un);
7151 		} else {
7152 			un->un_f_allow_bus_device_reset = FALSE;
7153 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7154 			    "sd_unit_attach: un:0x%p Bus device reset "
7155 			    "disabled\n", un);
7156 		}
7157 	}
7158 
7159 	/*
7160 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7161 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7162 	 *
7163 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7164 	 * property. The new "variant" property with a value of "atapi" has been
7165 	 * introduced so that future 'variants' of standard SCSI behavior (like
7166 	 * atapi) could be specified by the underlying HBA drivers by supplying
7167 	 * a new value for the "variant" property, instead of having to define a
7168 	 * new property.
7169 	 */
7170 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7171 		un->un_f_cfg_is_atapi = TRUE;
7172 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7173 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7174 	}
7175 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7176 	    &variantp) == DDI_PROP_SUCCESS) {
7177 		if (strcmp(variantp, "atapi") == 0) {
7178 			un->un_f_cfg_is_atapi = TRUE;
7179 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7180 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7181 		}
7182 		ddi_prop_free(variantp);
7183 	}
7184 
7185 	un->un_cmd_timeout	= SD_IO_TIME;
7186 
7187 	un->un_busy_timeout  = SD_BSY_TIMEOUT;
7188 
7189 	/* Info on current states, statuses, etc. (Updated frequently) */
7190 	un->un_state		= SD_STATE_NORMAL;
7191 	un->un_last_state	= SD_STATE_NORMAL;
7192 
7193 	/* Control & status info for command throttling */
7194 	un->un_throttle		= sd_max_throttle;
7195 	un->un_saved_throttle	= sd_max_throttle;
7196 	un->un_min_throttle	= sd_min_throttle;
7197 
7198 	if (un->un_f_is_fibre == TRUE) {
7199 		un->un_f_use_adaptive_throttle = TRUE;
7200 	} else {
7201 		un->un_f_use_adaptive_throttle = FALSE;
7202 	}
7203 
7204 	/* Removable media support. */
7205 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7206 	un->un_mediastate		= DKIO_NONE;
7207 	un->un_specified_mediastate	= DKIO_NONE;
7208 
7209 	/* CVs for suspend/resume (PM or DR) */
7210 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7211 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7212 
7213 	/* Power management support. */
7214 	un->un_power_level = SD_SPINDLE_UNINIT;
7215 
7216 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
7217 	un->un_f_wcc_inprog = 0;
7218 
7219 	/*
7220 	 * The open/close semaphore is used to serialize threads executing
7221 	 * in the driver's open & close entry point routines for a given
7222 	 * instance.
7223 	 */
7224 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
7225 
7226 	/*
7227 	 * The conf file entry and softstate variable is a forceful override,
7228 	 * meaning a non-zero value must be entered to change the default.
7229 	 */
7230 	un->un_f_disksort_disabled = FALSE;
7231 
7232 	/*
7233 	 * Retrieve the properties from the static driver table or the driver
7234 	 * configuration file (.conf) for this unit and update the soft state
7235 	 * for the device as needed for the indicated properties.
7236 	 * Note: the property configuration needs to occur here as some of the
7237 	 * following routines may have dependencies on soft state flags set
7238 	 * as part of the driver property configuration.
7239 	 */
7240 	sd_read_unit_properties(un);
7241 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7242 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
7243 
7244 	/*
7245 	 * Only if a device has "hotpluggable" property, it is
7246 	 * treated as hotpluggable device. Otherwise, it is
7247 	 * regarded as non-hotpluggable one.
7248 	 */
7249 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
7250 	    -1) != -1) {
7251 		un->un_f_is_hotpluggable = TRUE;
7252 	}
7253 
7254 	/*
7255 	 * set unit's attributes(flags) according to "hotpluggable" and
7256 	 * RMB bit in INQUIRY data.
7257 	 */
7258 	sd_set_unit_attributes(un, devi);
7259 
7260 	/*
7261 	 * By default, we mark the capacity, lbasize, and geometry
7262 	 * as invalid. Only if we successfully read a valid capacity
7263 	 * will we update the un_blockcount and un_tgt_blocksize with the
7264 	 * valid values (the geometry will be validated later).
7265 	 */
7266 	un->un_f_blockcount_is_valid	= FALSE;
7267 	un->un_f_tgt_blocksize_is_valid	= FALSE;
7268 
7269 	/*
7270 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
7271 	 * otherwise.
7272 	 */
7273 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
7274 	un->un_blockcount = 0;
7275 
7276 	/*
7277 	 * Set up the per-instance info needed to determine the correct
7278 	 * CDBs and other info for issuing commands to the target.
7279 	 */
7280 	sd_init_cdb_limits(un);
7281 
7282 	/*
7283 	 * Set up the IO chains to use, based upon the target type.
7284 	 */
7285 	if (un->un_f_non_devbsize_supported) {
7286 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7287 	} else {
7288 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7289 	}
7290 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7291 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
7292 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
7293 
7294 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
7295 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
7296 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
7297 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
7298 
7299 
7300 	if (ISCD(un)) {
7301 		un->un_additional_codes = sd_additional_codes;
7302 	} else {
7303 		un->un_additional_codes = NULL;
7304 	}
7305 
7306 	/*
7307 	 * Create the kstats here so they can be available for attach-time
7308 	 * routines that send commands to the unit (either polled or via
7309 	 * sd_send_scsi_cmd).
7310 	 *
7311 	 * Note: This is a critical sequence that needs to be maintained:
7312 	 *	1) Instantiate the kstats here, before any routines using the
7313 	 *	   iopath (i.e. sd_send_scsi_cmd).
7314 	 *	2) Instantiate and initialize the partition stats
7315 	 *	   (sd_set_pstats).
7316 	 *	3) Initialize the error stats (sd_set_errstats), following
7317 	 *	   sd_validate_geometry(),sd_register_devid(),
7318 	 *	   and sd_cache_control().
7319 	 */
7320 
7321 	un->un_stats = kstat_create(sd_label, instance,
7322 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
7323 	if (un->un_stats != NULL) {
7324 		un->un_stats->ks_lock = SD_MUTEX(un);
7325 		kstat_install(un->un_stats);
7326 	}
7327 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7328 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
7329 
7330 	sd_create_errstats(un, instance);
7331 	if (un->un_errstats == NULL) {
7332 		goto create_errstats_failed;
7333 	}
7334 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7335 	    "sd_unit_attach: un:0x%p errstats created\n", un);
7336 
7337 	/*
7338 	 * The following if/else code was relocated here from below as part
7339 	 * of the fix for bug (4430280). However with the default setup added
7340 	 * on entry to this routine, it's no longer absolutely necessary for
7341 	 * this to be before the call to sd_spin_up_unit.
7342 	 */
7343 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
7344 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
7345 		    (devp->sd_inq->inq_ansi == 5)) &&
7346 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
7347 
7348 		/*
7349 		 * If tagged queueing is supported by the target
7350 		 * and by the host adapter then we will enable it
7351 		 */
7352 		un->un_tagflags = 0;
7353 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
7354 		    (un->un_f_arq_enabled == TRUE)) {
7355 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
7356 			    1, 1) == 1) {
7357 				un->un_tagflags = FLAG_STAG;
7358 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7359 				    "sd_unit_attach: un:0x%p tag queueing "
7360 				    "enabled\n", un);
7361 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
7362 			    "untagged-qing", 0) == 1) {
7363 				un->un_f_opt_queueing = TRUE;
7364 				un->un_saved_throttle = un->un_throttle =
7365 				    min(un->un_throttle, 3);
7366 			} else {
7367 				un->un_f_opt_queueing = FALSE;
7368 				un->un_saved_throttle = un->un_throttle = 1;
7369 			}
7370 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
7371 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
7372 			/* The Host Adapter supports internal queueing. */
7373 			un->un_f_opt_queueing = TRUE;
7374 			un->un_saved_throttle = un->un_throttle =
7375 			    min(un->un_throttle, 3);
7376 		} else {
7377 			un->un_f_opt_queueing = FALSE;
7378 			un->un_saved_throttle = un->un_throttle = 1;
7379 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7380 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
7381 		}
7382 
7383 		/*
7384 		 * Enable large transfers for SATA/SAS drives
7385 		 */
7386 		if (SD_IS_SERIAL(un)) {
7387 			un->un_max_xfer_size =
7388 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7389 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7390 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7391 			    "sd_unit_attach: un:0x%p max transfer "
7392 			    "size=0x%x\n", un, un->un_max_xfer_size);
7393 
7394 		}
7395 
7396 		/* Setup or tear down default wide operations for disks */
7397 
7398 		/*
7399 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
7400 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
7401 		 * system and be set to different values. In the future this
7402 		 * code may need to be updated when the ssd module is
7403 		 * obsoleted and removed from the system. (4299588)
7404 		 */
7405 		if (SD_IS_PARALLEL_SCSI(un) &&
7406 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
7407 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
7408 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7409 			    1, 1) == 1) {
7410 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7411 				    "sd_unit_attach: un:0x%p Wide Transfer "
7412 				    "enabled\n", un);
7413 			}
7414 
7415 			/*
7416 			 * If tagged queuing has also been enabled, then
7417 			 * enable large xfers
7418 			 */
7419 			if (un->un_saved_throttle == sd_max_throttle) {
7420 				un->un_max_xfer_size =
7421 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7422 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7423 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7424 				    "sd_unit_attach: un:0x%p max transfer "
7425 				    "size=0x%x\n", un, un->un_max_xfer_size);
7426 			}
7427 		} else {
7428 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7429 			    0, 1) == 1) {
7430 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7431 				    "sd_unit_attach: un:0x%p "
7432 				    "Wide Transfer disabled\n", un);
7433 			}
7434 		}
7435 	} else {
7436 		un->un_tagflags = FLAG_STAG;
7437 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7438 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7439 	}
7440 
7441 	/*
7442 	 * If this target supports LUN reset, try to enable it.
7443 	 */
7444 	if (un->un_f_lun_reset_enabled) {
7445 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7446 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7447 			    "un:0x%p lun_reset capability set\n", un);
7448 		} else {
7449 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7450 			    "un:0x%p lun-reset capability not set\n", un);
7451 		}
7452 	}
7453 
7454 	/*
7455 	 * Adjust the maximum transfer size. This is to fix
7456 	 * the problem of partial DMA support on SPARC. Some
7457 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7458 	 * size, which requires partial DMA support on SPARC.
7459 	 * In the future the SPARC pci nexus driver may solve
7460 	 * the problem instead of this fix.
7461 	 */
7462 #if defined(__sparc)
7463 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7464 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7465 		un->un_max_xfer_size = max_xfer_size;
7466 		un->un_partial_dma_supported = 1;
7467 	}
7468 #endif
7469 
7470 	/*
7471 	 * Set PKT_DMA_PARTIAL flag.
7472 	 */
7473 	if (un->un_partial_dma_supported == 1) {
7474 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7475 	} else {
7476 		un->un_pkt_flags = 0;
7477 	}
7478 
7479 	/* Initialize sd_ssc_t for internal uscsi commands */
7480 	ssc = sd_ssc_init(un);
7481 	scsi_fm_init(devp);
7482 
7483 	/*
7484 	 * Allocate memory for SCSI FMA stuffs.
7485 	 */
7486 	un->un_fm_private =
7487 	    kmem_zalloc(sizeof (struct sd_fm_internal), KM_SLEEP);
7488 	sfip = (struct sd_fm_internal *)un->un_fm_private;
7489 	sfip->fm_ssc.ssc_uscsi_cmd = &sfip->fm_ucmd;
7490 	sfip->fm_ssc.ssc_uscsi_info = &sfip->fm_uinfo;
7491 	sfip->fm_ssc.ssc_un = un;
7492 
7493 	if (ISCD(un) ||
7494 	    un->un_f_has_removable_media ||
7495 	    devp->sd_fm_capable == DDI_FM_NOT_CAPABLE) {
7496 		/*
7497 		 * We don't touch CDROM or the DDI_FM_NOT_CAPABLE device.
7498 		 * Their log are unchanged.
7499 		 */
7500 		sfip->fm_log_level = SD_FM_LOG_NSUP;
7501 	} else {
7502 		/*
7503 		 * If enter here, it should be non-CDROM and FM-capable
7504 		 * device, and it will not keep the old scsi_log as before
7505 		 * in /var/adm/messages. However, the property
7506 		 * "fm-scsi-log" will control whether the FM telemetry will
7507 		 * be logged in /var/adm/messages.
7508 		 */
7509 		int fm_scsi_log;
7510 		fm_scsi_log = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7511 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "fm-scsi-log", 0);
7512 
7513 		if (fm_scsi_log)
7514 			sfip->fm_log_level = SD_FM_LOG_EREPORT;
7515 		else
7516 			sfip->fm_log_level = SD_FM_LOG_SILENT;
7517 	}
7518 
7519 	/*
7520 	 * At this point in the attach, we have enough info in the
7521 	 * soft state to be able to issue commands to the target.
7522 	 *
7523 	 * All command paths used below MUST issue their commands as
7524 	 * SD_PATH_DIRECT. This is important as intermediate layers
7525 	 * are not all initialized yet (such as PM).
7526 	 */
7527 
7528 	/*
7529 	 * Send a TEST UNIT READY command to the device. This should clear
7530 	 * any outstanding UNIT ATTENTION that may be present.
7531 	 *
7532 	 * Note: Don't check for success, just track if there is a reservation,
7533 	 * this is a throw away command to clear any unit attentions.
7534 	 *
7535 	 * Note: This MUST be the first command issued to the target during
7536 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7537 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7538 	 * with attempts at spinning up a device with no media.
7539 	 */
7540 	status = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
7541 	if (status != 0) {
7542 		if (status == EACCES)
7543 			reservation_flag = SD_TARGET_IS_RESERVED;
7544 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7545 	}
7546 
7547 	/*
7548 	 * If the device is NOT a removable media device, attempt to spin
7549 	 * it up (using the START_STOP_UNIT command) and read its capacity
7550 	 * (using the READ CAPACITY command).  Note, however, that either
7551 	 * of these could fail and in some cases we would continue with
7552 	 * the attach despite the failure (see below).
7553 	 */
7554 	if (un->un_f_descr_format_supported) {
7555 
7556 		switch (sd_spin_up_unit(ssc)) {
7557 		case 0:
7558 			/*
7559 			 * Spin-up was successful; now try to read the
7560 			 * capacity.  If successful then save the results
7561 			 * and mark the capacity & lbasize as valid.
7562 			 */
7563 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7564 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7565 
7566 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
7567 			    &lbasize, SD_PATH_DIRECT);
7568 
7569 			switch (status) {
7570 			case 0: {
7571 				if (capacity > DK_MAX_BLOCKS) {
7572 #ifdef _LP64
7573 					if ((capacity + 1) >
7574 					    SD_GROUP1_MAX_ADDRESS) {
7575 						/*
7576 						 * Enable descriptor format
7577 						 * sense data so that we can
7578 						 * get 64 bit sense data
7579 						 * fields.
7580 						 */
7581 						sd_enable_descr_sense(ssc);
7582 					}
7583 #else
7584 					/* 32-bit kernels can't handle this */
7585 					scsi_log(SD_DEVINFO(un),
7586 					    sd_label, CE_WARN,
7587 					    "disk has %llu blocks, which "
7588 					    "is too large for a 32-bit "
7589 					    "kernel", capacity);
7590 
7591 #if defined(__i386) || defined(__amd64)
7592 					/*
7593 					 * 1TB disk was treated as (1T - 512)B
7594 					 * in the past, so that it might have
7595 					 * valid VTOC and solaris partitions,
7596 					 * we have to allow it to continue to
7597 					 * work.
7598 					 */
7599 					if (capacity -1 > DK_MAX_BLOCKS)
7600 #endif
7601 					goto spinup_failed;
7602 #endif
7603 				}
7604 
7605 				/*
7606 				 * Here it's not necessary to check the case:
7607 				 * the capacity of the device is bigger than
7608 				 * what the max hba cdb can support. Because
7609 				 * sd_send_scsi_READ_CAPACITY will retrieve
7610 				 * the capacity by sending USCSI command, which
7611 				 * is constrained by the max hba cdb. Actually,
7612 				 * sd_send_scsi_READ_CAPACITY will return
7613 				 * EINVAL when using bigger cdb than required
7614 				 * cdb length. Will handle this case in
7615 				 * "case EINVAL".
7616 				 */
7617 
7618 				/*
7619 				 * The following relies on
7620 				 * sd_send_scsi_READ_CAPACITY never
7621 				 * returning 0 for capacity and/or lbasize.
7622 				 */
7623 				sd_update_block_info(un, lbasize, capacity);
7624 
7625 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7626 				    "sd_unit_attach: un:0x%p capacity = %ld "
7627 				    "blocks; lbasize= %ld.\n", un,
7628 				    un->un_blockcount, un->un_tgt_blocksize);
7629 
7630 				break;
7631 			}
7632 			case EINVAL:
7633 				/*
7634 				 * In the case where the max-cdb-length property
7635 				 * is smaller than the required CDB length for
7636 				 * a SCSI device, a target driver can fail to
7637 				 * attach to that device.
7638 				 */
7639 				scsi_log(SD_DEVINFO(un),
7640 				    sd_label, CE_WARN,
7641 				    "disk capacity is too large "
7642 				    "for current cdb length");
7643 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7644 
7645 				goto spinup_failed;
7646 			case EACCES:
7647 				/*
7648 				 * Should never get here if the spin-up
7649 				 * succeeded, but code it in anyway.
7650 				 * From here, just continue with the attach...
7651 				 */
7652 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7653 				    "sd_unit_attach: un:0x%p "
7654 				    "sd_send_scsi_READ_CAPACITY "
7655 				    "returned reservation conflict\n", un);
7656 				reservation_flag = SD_TARGET_IS_RESERVED;
7657 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7658 				break;
7659 			default:
7660 				/*
7661 				 * Likewise, should never get here if the
7662 				 * spin-up succeeded. Just continue with
7663 				 * the attach...
7664 				 */
7665 				if (status == EIO)
7666 					sd_ssc_assessment(ssc,
7667 					    SD_FMT_STATUS_CHECK);
7668 				else
7669 					sd_ssc_assessment(ssc,
7670 					    SD_FMT_IGNORE);
7671 				break;
7672 			}
7673 			break;
7674 		case EACCES:
7675 			/*
7676 			 * Device is reserved by another host.  In this case
7677 			 * we could not spin it up or read the capacity, but
7678 			 * we continue with the attach anyway.
7679 			 */
7680 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7681 			    "sd_unit_attach: un:0x%p spin-up reservation "
7682 			    "conflict.\n", un);
7683 			reservation_flag = SD_TARGET_IS_RESERVED;
7684 			break;
7685 		default:
7686 			/* Fail the attach if the spin-up failed. */
7687 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7688 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
7689 			goto spinup_failed;
7690 		}
7691 
7692 	}
7693 
7694 	/*
7695 	 * Check to see if this is a MMC drive
7696 	 */
7697 	if (ISCD(un)) {
7698 		sd_set_mmc_caps(ssc);
7699 	}
7700 
7701 
7702 	/*
7703 	 * Add a zero-length attribute to tell the world we support
7704 	 * kernel ioctls (for layered drivers)
7705 	 */
7706 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7707 	    DDI_KERNEL_IOCTL, NULL, 0);
7708 
7709 	/*
7710 	 * Add a boolean property to tell the world we support
7711 	 * the B_FAILFAST flag (for layered drivers)
7712 	 */
7713 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7714 	    "ddi-failfast-supported", NULL, 0);
7715 
7716 	/*
7717 	 * Initialize power management
7718 	 */
7719 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
7720 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
7721 	sd_setup_pm(ssc, devi);
7722 	if (un->un_f_pm_is_enabled == FALSE) {
7723 		/*
7724 		 * For performance, point to a jump table that does
7725 		 * not include pm.
7726 		 * The direct and priority chains don't change with PM.
7727 		 *
7728 		 * Note: this is currently done based on individual device
7729 		 * capabilities. When an interface for determining system
7730 		 * power enabled state becomes available, or when additional
7731 		 * layers are added to the command chain, these values will
7732 		 * have to be re-evaluated for correctness.
7733 		 */
7734 		if (un->un_f_non_devbsize_supported) {
7735 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
7736 		} else {
7737 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
7738 		}
7739 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
7740 	}
7741 
7742 	/*
7743 	 * This property is set to 0 by HA software to avoid retries
7744 	 * on a reserved disk. (The preferred property name is
7745 	 * "retry-on-reservation-conflict") (1189689)
7746 	 *
7747 	 * Note: The use of a global here can have unintended consequences. A
7748 	 * per instance variable is preferable to match the capabilities of
7749 	 * different underlying hba's (4402600)
7750 	 */
7751 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
7752 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
7753 	    sd_retry_on_reservation_conflict);
7754 	if (sd_retry_on_reservation_conflict != 0) {
7755 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
7756 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
7757 		    sd_retry_on_reservation_conflict);
7758 	}
7759 
7760 	/* Set up options for QFULL handling. */
7761 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7762 	    "qfull-retries", -1)) != -1) {
7763 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
7764 		    rval, 1);
7765 	}
7766 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7767 	    "qfull-retry-interval", -1)) != -1) {
7768 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
7769 		    rval, 1);
7770 	}
7771 
7772 	/*
7773 	 * This just prints a message that announces the existence of the
7774 	 * device. The message is always printed in the system logfile, but
7775 	 * only appears on the console if the system is booted with the
7776 	 * -v (verbose) argument.
7777 	 */
7778 	ddi_report_dev(devi);
7779 
7780 	un->un_mediastate = DKIO_NONE;
7781 
7782 	cmlb_alloc_handle(&un->un_cmlbhandle);
7783 
7784 #if defined(__i386) || defined(__amd64)
7785 	/*
7786 	 * On x86, compensate for off-by-1 legacy error
7787 	 */
7788 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
7789 	    (lbasize == un->un_sys_blocksize))
7790 		offbyone = CMLB_OFF_BY_ONE;
7791 #endif
7792 
7793 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
7794 	    un->un_f_has_removable_media, un->un_f_is_hotpluggable,
7795 	    un->un_node_type, offbyone, un->un_cmlbhandle,
7796 	    (void *)SD_PATH_DIRECT) != 0) {
7797 		goto cmlb_attach_failed;
7798 	}
7799 
7800 
7801 	/*
7802 	 * Read and validate the device's geometry (ie, disk label)
7803 	 * A new unformatted drive will not have a valid geometry, but
7804 	 * the driver needs to successfully attach to this device so
7805 	 * the drive can be formatted via ioctls.
7806 	 */
7807 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
7808 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
7809 
7810 	mutex_enter(SD_MUTEX(un));
7811 
7812 	/*
7813 	 * Read and initialize the devid for the unit.
7814 	 */
7815 	if (un->un_f_devid_supported) {
7816 		sd_register_devid(ssc, devi, reservation_flag);
7817 	}
7818 	mutex_exit(SD_MUTEX(un));
7819 
7820 #if (defined(__fibre))
7821 	/*
7822 	 * Register callbacks for fibre only.  You can't do this solely
7823 	 * on the basis of the devid_type because this is hba specific.
7824 	 * We need to query our hba capabilities to find out whether to
7825 	 * register or not.
7826 	 */
7827 	if (un->un_f_is_fibre) {
7828 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
7829 			sd_init_event_callbacks(un);
7830 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7831 			    "sd_unit_attach: un:0x%p event callbacks inserted",
7832 			    un);
7833 		}
7834 	}
7835 #endif
7836 
7837 	if (un->un_f_opt_disable_cache == TRUE) {
7838 		/*
7839 		 * Disable both read cache and write cache.  This is
7840 		 * the historic behavior of the keywords in the config file.
7841 		 */
7842 		if (sd_cache_control(ssc, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
7843 		    0) {
7844 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7845 			    "sd_unit_attach: un:0x%p Could not disable "
7846 			    "caching", un);
7847 			goto devid_failed;
7848 		}
7849 	}
7850 
7851 	/*
7852 	 * Check the value of the WCE bit now and
7853 	 * set un_f_write_cache_enabled accordingly.
7854 	 */
7855 	(void) sd_get_write_cache_enabled(ssc, &wc_enabled);
7856 	mutex_enter(SD_MUTEX(un));
7857 	un->un_f_write_cache_enabled = (wc_enabled != 0);
7858 	mutex_exit(SD_MUTEX(un));
7859 
7860 	/*
7861 	 * Check the value of the NV_SUP bit and set
7862 	 * un_f_suppress_cache_flush accordingly.
7863 	 */
7864 	sd_get_nv_sup(ssc);
7865 
7866 	/*
7867 	 * Find out what type of reservation this disk supports.
7868 	 */
7869 	status = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS, 0, NULL);
7870 
7871 	switch (status) {
7872 	case 0:
7873 		/*
7874 		 * SCSI-3 reservations are supported.
7875 		 */
7876 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7877 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7878 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
7879 		break;
7880 	case ENOTSUP:
7881 		/*
7882 		 * The PERSISTENT RESERVE IN command would not be recognized by
7883 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
7884 		 */
7885 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7886 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
7887 		un->un_reservation_type = SD_SCSI2_RESERVATION;
7888 
7889 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7890 		break;
7891 	default:
7892 		/*
7893 		 * default to SCSI-3 reservations
7894 		 */
7895 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7896 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
7897 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7898 
7899 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7900 		break;
7901 	}
7902 
7903 	/*
7904 	 * Set the pstat and error stat values here, so data obtained during the
7905 	 * previous attach-time routines is available.
7906 	 *
7907 	 * Note: This is a critical sequence that needs to be maintained:
7908 	 *	1) Instantiate the kstats before any routines using the iopath
7909 	 *	   (i.e. sd_send_scsi_cmd).
7910 	 *	2) Initialize the error stats (sd_set_errstats) and partition
7911 	 *	   stats (sd_set_pstats)here, following
7912 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
7913 	 *	   sd_cache_control().
7914 	 */
7915 
7916 	if (un->un_f_pkstats_enabled && geom_label_valid) {
7917 		sd_set_pstats(un);
7918 		SD_TRACE(SD_LOG_IO_PARTITION, un,
7919 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
7920 	}
7921 
7922 	sd_set_errstats(un);
7923 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7924 	    "sd_unit_attach: un:0x%p errstats set\n", un);
7925 
7926 
7927 	/*
7928 	 * After successfully attaching an instance, we record the information
7929 	 * of how many luns have been attached on the relative target and
7930 	 * controller for parallel SCSI. This information is used when sd tries
7931 	 * to set the tagged queuing capability in HBA.
7932 	 */
7933 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7934 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
7935 	}
7936 
7937 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7938 	    "sd_unit_attach: un:0x%p exit success\n", un);
7939 
7940 	/* Uninitialize sd_ssc_t pointer */
7941 	sd_ssc_fini(ssc);
7942 
7943 	return (DDI_SUCCESS);
7944 
7945 	/*
7946 	 * An error occurred during the attach; clean up & return failure.
7947 	 */
7948 
7949 devid_failed:
7950 
7951 setup_pm_failed:
7952 	ddi_remove_minor_node(devi, NULL);
7953 
7954 cmlb_attach_failed:
7955 	/*
7956 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7957 	 */
7958 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7959 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7960 
7961 	/*
7962 	 * Refer to the comments of setting tagged-qing in the beginning of
7963 	 * sd_unit_attach. We can only disable tagged queuing when there is
7964 	 * no lun attached on the target.
7965 	 */
7966 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7967 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7968 	}
7969 
7970 	if (un->un_f_is_fibre == FALSE) {
7971 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7972 	}
7973 
7974 spinup_failed:
7975 
7976 	/* Uninitialize sd_ssc_t pointer */
7977 	sd_ssc_fini(ssc);
7978 
7979 	mutex_enter(SD_MUTEX(un));
7980 
7981 	/* Deallocate SCSI FMA memory spaces */
7982 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
7983 
7984 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
7985 	if (un->un_direct_priority_timeid != NULL) {
7986 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7987 		un->un_direct_priority_timeid = NULL;
7988 		mutex_exit(SD_MUTEX(un));
7989 		(void) untimeout(temp_id);
7990 		mutex_enter(SD_MUTEX(un));
7991 	}
7992 
7993 	/* Cancel any pending start/stop timeouts */
7994 	if (un->un_startstop_timeid != NULL) {
7995 		timeout_id_t temp_id = un->un_startstop_timeid;
7996 		un->un_startstop_timeid = NULL;
7997 		mutex_exit(SD_MUTEX(un));
7998 		(void) untimeout(temp_id);
7999 		mutex_enter(SD_MUTEX(un));
8000 	}
8001 
8002 	/* Cancel any pending reset-throttle timeouts */
8003 	if (un->un_reset_throttle_timeid != NULL) {
8004 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8005 		un->un_reset_throttle_timeid = NULL;
8006 		mutex_exit(SD_MUTEX(un));
8007 		(void) untimeout(temp_id);
8008 		mutex_enter(SD_MUTEX(un));
8009 	}
8010 
8011 	/* Cancel any pending retry timeouts */
8012 	if (un->un_retry_timeid != NULL) {
8013 		timeout_id_t temp_id = un->un_retry_timeid;
8014 		un->un_retry_timeid = NULL;
8015 		mutex_exit(SD_MUTEX(un));
8016 		(void) untimeout(temp_id);
8017 		mutex_enter(SD_MUTEX(un));
8018 	}
8019 
8020 	/* Cancel any pending delayed cv broadcast timeouts */
8021 	if (un->un_dcvb_timeid != NULL) {
8022 		timeout_id_t temp_id = un->un_dcvb_timeid;
8023 		un->un_dcvb_timeid = NULL;
8024 		mutex_exit(SD_MUTEX(un));
8025 		(void) untimeout(temp_id);
8026 		mutex_enter(SD_MUTEX(un));
8027 	}
8028 
8029 	mutex_exit(SD_MUTEX(un));
8030 
8031 	/* There should not be any in-progress I/O so ASSERT this check */
8032 	ASSERT(un->un_ncmds_in_transport == 0);
8033 	ASSERT(un->un_ncmds_in_driver == 0);
8034 
8035 	/* Do not free the softstate if the callback routine is active */
8036 	sd_sync_with_callback(un);
8037 
8038 	/*
8039 	 * Partition stats apparently are not used with removables. These would
8040 	 * not have been created during attach, so no need to clean them up...
8041 	 */
8042 	if (un->un_errstats != NULL) {
8043 		kstat_delete(un->un_errstats);
8044 		un->un_errstats = NULL;
8045 	}
8046 
8047 create_errstats_failed:
8048 
8049 	if (un->un_stats != NULL) {
8050 		kstat_delete(un->un_stats);
8051 		un->un_stats = NULL;
8052 	}
8053 
8054 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8055 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8056 
8057 	ddi_prop_remove_all(devi);
8058 	sema_destroy(&un->un_semoclose);
8059 	cv_destroy(&un->un_state_cv);
8060 
8061 getrbuf_failed:
8062 
8063 	sd_free_rqs(un);
8064 
8065 alloc_rqs_failed:
8066 
8067 	devp->sd_private = NULL;
8068 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8069 
8070 get_softstate_failed:
8071 	/*
8072 	 * Note: the man pages are unclear as to whether or not doing a
8073 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8074 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8075 	 * ddi_get_soft_state() fails.  The implication seems to be
8076 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8077 	 */
8078 	ddi_soft_state_free(sd_state, instance);
8079 
8080 probe_failed:
8081 	scsi_unprobe(devp);
8082 
8083 	return (DDI_FAILURE);
8084 }
8085 
8086 
8087 /*
8088  *    Function: sd_unit_detach
8089  *
8090  * Description: Performs DDI_DETACH processing for sddetach().
8091  *
8092  * Return Code: DDI_SUCCESS
8093  *		DDI_FAILURE
8094  *
8095  *     Context: Kernel thread context
8096  */
8097 
8098 static int
8099 sd_unit_detach(dev_info_t *devi)
8100 {
8101 	struct scsi_device	*devp;
8102 	struct sd_lun		*un;
8103 	int			i;
8104 	int			tgt;
8105 	dev_t			dev;
8106 	dev_info_t		*pdip = ddi_get_parent(devi);
8107 	int			instance = ddi_get_instance(devi);
8108 
8109 	mutex_enter(&sd_detach_mutex);
8110 
8111 	/*
8112 	 * Fail the detach for any of the following:
8113 	 *  - Unable to get the sd_lun struct for the instance
8114 	 *  - A layered driver has an outstanding open on the instance
8115 	 *  - Another thread is already detaching this instance
8116 	 *  - Another thread is currently performing an open
8117 	 */
8118 	devp = ddi_get_driver_private(devi);
8119 	if ((devp == NULL) ||
8120 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8121 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
8122 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
8123 		mutex_exit(&sd_detach_mutex);
8124 		return (DDI_FAILURE);
8125 	}
8126 
8127 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8128 
8129 	/*
8130 	 * Mark this instance as currently in a detach, to inhibit any
8131 	 * opens from a layered driver.
8132 	 */
8133 	un->un_detach_count++;
8134 	mutex_exit(&sd_detach_mutex);
8135 
8136 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
8137 	    SCSI_ADDR_PROP_TARGET, -1);
8138 
8139 	dev = sd_make_device(SD_DEVINFO(un));
8140 
8141 #ifndef lint
8142 	_NOTE(COMPETING_THREADS_NOW);
8143 #endif
8144 
8145 	mutex_enter(SD_MUTEX(un));
8146 
8147 	/*
8148 	 * Fail the detach if there are any outstanding layered
8149 	 * opens on this device.
8150 	 */
8151 	for (i = 0; i < NDKMAP; i++) {
8152 		if (un->un_ocmap.lyropen[i] != 0) {
8153 			goto err_notclosed;
8154 		}
8155 	}
8156 
8157 	/*
8158 	 * Verify there are NO outstanding commands issued to this device.
8159 	 * ie, un_ncmds_in_transport == 0.
8160 	 * It's possible to have outstanding commands through the physio
8161 	 * code path, even though everything's closed.
8162 	 */
8163 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8164 	    (un->un_direct_priority_timeid != NULL) ||
8165 	    (un->un_state == SD_STATE_RWAIT)) {
8166 		mutex_exit(SD_MUTEX(un));
8167 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8168 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8169 		goto err_stillbusy;
8170 	}
8171 
8172 	/*
8173 	 * If we have the device reserved, release the reservation.
8174 	 */
8175 	if ((un->un_resvd_status & SD_RESERVE) &&
8176 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8177 		mutex_exit(SD_MUTEX(un));
8178 		/*
8179 		 * Note: sd_reserve_release sends a command to the device
8180 		 * via the sd_ioctlcmd() path, and can sleep.
8181 		 */
8182 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8183 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8184 			    "sd_dr_detach: Cannot release reservation \n");
8185 		}
8186 	} else {
8187 		mutex_exit(SD_MUTEX(un));
8188 	}
8189 
8190 	/*
8191 	 * Untimeout any reserve recover, throttle reset, restart unit
8192 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8193 	 * from getting nulled by their callback functions.
8194 	 */
8195 	mutex_enter(SD_MUTEX(un));
8196 	if (un->un_resvd_timeid != NULL) {
8197 		timeout_id_t temp_id = un->un_resvd_timeid;
8198 		un->un_resvd_timeid = NULL;
8199 		mutex_exit(SD_MUTEX(un));
8200 		(void) untimeout(temp_id);
8201 		mutex_enter(SD_MUTEX(un));
8202 	}
8203 
8204 	if (un->un_reset_throttle_timeid != NULL) {
8205 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8206 		un->un_reset_throttle_timeid = NULL;
8207 		mutex_exit(SD_MUTEX(un));
8208 		(void) untimeout(temp_id);
8209 		mutex_enter(SD_MUTEX(un));
8210 	}
8211 
8212 	if (un->un_startstop_timeid != NULL) {
8213 		timeout_id_t temp_id = un->un_startstop_timeid;
8214 		un->un_startstop_timeid = NULL;
8215 		mutex_exit(SD_MUTEX(un));
8216 		(void) untimeout(temp_id);
8217 		mutex_enter(SD_MUTEX(un));
8218 	}
8219 
8220 	if (un->un_dcvb_timeid != NULL) {
8221 		timeout_id_t temp_id = un->un_dcvb_timeid;
8222 		un->un_dcvb_timeid = NULL;
8223 		mutex_exit(SD_MUTEX(un));
8224 		(void) untimeout(temp_id);
8225 	} else {
8226 		mutex_exit(SD_MUTEX(un));
8227 	}
8228 
8229 	/* Remove any pending reservation reclaim requests for this device */
8230 	sd_rmv_resv_reclaim_req(dev);
8231 
8232 	mutex_enter(SD_MUTEX(un));
8233 
8234 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8235 	if (un->un_direct_priority_timeid != NULL) {
8236 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8237 		un->un_direct_priority_timeid = NULL;
8238 		mutex_exit(SD_MUTEX(un));
8239 		(void) untimeout(temp_id);
8240 		mutex_enter(SD_MUTEX(un));
8241 	}
8242 
8243 	/* Cancel any active multi-host disk watch thread requests */
8244 	if (un->un_mhd_token != NULL) {
8245 		mutex_exit(SD_MUTEX(un));
8246 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8247 		if (scsi_watch_request_terminate(un->un_mhd_token,
8248 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8249 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8250 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8251 			/*
8252 			 * Note: We are returning here after having removed
8253 			 * some driver timeouts above. This is consistent with
8254 			 * the legacy implementation but perhaps the watch
8255 			 * terminate call should be made with the wait flag set.
8256 			 */
8257 			goto err_stillbusy;
8258 		}
8259 		mutex_enter(SD_MUTEX(un));
8260 		un->un_mhd_token = NULL;
8261 	}
8262 
8263 	if (un->un_swr_token != NULL) {
8264 		mutex_exit(SD_MUTEX(un));
8265 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8266 		if (scsi_watch_request_terminate(un->un_swr_token,
8267 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8268 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8269 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8270 			/*
8271 			 * Note: We are returning here after having removed
8272 			 * some driver timeouts above. This is consistent with
8273 			 * the legacy implementation but perhaps the watch
8274 			 * terminate call should be made with the wait flag set.
8275 			 */
8276 			goto err_stillbusy;
8277 		}
8278 		mutex_enter(SD_MUTEX(un));
8279 		un->un_swr_token = NULL;
8280 	}
8281 
8282 	mutex_exit(SD_MUTEX(un));
8283 
8284 	/*
8285 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8286 	 * if we have not registered one.
8287 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8288 	 */
8289 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8290 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8291 
8292 	/*
8293 	 * protect the timeout pointers from getting nulled by
8294 	 * their callback functions during the cancellation process.
8295 	 * In such a scenario untimeout can be invoked with a null value.
8296 	 */
8297 	_NOTE(NO_COMPETING_THREADS_NOW);
8298 
8299 	mutex_enter(&un->un_pm_mutex);
8300 	if (un->un_pm_idle_timeid != NULL) {
8301 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8302 		un->un_pm_idle_timeid = NULL;
8303 		mutex_exit(&un->un_pm_mutex);
8304 
8305 		/*
8306 		 * Timeout is active; cancel it.
8307 		 * Note that it'll never be active on a device
8308 		 * that does not support PM therefore we don't
8309 		 * have to check before calling pm_idle_component.
8310 		 */
8311 		(void) untimeout(temp_id);
8312 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8313 		mutex_enter(&un->un_pm_mutex);
8314 	}
8315 
8316 	/*
8317 	 * Check whether there is already a timeout scheduled for power
8318 	 * management. If yes then don't lower the power here, that's.
8319 	 * the timeout handler's job.
8320 	 */
8321 	if (un->un_pm_timeid != NULL) {
8322 		timeout_id_t temp_id = un->un_pm_timeid;
8323 		un->un_pm_timeid = NULL;
8324 		mutex_exit(&un->un_pm_mutex);
8325 		/*
8326 		 * Timeout is active; cancel it.
8327 		 * Note that it'll never be active on a device
8328 		 * that does not support PM therefore we don't
8329 		 * have to check before calling pm_idle_component.
8330 		 */
8331 		(void) untimeout(temp_id);
8332 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8333 
8334 	} else {
8335 		mutex_exit(&un->un_pm_mutex);
8336 		if ((un->un_f_pm_is_enabled == TRUE) &&
8337 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_SPINDLE_OFF) !=
8338 		    DDI_SUCCESS)) {
8339 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8340 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8341 			/*
8342 			 * Fix for bug: 4297749, item # 13
8343 			 * The above test now includes a check to see if PM is
8344 			 * supported by this device before call
8345 			 * pm_lower_power().
8346 			 * Note, the following is not dead code. The call to
8347 			 * pm_lower_power above will generate a call back into
8348 			 * our sdpower routine which might result in a timeout
8349 			 * handler getting activated. Therefore the following
8350 			 * code is valid and necessary.
8351 			 */
8352 			mutex_enter(&un->un_pm_mutex);
8353 			if (un->un_pm_timeid != NULL) {
8354 				timeout_id_t temp_id = un->un_pm_timeid;
8355 				un->un_pm_timeid = NULL;
8356 				mutex_exit(&un->un_pm_mutex);
8357 				(void) untimeout(temp_id);
8358 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8359 			} else {
8360 				mutex_exit(&un->un_pm_mutex);
8361 			}
8362 		}
8363 	}
8364 
8365 	/*
8366 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8367 	 * Relocated here from above to be after the call to
8368 	 * pm_lower_power, which was getting errors.
8369 	 */
8370 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8371 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8372 
8373 	/*
8374 	 * Currently, tagged queuing is supported per target based by HBA.
8375 	 * Setting this per lun instance actually sets the capability of this
8376 	 * target in HBA, which affects those luns already attached on the
8377 	 * same target. So during detach, we can only disable this capability
8378 	 * only when this is the only lun left on this target. By doing
8379 	 * this, we assume a target has the same tagged queuing capability
8380 	 * for every lun. The condition can be removed when HBA is changed to
8381 	 * support per lun based tagged queuing capability.
8382 	 */
8383 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
8384 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8385 	}
8386 
8387 	if (un->un_f_is_fibre == FALSE) {
8388 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8389 	}
8390 
8391 	/*
8392 	 * Remove any event callbacks, fibre only
8393 	 */
8394 	if (un->un_f_is_fibre == TRUE) {
8395 		if ((un->un_insert_event != NULL) &&
8396 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
8397 		    DDI_SUCCESS)) {
8398 			/*
8399 			 * Note: We are returning here after having done
8400 			 * substantial cleanup above. This is consistent
8401 			 * with the legacy implementation but this may not
8402 			 * be the right thing to do.
8403 			 */
8404 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8405 			    "sd_dr_detach: Cannot cancel insert event\n");
8406 			goto err_remove_event;
8407 		}
8408 		un->un_insert_event = NULL;
8409 
8410 		if ((un->un_remove_event != NULL) &&
8411 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
8412 		    DDI_SUCCESS)) {
8413 			/*
8414 			 * Note: We are returning here after having done
8415 			 * substantial cleanup above. This is consistent
8416 			 * with the legacy implementation but this may not
8417 			 * be the right thing to do.
8418 			 */
8419 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8420 			    "sd_dr_detach: Cannot cancel remove event\n");
8421 			goto err_remove_event;
8422 		}
8423 		un->un_remove_event = NULL;
8424 	}
8425 
8426 	/* Do not free the softstate if the callback routine is active */
8427 	sd_sync_with_callback(un);
8428 
8429 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
8430 	cmlb_free_handle(&un->un_cmlbhandle);
8431 
8432 	/*
8433 	 * Hold the detach mutex here, to make sure that no other threads ever
8434 	 * can access a (partially) freed soft state structure.
8435 	 */
8436 	mutex_enter(&sd_detach_mutex);
8437 
8438 	/*
8439 	 * Clean up the soft state struct.
8440 	 * Cleanup is done in reverse order of allocs/inits.
8441 	 * At this point there should be no competing threads anymore.
8442 	 */
8443 
8444 	scsi_fm_fini(devp);
8445 
8446 	/*
8447 	 * Deallocate memory for SCSI FMA.
8448 	 */
8449 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8450 
8451 	/* Unregister and free device id. */
8452 	ddi_devid_unregister(devi);
8453 	if (un->un_devid) {
8454 		ddi_devid_free(un->un_devid);
8455 		un->un_devid = NULL;
8456 	}
8457 
8458 	/*
8459 	 * Destroy wmap cache if it exists.
8460 	 */
8461 	if (un->un_wm_cache != NULL) {
8462 		kmem_cache_destroy(un->un_wm_cache);
8463 		un->un_wm_cache = NULL;
8464 	}
8465 
8466 	/*
8467 	 * kstat cleanup is done in detach for all device types (4363169).
8468 	 * We do not want to fail detach if the device kstats are not deleted
8469 	 * since there is a confusion about the devo_refcnt for the device.
8470 	 * We just delete the kstats and let detach complete successfully.
8471 	 */
8472 	if (un->un_stats != NULL) {
8473 		kstat_delete(un->un_stats);
8474 		un->un_stats = NULL;
8475 	}
8476 	if (un->un_errstats != NULL) {
8477 		kstat_delete(un->un_errstats);
8478 		un->un_errstats = NULL;
8479 	}
8480 
8481 	/* Remove partition stats */
8482 	if (un->un_f_pkstats_enabled) {
8483 		for (i = 0; i < NSDMAP; i++) {
8484 			if (un->un_pstats[i] != NULL) {
8485 				kstat_delete(un->un_pstats[i]);
8486 				un->un_pstats[i] = NULL;
8487 			}
8488 		}
8489 	}
8490 
8491 	/* Remove xbuf registration */
8492 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8493 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8494 
8495 	/* Remove driver properties */
8496 	ddi_prop_remove_all(devi);
8497 
8498 	mutex_destroy(&un->un_pm_mutex);
8499 	cv_destroy(&un->un_pm_busy_cv);
8500 
8501 	cv_destroy(&un->un_wcc_cv);
8502 
8503 	/* Open/close semaphore */
8504 	sema_destroy(&un->un_semoclose);
8505 
8506 	/* Removable media condvar. */
8507 	cv_destroy(&un->un_state_cv);
8508 
8509 	/* Suspend/resume condvar. */
8510 	cv_destroy(&un->un_suspend_cv);
8511 	cv_destroy(&un->un_disk_busy_cv);
8512 
8513 	sd_free_rqs(un);
8514 
8515 	/* Free up soft state */
8516 	devp->sd_private = NULL;
8517 
8518 	bzero(un, sizeof (struct sd_lun));
8519 	ddi_soft_state_free(sd_state, instance);
8520 
8521 	mutex_exit(&sd_detach_mutex);
8522 
8523 	/* This frees up the INQUIRY data associated with the device. */
8524 	scsi_unprobe(devp);
8525 
8526 	/*
8527 	 * After successfully detaching an instance, we update the information
8528 	 * of how many luns have been attached in the relative target and
8529 	 * controller for parallel SCSI. This information is used when sd tries
8530 	 * to set the tagged queuing capability in HBA.
8531 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8532 	 * check if the device is parallel SCSI. However, we don't need to
8533 	 * check here because we've already checked during attach. No device
8534 	 * that is not parallel SCSI is in the chain.
8535 	 */
8536 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8537 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8538 	}
8539 
8540 	return (DDI_SUCCESS);
8541 
8542 err_notclosed:
8543 	mutex_exit(SD_MUTEX(un));
8544 
8545 err_stillbusy:
8546 	_NOTE(NO_COMPETING_THREADS_NOW);
8547 
8548 err_remove_event:
8549 	mutex_enter(&sd_detach_mutex);
8550 	un->un_detach_count--;
8551 	mutex_exit(&sd_detach_mutex);
8552 
8553 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
8554 	return (DDI_FAILURE);
8555 }
8556 
8557 
8558 /*
8559  *    Function: sd_create_errstats
8560  *
8561  * Description: This routine instantiates the device error stats.
8562  *
8563  *		Note: During attach the stats are instantiated first so they are
8564  *		available for attach-time routines that utilize the driver
8565  *		iopath to send commands to the device. The stats are initialized
8566  *		separately so data obtained during some attach-time routines is
8567  *		available. (4362483)
8568  *
8569  *   Arguments: un - driver soft state (unit) structure
8570  *		instance - driver instance
8571  *
8572  *     Context: Kernel thread context
8573  */
8574 
8575 static void
8576 sd_create_errstats(struct sd_lun *un, int instance)
8577 {
8578 	struct	sd_errstats	*stp;
8579 	char	kstatmodule_err[KSTAT_STRLEN];
8580 	char	kstatname[KSTAT_STRLEN];
8581 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
8582 
8583 	ASSERT(un != NULL);
8584 
8585 	if (un->un_errstats != NULL) {
8586 		return;
8587 	}
8588 
8589 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
8590 	    "%serr", sd_label);
8591 	(void) snprintf(kstatname, sizeof (kstatname),
8592 	    "%s%d,err", sd_label, instance);
8593 
8594 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8595 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8596 
8597 	if (un->un_errstats == NULL) {
8598 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8599 		    "sd_create_errstats: Failed kstat_create\n");
8600 		return;
8601 	}
8602 
8603 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8604 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
8605 	    KSTAT_DATA_UINT32);
8606 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
8607 	    KSTAT_DATA_UINT32);
8608 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
8609 	    KSTAT_DATA_UINT32);
8610 	kstat_named_init(&stp->sd_vid,		"Vendor",
8611 	    KSTAT_DATA_CHAR);
8612 	kstat_named_init(&stp->sd_pid,		"Product",
8613 	    KSTAT_DATA_CHAR);
8614 	kstat_named_init(&stp->sd_revision,	"Revision",
8615 	    KSTAT_DATA_CHAR);
8616 	kstat_named_init(&stp->sd_serial,	"Serial No",
8617 	    KSTAT_DATA_CHAR);
8618 	kstat_named_init(&stp->sd_capacity,	"Size",
8619 	    KSTAT_DATA_ULONGLONG);
8620 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
8621 	    KSTAT_DATA_UINT32);
8622 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
8623 	    KSTAT_DATA_UINT32);
8624 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
8625 	    KSTAT_DATA_UINT32);
8626 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
8627 	    KSTAT_DATA_UINT32);
8628 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
8629 	    KSTAT_DATA_UINT32);
8630 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
8631 	    KSTAT_DATA_UINT32);
8632 
8633 	un->un_errstats->ks_private = un;
8634 	un->un_errstats->ks_update  = nulldev;
8635 
8636 	kstat_install(un->un_errstats);
8637 }
8638 
8639 
8640 /*
8641  *    Function: sd_set_errstats
8642  *
8643  * Description: This routine sets the value of the vendor id, product id,
8644  *		revision, serial number, and capacity device error stats.
8645  *
8646  *		Note: During attach the stats are instantiated first so they are
8647  *		available for attach-time routines that utilize the driver
8648  *		iopath to send commands to the device. The stats are initialized
8649  *		separately so data obtained during some attach-time routines is
8650  *		available. (4362483)
8651  *
8652  *   Arguments: un - driver soft state (unit) structure
8653  *
8654  *     Context: Kernel thread context
8655  */
8656 
8657 static void
8658 sd_set_errstats(struct sd_lun *un)
8659 {
8660 	struct	sd_errstats	*stp;
8661 
8662 	ASSERT(un != NULL);
8663 	ASSERT(un->un_errstats != NULL);
8664 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8665 	ASSERT(stp != NULL);
8666 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
8667 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
8668 	(void) strncpy(stp->sd_revision.value.c,
8669 	    un->un_sd->sd_inq->inq_revision, 4);
8670 
8671 	/*
8672 	 * All the errstats are persistent across detach/attach,
8673 	 * so reset all the errstats here in case of the hot
8674 	 * replacement of disk drives, except for not changed
8675 	 * Sun qualified drives.
8676 	 */
8677 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
8678 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8679 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
8680 		stp->sd_softerrs.value.ui32 = 0;
8681 		stp->sd_harderrs.value.ui32 = 0;
8682 		stp->sd_transerrs.value.ui32 = 0;
8683 		stp->sd_rq_media_err.value.ui32 = 0;
8684 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
8685 		stp->sd_rq_nodev_err.value.ui32 = 0;
8686 		stp->sd_rq_recov_err.value.ui32 = 0;
8687 		stp->sd_rq_illrq_err.value.ui32 = 0;
8688 		stp->sd_rq_pfa_err.value.ui32 = 0;
8689 	}
8690 
8691 	/*
8692 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
8693 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
8694 	 * (4376302))
8695 	 */
8696 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
8697 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8698 		    sizeof (SD_INQUIRY(un)->inq_serial));
8699 	}
8700 
8701 	if (un->un_f_blockcount_is_valid != TRUE) {
8702 		/*
8703 		 * Set capacity error stat to 0 for no media. This ensures
8704 		 * a valid capacity is displayed in response to 'iostat -E'
8705 		 * when no media is present in the device.
8706 		 */
8707 		stp->sd_capacity.value.ui64 = 0;
8708 	} else {
8709 		/*
8710 		 * Multiply un_blockcount by un->un_sys_blocksize to get
8711 		 * capacity.
8712 		 *
8713 		 * Note: for non-512 blocksize devices "un_blockcount" has been
8714 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
8715 		 * (un_tgt_blocksize / un->un_sys_blocksize).
8716 		 */
8717 		stp->sd_capacity.value.ui64 = (uint64_t)
8718 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
8719 	}
8720 }
8721 
8722 
8723 /*
8724  *    Function: sd_set_pstats
8725  *
8726  * Description: This routine instantiates and initializes the partition
8727  *              stats for each partition with more than zero blocks.
8728  *		(4363169)
8729  *
8730  *   Arguments: un - driver soft state (unit) structure
8731  *
8732  *     Context: Kernel thread context
8733  */
8734 
8735 static void
8736 sd_set_pstats(struct sd_lun *un)
8737 {
8738 	char	kstatname[KSTAT_STRLEN];
8739 	int	instance;
8740 	int	i;
8741 	diskaddr_t	nblks = 0;
8742 	char	*partname = NULL;
8743 
8744 	ASSERT(un != NULL);
8745 
8746 	instance = ddi_get_instance(SD_DEVINFO(un));
8747 
8748 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
8749 	for (i = 0; i < NSDMAP; i++) {
8750 
8751 		if (cmlb_partinfo(un->un_cmlbhandle, i,
8752 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
8753 			continue;
8754 		mutex_enter(SD_MUTEX(un));
8755 
8756 		if ((un->un_pstats[i] == NULL) &&
8757 		    (nblks != 0)) {
8758 
8759 			(void) snprintf(kstatname, sizeof (kstatname),
8760 			    "%s%d,%s", sd_label, instance,
8761 			    partname);
8762 
8763 			un->un_pstats[i] = kstat_create(sd_label,
8764 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
8765 			    1, KSTAT_FLAG_PERSISTENT);
8766 			if (un->un_pstats[i] != NULL) {
8767 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
8768 				kstat_install(un->un_pstats[i]);
8769 			}
8770 		}
8771 		mutex_exit(SD_MUTEX(un));
8772 	}
8773 }
8774 
8775 
8776 #if (defined(__fibre))
8777 /*
8778  *    Function: sd_init_event_callbacks
8779  *
8780  * Description: This routine initializes the insertion and removal event
8781  *		callbacks. (fibre only)
8782  *
8783  *   Arguments: un - driver soft state (unit) structure
8784  *
8785  *     Context: Kernel thread context
8786  */
8787 
8788 static void
8789 sd_init_event_callbacks(struct sd_lun *un)
8790 {
8791 	ASSERT(un != NULL);
8792 
8793 	if ((un->un_insert_event == NULL) &&
8794 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
8795 	    &un->un_insert_event) == DDI_SUCCESS)) {
8796 		/*
8797 		 * Add the callback for an insertion event
8798 		 */
8799 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8800 		    un->un_insert_event, sd_event_callback, (void *)un,
8801 		    &(un->un_insert_cb_id));
8802 	}
8803 
8804 	if ((un->un_remove_event == NULL) &&
8805 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
8806 	    &un->un_remove_event) == DDI_SUCCESS)) {
8807 		/*
8808 		 * Add the callback for a removal event
8809 		 */
8810 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8811 		    un->un_remove_event, sd_event_callback, (void *)un,
8812 		    &(un->un_remove_cb_id));
8813 	}
8814 }
8815 
8816 
8817 /*
8818  *    Function: sd_event_callback
8819  *
8820  * Description: This routine handles insert/remove events (photon). The
8821  *		state is changed to OFFLINE which can be used to supress
8822  *		error msgs. (fibre only)
8823  *
8824  *   Arguments: un - driver soft state (unit) structure
8825  *
8826  *     Context: Callout thread context
8827  */
8828 /* ARGSUSED */
8829 static void
8830 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
8831     void *bus_impldata)
8832 {
8833 	struct sd_lun *un = (struct sd_lun *)arg;
8834 
8835 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
8836 	if (event == un->un_insert_event) {
8837 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
8838 		mutex_enter(SD_MUTEX(un));
8839 		if (un->un_state == SD_STATE_OFFLINE) {
8840 			if (un->un_last_state != SD_STATE_SUSPENDED) {
8841 				un->un_state = un->un_last_state;
8842 			} else {
8843 				/*
8844 				 * We have gone through SUSPEND/RESUME while
8845 				 * we were offline. Restore the last state
8846 				 */
8847 				un->un_state = un->un_save_state;
8848 			}
8849 		}
8850 		mutex_exit(SD_MUTEX(un));
8851 
8852 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
8853 	} else if (event == un->un_remove_event) {
8854 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
8855 		mutex_enter(SD_MUTEX(un));
8856 		/*
8857 		 * We need to handle an event callback that occurs during
8858 		 * the suspend operation, since we don't prevent it.
8859 		 */
8860 		if (un->un_state != SD_STATE_OFFLINE) {
8861 			if (un->un_state != SD_STATE_SUSPENDED) {
8862 				New_state(un, SD_STATE_OFFLINE);
8863 			} else {
8864 				un->un_last_state = SD_STATE_OFFLINE;
8865 			}
8866 		}
8867 		mutex_exit(SD_MUTEX(un));
8868 	} else {
8869 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
8870 		    "!Unknown event\n");
8871 	}
8872 
8873 }
8874 #endif
8875 
8876 /*
8877  *    Function: sd_cache_control()
8878  *
8879  * Description: This routine is the driver entry point for setting
8880  *		read and write caching by modifying the WCE (write cache
8881  *		enable) and RCD (read cache disable) bits of mode
8882  *		page 8 (MODEPAGE_CACHING).
8883  *
8884  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
8885  *                      structure for this target.
8886  *		rcd_flag - flag for controlling the read cache
8887  *		wce_flag - flag for controlling the write cache
8888  *
8889  * Return Code: EIO
8890  *		code returned by sd_send_scsi_MODE_SENSE and
8891  *		sd_send_scsi_MODE_SELECT
8892  *
8893  *     Context: Kernel Thread
8894  */
8895 
8896 static int
8897 sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag)
8898 {
8899 	struct mode_caching	*mode_caching_page;
8900 	uchar_t			*header;
8901 	size_t			buflen;
8902 	int			hdrlen;
8903 	int			bd_len;
8904 	int			rval = 0;
8905 	struct mode_header_grp2	*mhp;
8906 	struct sd_lun		*un;
8907 	int			status;
8908 
8909 	ASSERT(ssc != NULL);
8910 	un = ssc->ssc_un;
8911 	ASSERT(un != NULL);
8912 
8913 	/*
8914 	 * Do a test unit ready, otherwise a mode sense may not work if this
8915 	 * is the first command sent to the device after boot.
8916 	 */
8917 	status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
8918 	if (status != 0)
8919 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8920 
8921 	if (un->un_f_cfg_is_atapi == TRUE) {
8922 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8923 	} else {
8924 		hdrlen = MODE_HEADER_LENGTH;
8925 	}
8926 
8927 	/*
8928 	 * Allocate memory for the retrieved mode page and its headers.  Set
8929 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
8930 	 * we get all of the mode sense data otherwise, the mode select
8931 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
8932 	 */
8933 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
8934 	    sizeof (struct mode_cache_scsi3);
8935 
8936 	header = kmem_zalloc(buflen, KM_SLEEP);
8937 
8938 	/* Get the information from the device. */
8939 	if (un->un_f_cfg_is_atapi == TRUE) {
8940 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, header, buflen,
8941 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8942 	} else {
8943 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
8944 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8945 	}
8946 
8947 	if (rval != 0) {
8948 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8949 		    "sd_cache_control: Mode Sense Failed\n");
8950 		goto mode_sense_failed;
8951 	}
8952 
8953 	/*
8954 	 * Determine size of Block Descriptors in order to locate
8955 	 * the mode page data. ATAPI devices return 0, SCSI devices
8956 	 * should return MODE_BLK_DESC_LENGTH.
8957 	 */
8958 	if (un->un_f_cfg_is_atapi == TRUE) {
8959 		mhp	= (struct mode_header_grp2 *)header;
8960 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8961 	} else {
8962 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8963 	}
8964 
8965 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8966 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
8967 		    "sd_cache_control: Mode Sense returned invalid block "
8968 		    "descriptor length\n");
8969 		rval = EIO;
8970 		goto mode_sense_failed;
8971 	}
8972 
8973 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8974 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8975 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
8976 		    "sd_cache_control: Mode Sense caching page code mismatch "
8977 		    "%d\n", mode_caching_page->mode_page.code);
8978 		rval = EIO;
8979 		goto mode_sense_failed;
8980 	}
8981 
8982 	/* Check the relevant bits on successful mode sense. */
8983 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
8984 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
8985 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
8986 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
8987 
8988 		size_t sbuflen;
8989 		uchar_t save_pg;
8990 
8991 		/*
8992 		 * Construct select buffer length based on the
8993 		 * length of the sense data returned.
8994 		 */
8995 		sbuflen =  hdrlen + MODE_BLK_DESC_LENGTH +
8996 		    sizeof (struct mode_page) +
8997 		    (int)mode_caching_page->mode_page.length;
8998 
8999 		/*
9000 		 * Set the caching bits as requested.
9001 		 */
9002 		if (rcd_flag == SD_CACHE_ENABLE)
9003 			mode_caching_page->rcd = 0;
9004 		else if (rcd_flag == SD_CACHE_DISABLE)
9005 			mode_caching_page->rcd = 1;
9006 
9007 		if (wce_flag == SD_CACHE_ENABLE)
9008 			mode_caching_page->wce = 1;
9009 		else if (wce_flag == SD_CACHE_DISABLE)
9010 			mode_caching_page->wce = 0;
9011 
9012 		/*
9013 		 * Save the page if the mode sense says the
9014 		 * drive supports it.
9015 		 */
9016 		save_pg = mode_caching_page->mode_page.ps ?
9017 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
9018 
9019 		/* Clear reserved bits before mode select. */
9020 		mode_caching_page->mode_page.ps = 0;
9021 
9022 		/*
9023 		 * Clear out mode header for mode select.
9024 		 * The rest of the retrieved page will be reused.
9025 		 */
9026 		bzero(header, hdrlen);
9027 
9028 		if (un->un_f_cfg_is_atapi == TRUE) {
9029 			mhp = (struct mode_header_grp2 *)header;
9030 			mhp->bdesc_length_hi = bd_len >> 8;
9031 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
9032 		} else {
9033 			((struct mode_header *)header)->bdesc_length = bd_len;
9034 		}
9035 
9036 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9037 
9038 		/* Issue mode select to change the cache settings */
9039 		if (un->un_f_cfg_is_atapi == TRUE) {
9040 			rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, header,
9041 			    sbuflen, save_pg, SD_PATH_DIRECT);
9042 		} else {
9043 			rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
9044 			    sbuflen, save_pg, SD_PATH_DIRECT);
9045 		}
9046 
9047 	}
9048 
9049 
9050 mode_sense_failed:
9051 
9052 	kmem_free(header, buflen);
9053 
9054 	if (rval != 0) {
9055 		if (rval == EIO)
9056 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9057 		else
9058 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9059 	}
9060 	return (rval);
9061 }
9062 
9063 
9064 /*
9065  *    Function: sd_get_write_cache_enabled()
9066  *
9067  * Description: This routine is the driver entry point for determining if
9068  *		write caching is enabled.  It examines the WCE (write cache
9069  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
9070  *
9071  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
9072  *                      structure for this target.
9073  *		is_enabled - pointer to int where write cache enabled state
9074  *		is returned (non-zero -> write cache enabled)
9075  *
9076  *
9077  * Return Code: EIO
9078  *		code returned by sd_send_scsi_MODE_SENSE
9079  *
9080  *     Context: Kernel Thread
9081  *
9082  * NOTE: If ioctl is added to disable write cache, this sequence should
9083  * be followed so that no locking is required for accesses to
9084  * un->un_f_write_cache_enabled:
9085  * 	do mode select to clear wce
9086  * 	do synchronize cache to flush cache
9087  * 	set un->un_f_write_cache_enabled = FALSE
9088  *
9089  * Conversely, an ioctl to enable the write cache should be done
9090  * in this order:
9091  * 	set un->un_f_write_cache_enabled = TRUE
9092  * 	do mode select to set wce
9093  */
9094 
9095 static int
9096 sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled)
9097 {
9098 	struct mode_caching	*mode_caching_page;
9099 	uchar_t			*header;
9100 	size_t			buflen;
9101 	int			hdrlen;
9102 	int			bd_len;
9103 	int			rval = 0;
9104 	struct sd_lun		*un;
9105 	int			status;
9106 
9107 	ASSERT(ssc != NULL);
9108 	un = ssc->ssc_un;
9109 	ASSERT(un != NULL);
9110 	ASSERT(is_enabled != NULL);
9111 
9112 	/* in case of error, flag as enabled */
9113 	*is_enabled = TRUE;
9114 
9115 	/*
9116 	 * Do a test unit ready, otherwise a mode sense may not work if this
9117 	 * is the first command sent to the device after boot.
9118 	 */
9119 	status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
9120 
9121 	if (status != 0)
9122 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9123 
9124 	if (un->un_f_cfg_is_atapi == TRUE) {
9125 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9126 	} else {
9127 		hdrlen = MODE_HEADER_LENGTH;
9128 	}
9129 
9130 	/*
9131 	 * Allocate memory for the retrieved mode page and its headers.  Set
9132 	 * a pointer to the page itself.
9133 	 */
9134 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
9135 	header = kmem_zalloc(buflen, KM_SLEEP);
9136 
9137 	/* Get the information from the device. */
9138 	if (un->un_f_cfg_is_atapi == TRUE) {
9139 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, header, buflen,
9140 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9141 	} else {
9142 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
9143 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9144 	}
9145 
9146 	if (rval != 0) {
9147 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9148 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
9149 		goto mode_sense_failed;
9150 	}
9151 
9152 	/*
9153 	 * Determine size of Block Descriptors in order to locate
9154 	 * the mode page data. ATAPI devices return 0, SCSI devices
9155 	 * should return MODE_BLK_DESC_LENGTH.
9156 	 */
9157 	if (un->un_f_cfg_is_atapi == TRUE) {
9158 		struct mode_header_grp2	*mhp;
9159 		mhp	= (struct mode_header_grp2 *)header;
9160 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9161 	} else {
9162 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9163 	}
9164 
9165 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9166 		/* FMA should make upset complain here */
9167 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9168 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
9169 		    "block descriptor length\n");
9170 		rval = EIO;
9171 		goto mode_sense_failed;
9172 	}
9173 
9174 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9175 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9176 		/* FMA could make upset complain here */
9177 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9178 		    "sd_get_write_cache_enabled: Mode Sense caching page "
9179 		    "code mismatch %d\n", mode_caching_page->mode_page.code);
9180 		rval = EIO;
9181 		goto mode_sense_failed;
9182 	}
9183 	*is_enabled = mode_caching_page->wce;
9184 
9185 mode_sense_failed:
9186 	if (rval == 0) {
9187 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9188 	} else if (rval == EIO) {
9189 		/*
9190 		 * Some disks do not support mode sense(6), we
9191 		 * should ignore this kind of error(sense key is
9192 		 * 0x5 - illegal request).
9193 		 */
9194 		uint8_t *sensep;
9195 		int senlen;
9196 
9197 		sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
9198 		senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
9199 		    ssc->ssc_uscsi_cmd->uscsi_rqresid);
9200 
9201 		if (senlen > 0 &&
9202 		    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
9203 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
9204 		} else {
9205 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9206 		}
9207 	} else {
9208 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9209 	}
9210 	kmem_free(header, buflen);
9211 	return (rval);
9212 }
9213 
9214 /*
9215  *    Function: sd_get_nv_sup()
9216  *
9217  * Description: This routine is the driver entry point for
9218  * determining whether non-volatile cache is supported. This
9219  * determination process works as follows:
9220  *
9221  * 1. sd first queries sd.conf on whether
9222  * suppress_cache_flush bit is set for this device.
9223  *
9224  * 2. if not there, then queries the internal disk table.
9225  *
9226  * 3. if either sd.conf or internal disk table specifies
9227  * cache flush be suppressed, we don't bother checking
9228  * NV_SUP bit.
9229  *
9230  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
9231  * the optional INQUIRY VPD page 0x86. If the device
9232  * supports VPD page 0x86, sd examines the NV_SUP
9233  * (non-volatile cache support) bit in the INQUIRY VPD page
9234  * 0x86:
9235  *   o If NV_SUP bit is set, sd assumes the device has a
9236  *   non-volatile cache and set the
9237  *   un_f_sync_nv_supported to TRUE.
9238  *   o Otherwise cache is not non-volatile,
9239  *   un_f_sync_nv_supported is set to FALSE.
9240  *
9241  * Arguments: un - driver soft state (unit) structure
9242  *
9243  * Return Code:
9244  *
9245  *     Context: Kernel Thread
9246  */
9247 
9248 static void
9249 sd_get_nv_sup(sd_ssc_t *ssc)
9250 {
9251 	int		rval		= 0;
9252 	uchar_t		*inq86		= NULL;
9253 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
9254 	size_t		inq86_resid	= 0;
9255 	struct		dk_callback *dkc;
9256 	struct sd_lun	*un;
9257 
9258 	ASSERT(ssc != NULL);
9259 	un = ssc->ssc_un;
9260 	ASSERT(un != NULL);
9261 
9262 	mutex_enter(SD_MUTEX(un));
9263 
9264 	/*
9265 	 * Be conservative on the device's support of
9266 	 * SYNC_NV bit: un_f_sync_nv_supported is
9267 	 * initialized to be false.
9268 	 */
9269 	un->un_f_sync_nv_supported = FALSE;
9270 
9271 	/*
9272 	 * If either sd.conf or internal disk table
9273 	 * specifies cache flush be suppressed, then
9274 	 * we don't bother checking NV_SUP bit.
9275 	 */
9276 	if (un->un_f_suppress_cache_flush == TRUE) {
9277 		mutex_exit(SD_MUTEX(un));
9278 		return;
9279 	}
9280 
9281 	if (sd_check_vpd_page_support(ssc) == 0 &&
9282 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
9283 		mutex_exit(SD_MUTEX(un));
9284 		/* collect page 86 data if available */
9285 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
9286 
9287 		rval = sd_send_scsi_INQUIRY(ssc, inq86, inq86_len,
9288 		    0x01, 0x86, &inq86_resid);
9289 
9290 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
9291 			SD_TRACE(SD_LOG_COMMON, un,
9292 			    "sd_get_nv_sup: \
9293 			    successfully get VPD page: %x \
9294 			    PAGE LENGTH: %x BYTE 6: %x\n",
9295 			    inq86[1], inq86[3], inq86[6]);
9296 
9297 			mutex_enter(SD_MUTEX(un));
9298 			/*
9299 			 * check the value of NV_SUP bit: only if the device
9300 			 * reports NV_SUP bit to be 1, the
9301 			 * un_f_sync_nv_supported bit will be set to true.
9302 			 */
9303 			if (inq86[6] & SD_VPD_NV_SUP) {
9304 				un->un_f_sync_nv_supported = TRUE;
9305 			}
9306 			mutex_exit(SD_MUTEX(un));
9307 		} else if (rval != 0) {
9308 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9309 		}
9310 
9311 		kmem_free(inq86, inq86_len);
9312 	} else {
9313 		mutex_exit(SD_MUTEX(un));
9314 	}
9315 
9316 	/*
9317 	 * Send a SYNC CACHE command to check whether
9318 	 * SYNC_NV bit is supported. This command should have
9319 	 * un_f_sync_nv_supported set to correct value.
9320 	 */
9321 	mutex_enter(SD_MUTEX(un));
9322 	if (un->un_f_sync_nv_supported) {
9323 		mutex_exit(SD_MUTEX(un));
9324 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
9325 		dkc->dkc_flag = FLUSH_VOLATILE;
9326 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
9327 
9328 		/*
9329 		 * Send a TEST UNIT READY command to the device. This should
9330 		 * clear any outstanding UNIT ATTENTION that may be present.
9331 		 */
9332 		rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
9333 		if (rval != 0)
9334 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9335 
9336 		kmem_free(dkc, sizeof (struct dk_callback));
9337 	} else {
9338 		mutex_exit(SD_MUTEX(un));
9339 	}
9340 
9341 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
9342 	    un_f_suppress_cache_flush is set to %d\n",
9343 	    un->un_f_suppress_cache_flush);
9344 }
9345 
9346 /*
9347  *    Function: sd_make_device
9348  *
9349  * Description: Utility routine to return the Solaris device number from
9350  *		the data in the device's dev_info structure.
9351  *
9352  * Return Code: The Solaris device number
9353  *
9354  *     Context: Any
9355  */
9356 
9357 static dev_t
9358 sd_make_device(dev_info_t *devi)
9359 {
9360 	return (makedevice(ddi_name_to_major(ddi_get_name(devi)),
9361 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9362 }
9363 
9364 
9365 /*
9366  *    Function: sd_pm_entry
9367  *
9368  * Description: Called at the start of a new command to manage power
9369  *		and busy status of a device. This includes determining whether
9370  *		the current power state of the device is sufficient for
9371  *		performing the command or whether it must be changed.
9372  *		The PM framework is notified appropriately.
9373  *		Only with a return status of DDI_SUCCESS will the
9374  *		component be busy to the framework.
9375  *
9376  *		All callers of sd_pm_entry must check the return status
9377  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9378  *		of DDI_FAILURE indicates the device failed to power up.
9379  *		In this case un_pm_count has been adjusted so the result
9380  *		on exit is still powered down, ie. count is less than 0.
9381  *		Calling sd_pm_exit with this count value hits an ASSERT.
9382  *
9383  * Return Code: DDI_SUCCESS or DDI_FAILURE
9384  *
9385  *     Context: Kernel thread context.
9386  */
9387 
9388 static int
9389 sd_pm_entry(struct sd_lun *un)
9390 {
9391 	int return_status = DDI_SUCCESS;
9392 
9393 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9394 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9395 
9396 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9397 
9398 	if (un->un_f_pm_is_enabled == FALSE) {
9399 		SD_TRACE(SD_LOG_IO_PM, un,
9400 		    "sd_pm_entry: exiting, PM not enabled\n");
9401 		return (return_status);
9402 	}
9403 
9404 	/*
9405 	 * Just increment a counter if PM is enabled. On the transition from
9406 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9407 	 * the count with each IO and mark the device as idle when the count
9408 	 * hits 0.
9409 	 *
9410 	 * If the count is less than 0 the device is powered down. If a powered
9411 	 * down device is successfully powered up then the count must be
9412 	 * incremented to reflect the power up. Note that it'll get incremented
9413 	 * a second time to become busy.
9414 	 *
9415 	 * Because the following has the potential to change the device state
9416 	 * and must release the un_pm_mutex to do so, only one thread can be
9417 	 * allowed through at a time.
9418 	 */
9419 
9420 	mutex_enter(&un->un_pm_mutex);
9421 	while (un->un_pm_busy == TRUE) {
9422 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9423 	}
9424 	un->un_pm_busy = TRUE;
9425 
9426 	if (un->un_pm_count < 1) {
9427 
9428 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9429 
9430 		/*
9431 		 * Indicate we are now busy so the framework won't attempt to
9432 		 * power down the device. This call will only fail if either
9433 		 * we passed a bad component number or the device has no
9434 		 * components. Neither of these should ever happen.
9435 		 */
9436 		mutex_exit(&un->un_pm_mutex);
9437 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9438 		ASSERT(return_status == DDI_SUCCESS);
9439 
9440 		mutex_enter(&un->un_pm_mutex);
9441 
9442 		if (un->un_pm_count < 0) {
9443 			mutex_exit(&un->un_pm_mutex);
9444 
9445 			SD_TRACE(SD_LOG_IO_PM, un,
9446 			    "sd_pm_entry: power up component\n");
9447 
9448 			/*
9449 			 * pm_raise_power will cause sdpower to be called
9450 			 * which brings the device power level to the
9451 			 * desired state, ON in this case. If successful,
9452 			 * un_pm_count and un_power_level will be updated
9453 			 * appropriately.
9454 			 */
9455 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9456 			    SD_SPINDLE_ON);
9457 
9458 			mutex_enter(&un->un_pm_mutex);
9459 
9460 			if (return_status != DDI_SUCCESS) {
9461 				/*
9462 				 * Power up failed.
9463 				 * Idle the device and adjust the count
9464 				 * so the result on exit is that we're
9465 				 * still powered down, ie. count is less than 0.
9466 				 */
9467 				SD_TRACE(SD_LOG_IO_PM, un,
9468 				    "sd_pm_entry: power up failed,"
9469 				    " idle the component\n");
9470 
9471 				(void) pm_idle_component(SD_DEVINFO(un), 0);
9472 				un->un_pm_count--;
9473 			} else {
9474 				/*
9475 				 * Device is powered up, verify the
9476 				 * count is non-negative.
9477 				 * This is debug only.
9478 				 */
9479 				ASSERT(un->un_pm_count == 0);
9480 			}
9481 		}
9482 
9483 		if (return_status == DDI_SUCCESS) {
9484 			/*
9485 			 * For performance, now that the device has been tagged
9486 			 * as busy, and it's known to be powered up, update the
9487 			 * chain types to use jump tables that do not include
9488 			 * pm. This significantly lowers the overhead and
9489 			 * therefore improves performance.
9490 			 */
9491 
9492 			mutex_exit(&un->un_pm_mutex);
9493 			mutex_enter(SD_MUTEX(un));
9494 			SD_TRACE(SD_LOG_IO_PM, un,
9495 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
9496 			    un->un_uscsi_chain_type);
9497 
9498 			if (un->un_f_non_devbsize_supported) {
9499 				un->un_buf_chain_type =
9500 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
9501 			} else {
9502 				un->un_buf_chain_type =
9503 				    SD_CHAIN_INFO_DISK_NO_PM;
9504 			}
9505 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
9506 
9507 			SD_TRACE(SD_LOG_IO_PM, un,
9508 			    "             changed  uscsi_chain_type to   %d\n",
9509 			    un->un_uscsi_chain_type);
9510 			mutex_exit(SD_MUTEX(un));
9511 			mutex_enter(&un->un_pm_mutex);
9512 
9513 			if (un->un_pm_idle_timeid == NULL) {
9514 				/* 300 ms. */
9515 				un->un_pm_idle_timeid =
9516 				    timeout(sd_pm_idletimeout_handler, un,
9517 				    (drv_usectohz((clock_t)300000)));
9518 				/*
9519 				 * Include an extra call to busy which keeps the
9520 				 * device busy with-respect-to the PM layer
9521 				 * until the timer fires, at which time it'll
9522 				 * get the extra idle call.
9523 				 */
9524 				(void) pm_busy_component(SD_DEVINFO(un), 0);
9525 			}
9526 		}
9527 	}
9528 	un->un_pm_busy = FALSE;
9529 	/* Next... */
9530 	cv_signal(&un->un_pm_busy_cv);
9531 
9532 	un->un_pm_count++;
9533 
9534 	SD_TRACE(SD_LOG_IO_PM, un,
9535 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
9536 
9537 	mutex_exit(&un->un_pm_mutex);
9538 
9539 	return (return_status);
9540 }
9541 
9542 
9543 /*
9544  *    Function: sd_pm_exit
9545  *
9546  * Description: Called at the completion of a command to manage busy
9547  *		status for the device. If the device becomes idle the
9548  *		PM framework is notified.
9549  *
9550  *     Context: Kernel thread context
9551  */
9552 
9553 static void
9554 sd_pm_exit(struct sd_lun *un)
9555 {
9556 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9557 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9558 
9559 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
9560 
9561 	/*
9562 	 * After attach the following flag is only read, so don't
9563 	 * take the penalty of acquiring a mutex for it.
9564 	 */
9565 	if (un->un_f_pm_is_enabled == TRUE) {
9566 
9567 		mutex_enter(&un->un_pm_mutex);
9568 		un->un_pm_count--;
9569 
9570 		SD_TRACE(SD_LOG_IO_PM, un,
9571 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
9572 
9573 		ASSERT(un->un_pm_count >= 0);
9574 		if (un->un_pm_count == 0) {
9575 			mutex_exit(&un->un_pm_mutex);
9576 
9577 			SD_TRACE(SD_LOG_IO_PM, un,
9578 			    "sd_pm_exit: idle component\n");
9579 
9580 			(void) pm_idle_component(SD_DEVINFO(un), 0);
9581 
9582 		} else {
9583 			mutex_exit(&un->un_pm_mutex);
9584 		}
9585 	}
9586 
9587 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
9588 }
9589 
9590 
9591 /*
9592  *    Function: sdopen
9593  *
9594  * Description: Driver's open(9e) entry point function.
9595  *
9596  *   Arguments: dev_i   - pointer to device number
9597  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
9598  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9599  *		cred_p  - user credential pointer
9600  *
9601  * Return Code: EINVAL
9602  *		ENXIO
9603  *		EIO
9604  *		EROFS
9605  *		EBUSY
9606  *
9607  *     Context: Kernel thread context
9608  */
9609 /* ARGSUSED */
9610 static int
9611 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
9612 {
9613 	struct sd_lun	*un;
9614 	int		nodelay;
9615 	int		part;
9616 	uint64_t	partmask;
9617 	int		instance;
9618 	dev_t		dev;
9619 	int		rval = EIO;
9620 	diskaddr_t	nblks = 0;
9621 	diskaddr_t	label_cap;
9622 
9623 	/* Validate the open type */
9624 	if (otyp >= OTYPCNT) {
9625 		return (EINVAL);
9626 	}
9627 
9628 	dev = *dev_p;
9629 	instance = SDUNIT(dev);
9630 	mutex_enter(&sd_detach_mutex);
9631 
9632 	/*
9633 	 * Fail the open if there is no softstate for the instance, or
9634 	 * if another thread somewhere is trying to detach the instance.
9635 	 */
9636 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
9637 	    (un->un_detach_count != 0)) {
9638 		mutex_exit(&sd_detach_mutex);
9639 		/*
9640 		 * The probe cache only needs to be cleared when open (9e) fails
9641 		 * with ENXIO (4238046).
9642 		 */
9643 		/*
9644 		 * un-conditionally clearing probe cache is ok with
9645 		 * separate sd/ssd binaries
9646 		 * x86 platform can be an issue with both parallel
9647 		 * and fibre in 1 binary
9648 		 */
9649 		sd_scsi_clear_probe_cache();
9650 		return (ENXIO);
9651 	}
9652 
9653 	/*
9654 	 * The un_layer_count is to prevent another thread in specfs from
9655 	 * trying to detach the instance, which can happen when we are
9656 	 * called from a higher-layer driver instead of thru specfs.
9657 	 * This will not be needed when DDI provides a layered driver
9658 	 * interface that allows specfs to know that an instance is in
9659 	 * use by a layered driver & should not be detached.
9660 	 *
9661 	 * Note: the semantics for layered driver opens are exactly one
9662 	 * close for every open.
9663 	 */
9664 	if (otyp == OTYP_LYR) {
9665 		un->un_layer_count++;
9666 	}
9667 
9668 	/*
9669 	 * Keep a count of the current # of opens in progress. This is because
9670 	 * some layered drivers try to call us as a regular open. This can
9671 	 * cause problems that we cannot prevent, however by keeping this count
9672 	 * we can at least keep our open and detach routines from racing against
9673 	 * each other under such conditions.
9674 	 */
9675 	un->un_opens_in_progress++;
9676 	mutex_exit(&sd_detach_mutex);
9677 
9678 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
9679 	part	 = SDPART(dev);
9680 	partmask = 1 << part;
9681 
9682 	/*
9683 	 * We use a semaphore here in order to serialize
9684 	 * open and close requests on the device.
9685 	 */
9686 	sema_p(&un->un_semoclose);
9687 
9688 	mutex_enter(SD_MUTEX(un));
9689 
9690 	/*
9691 	 * All device accesses go thru sdstrategy() where we check
9692 	 * on suspend status but there could be a scsi_poll command,
9693 	 * which bypasses sdstrategy(), so we need to check pm
9694 	 * status.
9695 	 */
9696 
9697 	if (!nodelay) {
9698 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9699 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9700 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9701 		}
9702 
9703 		mutex_exit(SD_MUTEX(un));
9704 		if (sd_pm_entry(un) != DDI_SUCCESS) {
9705 			rval = EIO;
9706 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
9707 			    "sdopen: sd_pm_entry failed\n");
9708 			goto open_failed_with_pm;
9709 		}
9710 		mutex_enter(SD_MUTEX(un));
9711 	}
9712 
9713 	/* check for previous exclusive open */
9714 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
9715 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9716 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
9717 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
9718 
9719 	if (un->un_exclopen & (partmask)) {
9720 		goto excl_open_fail;
9721 	}
9722 
9723 	if (flag & FEXCL) {
9724 		int i;
9725 		if (un->un_ocmap.lyropen[part]) {
9726 			goto excl_open_fail;
9727 		}
9728 		for (i = 0; i < (OTYPCNT - 1); i++) {
9729 			if (un->un_ocmap.regopen[i] & (partmask)) {
9730 				goto excl_open_fail;
9731 			}
9732 		}
9733 	}
9734 
9735 	/*
9736 	 * Check the write permission if this is a removable media device,
9737 	 * NDELAY has not been set, and writable permission is requested.
9738 	 *
9739 	 * Note: If NDELAY was set and this is write-protected media the WRITE
9740 	 * attempt will fail with EIO as part of the I/O processing. This is a
9741 	 * more permissive implementation that allows the open to succeed and
9742 	 * WRITE attempts to fail when appropriate.
9743 	 */
9744 	if (un->un_f_chk_wp_open) {
9745 		if ((flag & FWRITE) && (!nodelay)) {
9746 			mutex_exit(SD_MUTEX(un));
9747 			/*
9748 			 * Defer the check for write permission on writable
9749 			 * DVD drive till sdstrategy and will not fail open even
9750 			 * if FWRITE is set as the device can be writable
9751 			 * depending upon the media and the media can change
9752 			 * after the call to open().
9753 			 */
9754 			if (un->un_f_dvdram_writable_device == FALSE) {
9755 				if (ISCD(un) || sr_check_wp(dev)) {
9756 				rval = EROFS;
9757 				mutex_enter(SD_MUTEX(un));
9758 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9759 				    "write to cd or write protected media\n");
9760 				goto open_fail;
9761 				}
9762 			}
9763 			mutex_enter(SD_MUTEX(un));
9764 		}
9765 	}
9766 
9767 	/*
9768 	 * If opening in NDELAY/NONBLOCK mode, just return.
9769 	 * Check if disk is ready and has a valid geometry later.
9770 	 */
9771 	if (!nodelay) {
9772 		sd_ssc_t	*ssc;
9773 
9774 		mutex_exit(SD_MUTEX(un));
9775 		ssc = sd_ssc_init(un);
9776 		rval = sd_ready_and_valid(ssc, part);
9777 		sd_ssc_fini(ssc);
9778 		mutex_enter(SD_MUTEX(un));
9779 		/*
9780 		 * Fail if device is not ready or if the number of disk
9781 		 * blocks is zero or negative for non CD devices.
9782 		 */
9783 
9784 		nblks = 0;
9785 
9786 		if (rval == SD_READY_VALID && (!ISCD(un))) {
9787 			/* if cmlb_partinfo fails, nblks remains 0 */
9788 			mutex_exit(SD_MUTEX(un));
9789 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
9790 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
9791 			mutex_enter(SD_MUTEX(un));
9792 		}
9793 
9794 		if ((rval != SD_READY_VALID) ||
9795 		    (!ISCD(un) && nblks <= 0)) {
9796 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
9797 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9798 			    "device not ready or invalid disk block value\n");
9799 			goto open_fail;
9800 		}
9801 #if defined(__i386) || defined(__amd64)
9802 	} else {
9803 		uchar_t *cp;
9804 		/*
9805 		 * x86 requires special nodelay handling, so that p0 is
9806 		 * always defined and accessible.
9807 		 * Invalidate geometry only if device is not already open.
9808 		 */
9809 		cp = &un->un_ocmap.chkd[0];
9810 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9811 			if (*cp != (uchar_t)0) {
9812 				break;
9813 			}
9814 			cp++;
9815 		}
9816 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9817 			mutex_exit(SD_MUTEX(un));
9818 			cmlb_invalidate(un->un_cmlbhandle,
9819 			    (void *)SD_PATH_DIRECT);
9820 			mutex_enter(SD_MUTEX(un));
9821 		}
9822 
9823 #endif
9824 	}
9825 
9826 	if (otyp == OTYP_LYR) {
9827 		un->un_ocmap.lyropen[part]++;
9828 	} else {
9829 		un->un_ocmap.regopen[otyp] |= partmask;
9830 	}
9831 
9832 	/* Set up open and exclusive open flags */
9833 	if (flag & FEXCL) {
9834 		un->un_exclopen |= (partmask);
9835 	}
9836 
9837 	/*
9838 	 * If the lun is EFI labeled and lun capacity is greater than the
9839 	 * capacity contained in the label, log a sys-event to notify the
9840 	 * interested module.
9841 	 * To avoid an infinite loop of logging sys-event, we only log the
9842 	 * event when the lun is not opened in NDELAY mode. The event handler
9843 	 * should open the lun in NDELAY mode.
9844 	 */
9845 	if (!(flag & FNDELAY)) {
9846 		mutex_exit(SD_MUTEX(un));
9847 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
9848 		    (void*)SD_PATH_DIRECT) == 0) {
9849 			mutex_enter(SD_MUTEX(un));
9850 			if (un->un_f_blockcount_is_valid &&
9851 			    un->un_blockcount > label_cap) {
9852 				mutex_exit(SD_MUTEX(un));
9853 				sd_log_lun_expansion_event(un,
9854 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
9855 				mutex_enter(SD_MUTEX(un));
9856 			}
9857 		} else {
9858 			mutex_enter(SD_MUTEX(un));
9859 		}
9860 	}
9861 
9862 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9863 	    "open of part %d type %d\n", part, otyp);
9864 
9865 	mutex_exit(SD_MUTEX(un));
9866 	if (!nodelay) {
9867 		sd_pm_exit(un);
9868 	}
9869 
9870 	sema_v(&un->un_semoclose);
9871 
9872 	mutex_enter(&sd_detach_mutex);
9873 	un->un_opens_in_progress--;
9874 	mutex_exit(&sd_detach_mutex);
9875 
9876 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
9877 	return (DDI_SUCCESS);
9878 
9879 excl_open_fail:
9880 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
9881 	rval = EBUSY;
9882 
9883 open_fail:
9884 	mutex_exit(SD_MUTEX(un));
9885 
9886 	/*
9887 	 * On a failed open we must exit the pm management.
9888 	 */
9889 	if (!nodelay) {
9890 		sd_pm_exit(un);
9891 	}
9892 open_failed_with_pm:
9893 	sema_v(&un->un_semoclose);
9894 
9895 	mutex_enter(&sd_detach_mutex);
9896 	un->un_opens_in_progress--;
9897 	if (otyp == OTYP_LYR) {
9898 		un->un_layer_count--;
9899 	}
9900 	mutex_exit(&sd_detach_mutex);
9901 
9902 	return (rval);
9903 }
9904 
9905 
9906 /*
9907  *    Function: sdclose
9908  *
9909  * Description: Driver's close(9e) entry point function.
9910  *
9911  *   Arguments: dev    - device number
9912  *		flag   - file status flag, informational only
9913  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9914  *		cred_p - user credential pointer
9915  *
9916  * Return Code: ENXIO
9917  *
9918  *     Context: Kernel thread context
9919  */
9920 /* ARGSUSED */
9921 static int
9922 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
9923 {
9924 	struct sd_lun	*un;
9925 	uchar_t		*cp;
9926 	int		part;
9927 	int		nodelay;
9928 	int		rval = 0;
9929 
9930 	/* Validate the open type */
9931 	if (otyp >= OTYPCNT) {
9932 		return (ENXIO);
9933 	}
9934 
9935 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9936 		return (ENXIO);
9937 	}
9938 
9939 	part = SDPART(dev);
9940 	nodelay = flag & (FNDELAY | FNONBLOCK);
9941 
9942 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9943 	    "sdclose: close of part %d type %d\n", part, otyp);
9944 
9945 	/*
9946 	 * We use a semaphore here in order to serialize
9947 	 * open and close requests on the device.
9948 	 */
9949 	sema_p(&un->un_semoclose);
9950 
9951 	mutex_enter(SD_MUTEX(un));
9952 
9953 	/* Don't proceed if power is being changed. */
9954 	while (un->un_state == SD_STATE_PM_CHANGING) {
9955 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9956 	}
9957 
9958 	if (un->un_exclopen & (1 << part)) {
9959 		un->un_exclopen &= ~(1 << part);
9960 	}
9961 
9962 	/* Update the open partition map */
9963 	if (otyp == OTYP_LYR) {
9964 		un->un_ocmap.lyropen[part] -= 1;
9965 	} else {
9966 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
9967 	}
9968 
9969 	cp = &un->un_ocmap.chkd[0];
9970 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9971 		if (*cp != NULL) {
9972 			break;
9973 		}
9974 		cp++;
9975 	}
9976 
9977 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9978 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
9979 
9980 		/*
9981 		 * We avoid persistance upon the last close, and set
9982 		 * the throttle back to the maximum.
9983 		 */
9984 		un->un_throttle = un->un_saved_throttle;
9985 
9986 		if (un->un_state == SD_STATE_OFFLINE) {
9987 			if (un->un_f_is_fibre == FALSE) {
9988 				scsi_log(SD_DEVINFO(un), sd_label,
9989 				    CE_WARN, "offline\n");
9990 			}
9991 			mutex_exit(SD_MUTEX(un));
9992 			cmlb_invalidate(un->un_cmlbhandle,
9993 			    (void *)SD_PATH_DIRECT);
9994 			mutex_enter(SD_MUTEX(un));
9995 
9996 		} else {
9997 			/*
9998 			 * Flush any outstanding writes in NVRAM cache.
9999 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10000 			 * cmd, it may not work for non-Pluto devices.
10001 			 * SYNCHRONIZE CACHE is not required for removables,
10002 			 * except DVD-RAM drives.
10003 			 *
10004 			 * Also note: because SYNCHRONIZE CACHE is currently
10005 			 * the only command issued here that requires the
10006 			 * drive be powered up, only do the power up before
10007 			 * sending the Sync Cache command. If additional
10008 			 * commands are added which require a powered up
10009 			 * drive, the following sequence may have to change.
10010 			 *
10011 			 * And finally, note that parallel SCSI on SPARC
10012 			 * only issues a Sync Cache to DVD-RAM, a newly
10013 			 * supported device.
10014 			 */
10015 #if defined(__i386) || defined(__amd64)
10016 			if ((un->un_f_sync_cache_supported &&
10017 			    un->un_f_sync_cache_required) ||
10018 			    un->un_f_dvdram_writable_device == TRUE) {
10019 #else
10020 			if (un->un_f_dvdram_writable_device == TRUE) {
10021 #endif
10022 				mutex_exit(SD_MUTEX(un));
10023 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10024 					rval =
10025 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10026 					    NULL);
10027 					/* ignore error if not supported */
10028 					if (rval == ENOTSUP) {
10029 						rval = 0;
10030 					} else if (rval != 0) {
10031 						rval = EIO;
10032 					}
10033 					sd_pm_exit(un);
10034 				} else {
10035 					rval = EIO;
10036 				}
10037 				mutex_enter(SD_MUTEX(un));
10038 			}
10039 
10040 			/*
10041 			 * For devices which supports DOOR_LOCK, send an ALLOW
10042 			 * MEDIA REMOVAL command, but don't get upset if it
10043 			 * fails. We need to raise the power of the drive before
10044 			 * we can call sd_send_scsi_DOORLOCK()
10045 			 */
10046 			if (un->un_f_doorlock_supported) {
10047 				mutex_exit(SD_MUTEX(un));
10048 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10049 					sd_ssc_t	*ssc;
10050 
10051 					ssc = sd_ssc_init(un);
10052 					rval = sd_send_scsi_DOORLOCK(ssc,
10053 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10054 					if (rval != 0)
10055 						sd_ssc_assessment(ssc,
10056 						    SD_FMT_IGNORE);
10057 					sd_ssc_fini(ssc);
10058 
10059 					sd_pm_exit(un);
10060 					if (ISCD(un) && (rval != 0) &&
10061 					    (nodelay != 0)) {
10062 						rval = ENXIO;
10063 					}
10064 				} else {
10065 					rval = EIO;
10066 				}
10067 				mutex_enter(SD_MUTEX(un));
10068 			}
10069 
10070 			/*
10071 			 * If a device has removable media, invalidate all
10072 			 * parameters related to media, such as geometry,
10073 			 * blocksize, and blockcount.
10074 			 */
10075 			if (un->un_f_has_removable_media) {
10076 				sr_ejected(un);
10077 			}
10078 
10079 			/*
10080 			 * Destroy the cache (if it exists) which was
10081 			 * allocated for the write maps since this is
10082 			 * the last close for this media.
10083 			 */
10084 			if (un->un_wm_cache) {
10085 				/*
10086 				 * Check if there are pending commands.
10087 				 * and if there are give a warning and
10088 				 * do not destroy the cache.
10089 				 */
10090 				if (un->un_ncmds_in_driver > 0) {
10091 					scsi_log(SD_DEVINFO(un),
10092 					    sd_label, CE_WARN,
10093 					    "Unable to clean up memory "
10094 					    "because of pending I/O\n");
10095 				} else {
10096 					kmem_cache_destroy(
10097 					    un->un_wm_cache);
10098 					un->un_wm_cache = NULL;
10099 				}
10100 			}
10101 		}
10102 	}
10103 
10104 	mutex_exit(SD_MUTEX(un));
10105 	sema_v(&un->un_semoclose);
10106 
10107 	if (otyp == OTYP_LYR) {
10108 		mutex_enter(&sd_detach_mutex);
10109 		/*
10110 		 * The detach routine may run when the layer count
10111 		 * drops to zero.
10112 		 */
10113 		un->un_layer_count--;
10114 		mutex_exit(&sd_detach_mutex);
10115 	}
10116 
10117 	return (rval);
10118 }
10119 
10120 
10121 /*
10122  *    Function: sd_ready_and_valid
10123  *
10124  * Description: Test if device is ready and has a valid geometry.
10125  *
10126  *   Arguments: ssc - sd_ssc_t will contain un
10127  *		un  - driver soft state (unit) structure
10128  *
10129  * Return Code: SD_READY_VALID		ready and valid label
10130  *		SD_NOT_READY_VALID	not ready, no label
10131  *		SD_RESERVED_BY_OTHERS	reservation conflict
10132  *
10133  *     Context: Never called at interrupt context.
10134  */
10135 
10136 static int
10137 sd_ready_and_valid(sd_ssc_t *ssc, int part)
10138 {
10139 	struct sd_errstats	*stp;
10140 	uint64_t		capacity;
10141 	uint_t			lbasize;
10142 	int			rval = SD_READY_VALID;
10143 	char			name_str[48];
10144 	int			is_valid;
10145 	struct sd_lun		*un;
10146 	int			status;
10147 
10148 	ASSERT(ssc != NULL);
10149 	un = ssc->ssc_un;
10150 	ASSERT(un != NULL);
10151 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10152 
10153 	mutex_enter(SD_MUTEX(un));
10154 	/*
10155 	 * If a device has removable media, we must check if media is
10156 	 * ready when checking if this device is ready and valid.
10157 	 */
10158 	if (un->un_f_has_removable_media) {
10159 		mutex_exit(SD_MUTEX(un));
10160 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10161 
10162 		if (status != 0) {
10163 			rval = SD_NOT_READY_VALID;
10164 			mutex_enter(SD_MUTEX(un));
10165 
10166 			/* Ignore all failed status for removalbe media */
10167 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10168 
10169 			goto done;
10170 		}
10171 
10172 		is_valid = SD_IS_VALID_LABEL(un);
10173 		mutex_enter(SD_MUTEX(un));
10174 		if (!is_valid ||
10175 		    (un->un_f_blockcount_is_valid == FALSE) ||
10176 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10177 
10178 			/* capacity has to be read every open. */
10179 			mutex_exit(SD_MUTEX(un));
10180 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
10181 			    &lbasize, SD_PATH_DIRECT);
10182 
10183 			if (status != 0) {
10184 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10185 
10186 				cmlb_invalidate(un->un_cmlbhandle,
10187 				    (void *)SD_PATH_DIRECT);
10188 				mutex_enter(SD_MUTEX(un));
10189 				rval = SD_NOT_READY_VALID;
10190 
10191 				goto done;
10192 			} else {
10193 				mutex_enter(SD_MUTEX(un));
10194 				sd_update_block_info(un, lbasize, capacity);
10195 			}
10196 		}
10197 
10198 		/*
10199 		 * Check if the media in the device is writable or not.
10200 		 */
10201 		if (!is_valid && ISCD(un)) {
10202 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
10203 		}
10204 
10205 	} else {
10206 		/*
10207 		 * Do a test unit ready to clear any unit attention from non-cd
10208 		 * devices.
10209 		 */
10210 		mutex_exit(SD_MUTEX(un));
10211 
10212 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10213 		if (status != 0) {
10214 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10215 		}
10216 
10217 		mutex_enter(SD_MUTEX(un));
10218 	}
10219 
10220 
10221 	/*
10222 	 * If this is a non 512 block device, allocate space for
10223 	 * the wmap cache. This is being done here since every time
10224 	 * a media is changed this routine will be called and the
10225 	 * block size is a function of media rather than device.
10226 	 */
10227 	if (un->un_f_non_devbsize_supported && NOT_DEVBSIZE(un)) {
10228 		if (!(un->un_wm_cache)) {
10229 			(void) snprintf(name_str, sizeof (name_str),
10230 			    "%s%d_cache",
10231 			    ddi_driver_name(SD_DEVINFO(un)),
10232 			    ddi_get_instance(SD_DEVINFO(un)));
10233 			un->un_wm_cache = kmem_cache_create(
10234 			    name_str, sizeof (struct sd_w_map),
10235 			    8, sd_wm_cache_constructor,
10236 			    sd_wm_cache_destructor, NULL,
10237 			    (void *)un, NULL, 0);
10238 			if (!(un->un_wm_cache)) {
10239 				rval = ENOMEM;
10240 				goto done;
10241 			}
10242 		}
10243 	}
10244 
10245 	if (un->un_state == SD_STATE_NORMAL) {
10246 		/*
10247 		 * If the target is not yet ready here (defined by a TUR
10248 		 * failure), invalidate the geometry and print an 'offline'
10249 		 * message. This is a legacy message, as the state of the
10250 		 * target is not actually changed to SD_STATE_OFFLINE.
10251 		 *
10252 		 * If the TUR fails for EACCES (Reservation Conflict),
10253 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
10254 		 * reservation conflict. If the TUR fails for other
10255 		 * reasons, SD_NOT_READY_VALID will be returned.
10256 		 */
10257 		int err;
10258 
10259 		mutex_exit(SD_MUTEX(un));
10260 		err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10261 		mutex_enter(SD_MUTEX(un));
10262 
10263 		if (err != 0) {
10264 			mutex_exit(SD_MUTEX(un));
10265 			cmlb_invalidate(un->un_cmlbhandle,
10266 			    (void *)SD_PATH_DIRECT);
10267 			mutex_enter(SD_MUTEX(un));
10268 			if (err == EACCES) {
10269 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10270 				    "reservation conflict\n");
10271 				rval = SD_RESERVED_BY_OTHERS;
10272 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10273 			} else {
10274 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10275 				    "drive offline\n");
10276 				rval = SD_NOT_READY_VALID;
10277 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
10278 			}
10279 			goto done;
10280 		}
10281 	}
10282 
10283 	if (un->un_f_format_in_progress == FALSE) {
10284 		mutex_exit(SD_MUTEX(un));
10285 
10286 		if (cmlb_partinfo(un->un_cmlbhandle, part, NULL, NULL, NULL,
10287 		    NULL, (void *) SD_PATH_DIRECT) != 0) {
10288 			rval = SD_NOT_READY_VALID;
10289 			mutex_enter(SD_MUTEX(un));
10290 
10291 			goto done;
10292 		}
10293 		if (un->un_f_pkstats_enabled) {
10294 			sd_set_pstats(un);
10295 			SD_TRACE(SD_LOG_IO_PARTITION, un,
10296 			    "sd_ready_and_valid: un:0x%p pstats created and "
10297 			    "set\n", un);
10298 		}
10299 		mutex_enter(SD_MUTEX(un));
10300 	}
10301 
10302 	/*
10303 	 * If this device supports DOOR_LOCK command, try and send
10304 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10305 	 * if it fails. For a CD, however, it is an error
10306 	 */
10307 	if (un->un_f_doorlock_supported) {
10308 		mutex_exit(SD_MUTEX(un));
10309 		status = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
10310 		    SD_PATH_DIRECT);
10311 
10312 		if ((status != 0) && ISCD(un)) {
10313 			rval = SD_NOT_READY_VALID;
10314 			mutex_enter(SD_MUTEX(un));
10315 
10316 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10317 
10318 			goto done;
10319 		} else if (status != 0)
10320 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10321 		mutex_enter(SD_MUTEX(un));
10322 	}
10323 
10324 	/* The state has changed, inform the media watch routines */
10325 	un->un_mediastate = DKIO_INSERTED;
10326 	cv_broadcast(&un->un_state_cv);
10327 	rval = SD_READY_VALID;
10328 
10329 done:
10330 
10331 	/*
10332 	 * Initialize the capacity kstat value, if no media previously
10333 	 * (capacity kstat is 0) and a media has been inserted
10334 	 * (un_blockcount > 0).
10335 	 */
10336 	if (un->un_errstats != NULL) {
10337 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10338 		if ((stp->sd_capacity.value.ui64 == 0) &&
10339 		    (un->un_f_blockcount_is_valid == TRUE)) {
10340 			stp->sd_capacity.value.ui64 =
10341 			    (uint64_t)((uint64_t)un->un_blockcount *
10342 			    un->un_sys_blocksize);
10343 		}
10344 	}
10345 
10346 	mutex_exit(SD_MUTEX(un));
10347 	return (rval);
10348 }
10349 
10350 
10351 /*
10352  *    Function: sdmin
10353  *
10354  * Description: Routine to limit the size of a data transfer. Used in
10355  *		conjunction with physio(9F).
10356  *
10357  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10358  *
10359  *     Context: Kernel thread context.
10360  */
10361 
10362 static void
10363 sdmin(struct buf *bp)
10364 {
10365 	struct sd_lun	*un;
10366 	int		instance;
10367 
10368 	instance = SDUNIT(bp->b_edev);
10369 
10370 	un = ddi_get_soft_state(sd_state, instance);
10371 	ASSERT(un != NULL);
10372 
10373 	if (bp->b_bcount > un->un_max_xfer_size) {
10374 		bp->b_bcount = un->un_max_xfer_size;
10375 	}
10376 }
10377 
10378 
10379 /*
10380  *    Function: sdread
10381  *
10382  * Description: Driver's read(9e) entry point function.
10383  *
10384  *   Arguments: dev   - device number
10385  *		uio   - structure pointer describing where data is to be stored
10386  *			in user's space
10387  *		cred_p  - user credential pointer
10388  *
10389  * Return Code: ENXIO
10390  *		EIO
10391  *		EINVAL
10392  *		value returned by physio
10393  *
10394  *     Context: Kernel thread context.
10395  */
10396 /* ARGSUSED */
10397 static int
10398 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10399 {
10400 	struct sd_lun	*un = NULL;
10401 	int		secmask;
10402 	int		err = 0;
10403 	sd_ssc_t	*ssc;
10404 
10405 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10406 		return (ENXIO);
10407 	}
10408 
10409 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10410 
10411 
10412 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10413 		mutex_enter(SD_MUTEX(un));
10414 		/*
10415 		 * Because the call to sd_ready_and_valid will issue I/O we
10416 		 * must wait here if either the device is suspended or
10417 		 * if it's power level is changing.
10418 		 */
10419 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10420 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10421 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10422 		}
10423 		un->un_ncmds_in_driver++;
10424 		mutex_exit(SD_MUTEX(un));
10425 
10426 		/* Initialize sd_ssc_t for internal uscsi commands */
10427 		ssc = sd_ssc_init(un);
10428 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10429 			err = EIO;
10430 		} else {
10431 			err = 0;
10432 		}
10433 		sd_ssc_fini(ssc);
10434 
10435 		mutex_enter(SD_MUTEX(un));
10436 		un->un_ncmds_in_driver--;
10437 		ASSERT(un->un_ncmds_in_driver >= 0);
10438 		mutex_exit(SD_MUTEX(un));
10439 		if (err != 0)
10440 			return (err);
10441 	}
10442 
10443 	/*
10444 	 * Read requests are restricted to multiples of the system block size.
10445 	 */
10446 	secmask = un->un_sys_blocksize - 1;
10447 
10448 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10449 		SD_ERROR(SD_LOG_READ_WRITE, un,
10450 		    "sdread: file offset not modulo %d\n",
10451 		    un->un_sys_blocksize);
10452 		err = EINVAL;
10453 	} else if (uio->uio_iov->iov_len & (secmask)) {
10454 		SD_ERROR(SD_LOG_READ_WRITE, un,
10455 		    "sdread: transfer length not modulo %d\n",
10456 		    un->un_sys_blocksize);
10457 		err = EINVAL;
10458 	} else {
10459 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
10460 	}
10461 
10462 	return (err);
10463 }
10464 
10465 
10466 /*
10467  *    Function: sdwrite
10468  *
10469  * Description: Driver's write(9e) entry point function.
10470  *
10471  *   Arguments: dev   - device number
10472  *		uio   - structure pointer describing where data is stored in
10473  *			user's space
10474  *		cred_p  - user credential pointer
10475  *
10476  * Return Code: ENXIO
10477  *		EIO
10478  *		EINVAL
10479  *		value returned by physio
10480  *
10481  *     Context: Kernel thread context.
10482  */
10483 /* ARGSUSED */
10484 static int
10485 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
10486 {
10487 	struct sd_lun	*un = NULL;
10488 	int		secmask;
10489 	int		err = 0;
10490 	sd_ssc_t	*ssc;
10491 
10492 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10493 		return (ENXIO);
10494 	}
10495 
10496 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10497 
10498 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10499 		mutex_enter(SD_MUTEX(un));
10500 		/*
10501 		 * Because the call to sd_ready_and_valid will issue I/O we
10502 		 * must wait here if either the device is suspended or
10503 		 * if it's power level is changing.
10504 		 */
10505 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10506 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10507 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10508 		}
10509 		un->un_ncmds_in_driver++;
10510 		mutex_exit(SD_MUTEX(un));
10511 
10512 		/* Initialize sd_ssc_t for internal uscsi commands */
10513 		ssc = sd_ssc_init(un);
10514 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10515 			err = EIO;
10516 		} else {
10517 			err = 0;
10518 		}
10519 		sd_ssc_fini(ssc);
10520 
10521 		mutex_enter(SD_MUTEX(un));
10522 		un->un_ncmds_in_driver--;
10523 		ASSERT(un->un_ncmds_in_driver >= 0);
10524 		mutex_exit(SD_MUTEX(un));
10525 		if (err != 0)
10526 			return (err);
10527 	}
10528 
10529 	/*
10530 	 * Write requests are restricted to multiples of the system block size.
10531 	 */
10532 	secmask = un->un_sys_blocksize - 1;
10533 
10534 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10535 		SD_ERROR(SD_LOG_READ_WRITE, un,
10536 		    "sdwrite: file offset not modulo %d\n",
10537 		    un->un_sys_blocksize);
10538 		err = EINVAL;
10539 	} else if (uio->uio_iov->iov_len & (secmask)) {
10540 		SD_ERROR(SD_LOG_READ_WRITE, un,
10541 		    "sdwrite: transfer length not modulo %d\n",
10542 		    un->un_sys_blocksize);
10543 		err = EINVAL;
10544 	} else {
10545 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
10546 	}
10547 
10548 	return (err);
10549 }
10550 
10551 
10552 /*
10553  *    Function: sdaread
10554  *
10555  * Description: Driver's aread(9e) entry point function.
10556  *
10557  *   Arguments: dev   - device number
10558  *		aio   - structure pointer describing where data is to be stored
10559  *		cred_p  - user credential pointer
10560  *
10561  * Return Code: ENXIO
10562  *		EIO
10563  *		EINVAL
10564  *		value returned by aphysio
10565  *
10566  *     Context: Kernel thread context.
10567  */
10568 /* ARGSUSED */
10569 static int
10570 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10571 {
10572 	struct sd_lun	*un = NULL;
10573 	struct uio	*uio = aio->aio_uio;
10574 	int		secmask;
10575 	int		err = 0;
10576 	sd_ssc_t	*ssc;
10577 
10578 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10579 		return (ENXIO);
10580 	}
10581 
10582 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10583 
10584 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10585 		mutex_enter(SD_MUTEX(un));
10586 		/*
10587 		 * Because the call to sd_ready_and_valid will issue I/O we
10588 		 * must wait here if either the device is suspended or
10589 		 * if it's power level is changing.
10590 		 */
10591 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10592 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10593 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10594 		}
10595 		un->un_ncmds_in_driver++;
10596 		mutex_exit(SD_MUTEX(un));
10597 
10598 		/* Initialize sd_ssc_t for internal uscsi commands */
10599 		ssc = sd_ssc_init(un);
10600 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10601 			err = EIO;
10602 		} else {
10603 			err = 0;
10604 		}
10605 		sd_ssc_fini(ssc);
10606 
10607 		mutex_enter(SD_MUTEX(un));
10608 		un->un_ncmds_in_driver--;
10609 		ASSERT(un->un_ncmds_in_driver >= 0);
10610 		mutex_exit(SD_MUTEX(un));
10611 		if (err != 0)
10612 			return (err);
10613 	}
10614 
10615 	/*
10616 	 * Read requests are restricted to multiples of the system block size.
10617 	 */
10618 	secmask = un->un_sys_blocksize - 1;
10619 
10620 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10621 		SD_ERROR(SD_LOG_READ_WRITE, un,
10622 		    "sdaread: file offset not modulo %d\n",
10623 		    un->un_sys_blocksize);
10624 		err = EINVAL;
10625 	} else if (uio->uio_iov->iov_len & (secmask)) {
10626 		SD_ERROR(SD_LOG_READ_WRITE, un,
10627 		    "sdaread: transfer length not modulo %d\n",
10628 		    un->un_sys_blocksize);
10629 		err = EINVAL;
10630 	} else {
10631 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
10632 	}
10633 
10634 	return (err);
10635 }
10636 
10637 
10638 /*
10639  *    Function: sdawrite
10640  *
10641  * Description: Driver's awrite(9e) entry point function.
10642  *
10643  *   Arguments: dev   - device number
10644  *		aio   - structure pointer describing where data is stored
10645  *		cred_p  - user credential pointer
10646  *
10647  * Return Code: ENXIO
10648  *		EIO
10649  *		EINVAL
10650  *		value returned by aphysio
10651  *
10652  *     Context: Kernel thread context.
10653  */
10654 /* ARGSUSED */
10655 static int
10656 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10657 {
10658 	struct sd_lun	*un = NULL;
10659 	struct uio	*uio = aio->aio_uio;
10660 	int		secmask;
10661 	int		err = 0;
10662 	sd_ssc_t	*ssc;
10663 
10664 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10665 		return (ENXIO);
10666 	}
10667 
10668 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10669 
10670 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10671 		mutex_enter(SD_MUTEX(un));
10672 		/*
10673 		 * Because the call to sd_ready_and_valid will issue I/O we
10674 		 * must wait here if either the device is suspended or
10675 		 * if it's power level is changing.
10676 		 */
10677 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10678 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10679 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10680 		}
10681 		un->un_ncmds_in_driver++;
10682 		mutex_exit(SD_MUTEX(un));
10683 
10684 		/* Initialize sd_ssc_t for internal uscsi commands */
10685 		ssc = sd_ssc_init(un);
10686 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10687 			err = EIO;
10688 		} else {
10689 			err = 0;
10690 		}
10691 		sd_ssc_fini(ssc);
10692 
10693 		mutex_enter(SD_MUTEX(un));
10694 		un->un_ncmds_in_driver--;
10695 		ASSERT(un->un_ncmds_in_driver >= 0);
10696 		mutex_exit(SD_MUTEX(un));
10697 		if (err != 0)
10698 			return (err);
10699 	}
10700 
10701 	/*
10702 	 * Write requests are restricted to multiples of the system block size.
10703 	 */
10704 	secmask = un->un_sys_blocksize - 1;
10705 
10706 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10707 		SD_ERROR(SD_LOG_READ_WRITE, un,
10708 		    "sdawrite: file offset not modulo %d\n",
10709 		    un->un_sys_blocksize);
10710 		err = EINVAL;
10711 	} else if (uio->uio_iov->iov_len & (secmask)) {
10712 		SD_ERROR(SD_LOG_READ_WRITE, un,
10713 		    "sdawrite: transfer length not modulo %d\n",
10714 		    un->un_sys_blocksize);
10715 		err = EINVAL;
10716 	} else {
10717 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
10718 	}
10719 
10720 	return (err);
10721 }
10722 
10723 
10724 
10725 
10726 
10727 /*
10728  * Driver IO processing follows the following sequence:
10729  *
10730  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
10731  *         |                |                     ^
10732  *         v                v                     |
10733  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
10734  *         |                |                     |                   |
10735  *         v                |                     |                   |
10736  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
10737  *         |                |                     ^                   ^
10738  *         v                v                     |                   |
10739  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
10740  *         |                |                     |                   |
10741  *     +---+                |                     +------------+      +-------+
10742  *     |                    |                                  |              |
10743  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10744  *     |                    v                                  |              |
10745  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
10746  *     |                    |                                  ^              |
10747  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10748  *     |                    v                                  |              |
10749  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
10750  *     |                    |                                  ^              |
10751  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10752  *     |                    v                                  |              |
10753  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
10754  *     |                    |                                  ^              |
10755  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
10756  *     |                    v                                  |              |
10757  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
10758  *     |                    |                                  ^              |
10759  *     |                    |                                  |              |
10760  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
10761  *                          |                           ^
10762  *                          v                           |
10763  *                   sd_core_iostart()                  |
10764  *                          |                           |
10765  *                          |                           +------>(*destroypkt)()
10766  *                          +-> sd_start_cmds() <-+     |           |
10767  *                          |                     |     |           v
10768  *                          |                     |     |  scsi_destroy_pkt(9F)
10769  *                          |                     |     |
10770  *                          +->(*initpkt)()       +- sdintr()
10771  *                          |  |                        |  |
10772  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
10773  *                          |  +-> scsi_setup_cdb(9F)   |
10774  *                          |                           |
10775  *                          +--> scsi_transport(9F)     |
10776  *                                     |                |
10777  *                                     +----> SCSA ---->+
10778  *
10779  *
10780  * This code is based upon the following presumptions:
10781  *
10782  *   - iostart and iodone functions operate on buf(9S) structures. These
10783  *     functions perform the necessary operations on the buf(9S) and pass
10784  *     them along to the next function in the chain by using the macros
10785  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
10786  *     (for iodone side functions).
10787  *
10788  *   - The iostart side functions may sleep. The iodone side functions
10789  *     are called under interrupt context and may NOT sleep. Therefore
10790  *     iodone side functions also may not call iostart side functions.
10791  *     (NOTE: iostart side functions should NOT sleep for memory, as
10792  *     this could result in deadlock.)
10793  *
10794  *   - An iostart side function may call its corresponding iodone side
10795  *     function directly (if necessary).
10796  *
10797  *   - In the event of an error, an iostart side function can return a buf(9S)
10798  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
10799  *     b_error in the usual way of course).
10800  *
10801  *   - The taskq mechanism may be used by the iodone side functions to dispatch
10802  *     requests to the iostart side functions.  The iostart side functions in
10803  *     this case would be called under the context of a taskq thread, so it's
10804  *     OK for them to block/sleep/spin in this case.
10805  *
10806  *   - iostart side functions may allocate "shadow" buf(9S) structs and
10807  *     pass them along to the next function in the chain.  The corresponding
10808  *     iodone side functions must coalesce the "shadow" bufs and return
10809  *     the "original" buf to the next higher layer.
10810  *
10811  *   - The b_private field of the buf(9S) struct holds a pointer to
10812  *     an sd_xbuf struct, which contains information needed to
10813  *     construct the scsi_pkt for the command.
10814  *
10815  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
10816  *     layer must acquire & release the SD_MUTEX(un) as needed.
10817  */
10818 
10819 
10820 /*
10821  * Create taskq for all targets in the system. This is created at
10822  * _init(9E) and destroyed at _fini(9E).
10823  *
10824  * Note: here we set the minalloc to a reasonably high number to ensure that
10825  * we will have an adequate supply of task entries available at interrupt time.
10826  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
10827  * sd_create_taskq().  Since we do not want to sleep for allocations at
10828  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
10829  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
10830  * requests any one instant in time.
10831  */
10832 #define	SD_TASKQ_NUMTHREADS	8
10833 #define	SD_TASKQ_MINALLOC	256
10834 #define	SD_TASKQ_MAXALLOC	256
10835 
10836 static taskq_t	*sd_tq = NULL;
10837 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
10838 
10839 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
10840 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
10841 
10842 /*
10843  * The following task queue is being created for the write part of
10844  * read-modify-write of non-512 block size devices.
10845  * Limit the number of threads to 1 for now. This number has been chosen
10846  * considering the fact that it applies only to dvd ram drives/MO drives
10847  * currently. Performance for which is not main criteria at this stage.
10848  * Note: It needs to be explored if we can use a single taskq in future
10849  */
10850 #define	SD_WMR_TASKQ_NUMTHREADS	1
10851 static taskq_t	*sd_wmr_tq = NULL;
10852 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
10853 
10854 /*
10855  *    Function: sd_taskq_create
10856  *
10857  * Description: Create taskq thread(s) and preallocate task entries
10858  *
10859  * Return Code: Returns a pointer to the allocated taskq_t.
10860  *
10861  *     Context: Can sleep. Requires blockable context.
10862  *
10863  *       Notes: - The taskq() facility currently is NOT part of the DDI.
10864  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
10865  *		- taskq_create() will block for memory, also it will panic
10866  *		  if it cannot create the requested number of threads.
10867  *		- Currently taskq_create() creates threads that cannot be
10868  *		  swapped.
10869  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
10870  *		  supply of taskq entries at interrupt time (ie, so that we
10871  *		  do not have to sleep for memory)
10872  */
10873 
10874 static void
10875 sd_taskq_create(void)
10876 {
10877 	char	taskq_name[TASKQ_NAMELEN];
10878 
10879 	ASSERT(sd_tq == NULL);
10880 	ASSERT(sd_wmr_tq == NULL);
10881 
10882 	(void) snprintf(taskq_name, sizeof (taskq_name),
10883 	    "%s_drv_taskq", sd_label);
10884 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
10885 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10886 	    TASKQ_PREPOPULATE));
10887 
10888 	(void) snprintf(taskq_name, sizeof (taskq_name),
10889 	    "%s_rmw_taskq", sd_label);
10890 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
10891 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10892 	    TASKQ_PREPOPULATE));
10893 }
10894 
10895 
10896 /*
10897  *    Function: sd_taskq_delete
10898  *
10899  * Description: Complementary cleanup routine for sd_taskq_create().
10900  *
10901  *     Context: Kernel thread context.
10902  */
10903 
10904 static void
10905 sd_taskq_delete(void)
10906 {
10907 	ASSERT(sd_tq != NULL);
10908 	ASSERT(sd_wmr_tq != NULL);
10909 	taskq_destroy(sd_tq);
10910 	taskq_destroy(sd_wmr_tq);
10911 	sd_tq = NULL;
10912 	sd_wmr_tq = NULL;
10913 }
10914 
10915 
10916 /*
10917  *    Function: sdstrategy
10918  *
10919  * Description: Driver's strategy (9E) entry point function.
10920  *
10921  *   Arguments: bp - pointer to buf(9S)
10922  *
10923  * Return Code: Always returns zero
10924  *
10925  *     Context: Kernel thread context.
10926  */
10927 
10928 static int
10929 sdstrategy(struct buf *bp)
10930 {
10931 	struct sd_lun *un;
10932 
10933 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10934 	if (un == NULL) {
10935 		bioerror(bp, EIO);
10936 		bp->b_resid = bp->b_bcount;
10937 		biodone(bp);
10938 		return (0);
10939 	}
10940 	/* As was done in the past, fail new cmds. if state is dumping. */
10941 	if (un->un_state == SD_STATE_DUMPING) {
10942 		bioerror(bp, ENXIO);
10943 		bp->b_resid = bp->b_bcount;
10944 		biodone(bp);
10945 		return (0);
10946 	}
10947 
10948 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10949 
10950 	/*
10951 	 * Commands may sneak in while we released the mutex in
10952 	 * DDI_SUSPEND, we should block new commands. However, old
10953 	 * commands that are still in the driver at this point should
10954 	 * still be allowed to drain.
10955 	 */
10956 	mutex_enter(SD_MUTEX(un));
10957 	/*
10958 	 * Must wait here if either the device is suspended or
10959 	 * if it's power level is changing.
10960 	 */
10961 	while ((un->un_state == SD_STATE_SUSPENDED) ||
10962 	    (un->un_state == SD_STATE_PM_CHANGING)) {
10963 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10964 	}
10965 
10966 	un->un_ncmds_in_driver++;
10967 
10968 	/*
10969 	 * atapi: Since we are running the CD for now in PIO mode we need to
10970 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10971 	 * the HBA's init_pkt routine.
10972 	 */
10973 	if (un->un_f_cfg_is_atapi == TRUE) {
10974 		mutex_exit(SD_MUTEX(un));
10975 		bp_mapin(bp);
10976 		mutex_enter(SD_MUTEX(un));
10977 	}
10978 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
10979 	    un->un_ncmds_in_driver);
10980 
10981 	if (bp->b_flags & B_WRITE)
10982 		un->un_f_sync_cache_required = TRUE;
10983 
10984 	mutex_exit(SD_MUTEX(un));
10985 
10986 	/*
10987 	 * This will (eventually) allocate the sd_xbuf area and
10988 	 * call sd_xbuf_strategy().  We just want to return the
10989 	 * result of ddi_xbuf_qstrategy so that we have an opt-
10990 	 * imized tail call which saves us a stack frame.
10991 	 */
10992 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
10993 }
10994 
10995 
10996 /*
10997  *    Function: sd_xbuf_strategy
10998  *
10999  * Description: Function for initiating IO operations via the
11000  *		ddi_xbuf_qstrategy() mechanism.
11001  *
11002  *     Context: Kernel thread context.
11003  */
11004 
11005 static void
11006 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11007 {
11008 	struct sd_lun *un = arg;
11009 
11010 	ASSERT(bp != NULL);
11011 	ASSERT(xp != NULL);
11012 	ASSERT(un != NULL);
11013 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11014 
11015 	/*
11016 	 * Initialize the fields in the xbuf and save a pointer to the
11017 	 * xbuf in bp->b_private.
11018 	 */
11019 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11020 
11021 	/* Send the buf down the iostart chain */
11022 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11023 }
11024 
11025 
11026 /*
11027  *    Function: sd_xbuf_init
11028  *
11029  * Description: Prepare the given sd_xbuf struct for use.
11030  *
11031  *   Arguments: un - ptr to softstate
11032  *		bp - ptr to associated buf(9S)
11033  *		xp - ptr to associated sd_xbuf
11034  *		chain_type - IO chain type to use:
11035  *			SD_CHAIN_NULL
11036  *			SD_CHAIN_BUFIO
11037  *			SD_CHAIN_USCSI
11038  *			SD_CHAIN_DIRECT
11039  *			SD_CHAIN_DIRECT_PRIORITY
11040  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11041  *			initialization; may be NULL if none.
11042  *
11043  *     Context: Kernel thread context
11044  */
11045 
11046 static void
11047 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11048 	uchar_t chain_type, void *pktinfop)
11049 {
11050 	int index;
11051 
11052 	ASSERT(un != NULL);
11053 	ASSERT(bp != NULL);
11054 	ASSERT(xp != NULL);
11055 
11056 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11057 	    bp, chain_type);
11058 
11059 	xp->xb_un	= un;
11060 	xp->xb_pktp	= NULL;
11061 	xp->xb_pktinfo	= pktinfop;
11062 	xp->xb_private	= bp->b_private;
11063 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11064 
11065 	/*
11066 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11067 	 * upon the specified chain type to use.
11068 	 */
11069 	switch (chain_type) {
11070 	case SD_CHAIN_NULL:
11071 		/*
11072 		 * Fall thru to just use the values for the buf type, even
11073 		 * tho for the NULL chain these values will never be used.
11074 		 */
11075 		/* FALLTHRU */
11076 	case SD_CHAIN_BUFIO:
11077 		index = un->un_buf_chain_type;
11078 		break;
11079 	case SD_CHAIN_USCSI:
11080 		index = un->un_uscsi_chain_type;
11081 		break;
11082 	case SD_CHAIN_DIRECT:
11083 		index = un->un_direct_chain_type;
11084 		break;
11085 	case SD_CHAIN_DIRECT_PRIORITY:
11086 		index = un->un_priority_chain_type;
11087 		break;
11088 	default:
11089 		/* We're really broken if we ever get here... */
11090 		panic("sd_xbuf_init: illegal chain type!");
11091 		/*NOTREACHED*/
11092 	}
11093 
11094 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11095 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11096 
11097 	/*
11098 	 * It might be a bit easier to simply bzero the entire xbuf above,
11099 	 * but it turns out that since we init a fair number of members anyway,
11100 	 * we save a fair number cycles by doing explicit assignment of zero.
11101 	 */
11102 	xp->xb_pkt_flags	= 0;
11103 	xp->xb_dma_resid	= 0;
11104 	xp->xb_retry_count	= 0;
11105 	xp->xb_victim_retry_count = 0;
11106 	xp->xb_ua_retry_count	= 0;
11107 	xp->xb_nr_retry_count	= 0;
11108 	xp->xb_sense_bp		= NULL;
11109 	xp->xb_sense_status	= 0;
11110 	xp->xb_sense_state	= 0;
11111 	xp->xb_sense_resid	= 0;
11112 	xp->xb_ena		= 0;
11113 
11114 	bp->b_private	= xp;
11115 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11116 	bp->b_resid	= 0;
11117 	bp->av_forw	= NULL;
11118 	bp->av_back	= NULL;
11119 	bioerror(bp, 0);
11120 
11121 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11122 }
11123 
11124 
11125 /*
11126  *    Function: sd_uscsi_strategy
11127  *
11128  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11129  *
11130  *   Arguments: bp - buf struct ptr
11131  *
11132  * Return Code: Always returns 0
11133  *
11134  *     Context: Kernel thread context
11135  */
11136 
11137 static int
11138 sd_uscsi_strategy(struct buf *bp)
11139 {
11140 	struct sd_lun		*un;
11141 	struct sd_uscsi_info	*uip;
11142 	struct sd_xbuf		*xp;
11143 	uchar_t			chain_type;
11144 	uchar_t			cmd;
11145 
11146 	ASSERT(bp != NULL);
11147 
11148 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11149 	if (un == NULL) {
11150 		bioerror(bp, EIO);
11151 		bp->b_resid = bp->b_bcount;
11152 		biodone(bp);
11153 		return (0);
11154 	}
11155 
11156 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11157 
11158 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11159 
11160 	/*
11161 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11162 	 */
11163 	ASSERT(bp->b_private != NULL);
11164 	uip = (struct sd_uscsi_info *)bp->b_private;
11165 	cmd = ((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_cdb[0];
11166 
11167 	mutex_enter(SD_MUTEX(un));
11168 	/*
11169 	 * atapi: Since we are running the CD for now in PIO mode we need to
11170 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11171 	 * the HBA's init_pkt routine.
11172 	 */
11173 	if (un->un_f_cfg_is_atapi == TRUE) {
11174 		mutex_exit(SD_MUTEX(un));
11175 		bp_mapin(bp);
11176 		mutex_enter(SD_MUTEX(un));
11177 	}
11178 	un->un_ncmds_in_driver++;
11179 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11180 	    un->un_ncmds_in_driver);
11181 
11182 	if ((bp->b_flags & B_WRITE) && (bp->b_bcount != 0) &&
11183 	    (cmd != SCMD_MODE_SELECT) && (cmd != SCMD_MODE_SELECT_G1))
11184 		un->un_f_sync_cache_required = TRUE;
11185 
11186 	mutex_exit(SD_MUTEX(un));
11187 
11188 	switch (uip->ui_flags) {
11189 	case SD_PATH_DIRECT:
11190 		chain_type = SD_CHAIN_DIRECT;
11191 		break;
11192 	case SD_PATH_DIRECT_PRIORITY:
11193 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11194 		break;
11195 	default:
11196 		chain_type = SD_CHAIN_USCSI;
11197 		break;
11198 	}
11199 
11200 	/*
11201 	 * We may allocate extra buf for external USCSI commands. If the
11202 	 * application asks for bigger than 20-byte sense data via USCSI,
11203 	 * SCSA layer will allocate 252 bytes sense buf for that command.
11204 	 */
11205 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
11206 	    SENSE_LENGTH) {
11207 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
11208 		    MAX_SENSE_LENGTH, KM_SLEEP);
11209 	} else {
11210 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
11211 	}
11212 
11213 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11214 
11215 	/* Use the index obtained within xbuf_init */
11216 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11217 
11218 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11219 
11220 	return (0);
11221 }
11222 
11223 /*
11224  *    Function: sd_send_scsi_cmd
11225  *
11226  * Description: Runs a USCSI command for user (when called thru sdioctl),
11227  *		or for the driver
11228  *
11229  *   Arguments: dev - the dev_t for the device
11230  *		incmd - ptr to a valid uscsi_cmd struct
11231  *		flag - bit flag, indicating open settings, 32/64 bit type
11232  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11233  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11234  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11235  *			to use the USCSI "direct" chain and bypass the normal
11236  *			command waitq.
11237  *
11238  * Return Code: 0 -  successful completion of the given command
11239  *		EIO - scsi_uscsi_handle_command() failed
11240  *		ENXIO  - soft state not found for specified dev
11241  *		EINVAL
11242  *		EFAULT - copyin/copyout error
11243  *		return code of scsi_uscsi_handle_command():
11244  *			EIO
11245  *			ENXIO
11246  *			EACCES
11247  *
11248  *     Context: Waits for command to complete. Can sleep.
11249  */
11250 
11251 static int
11252 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
11253 	enum uio_seg dataspace, int path_flag)
11254 {
11255 	struct sd_lun	*un;
11256 	sd_ssc_t	*ssc;
11257 	int		rval;
11258 
11259 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11260 	if (un == NULL) {
11261 		return (ENXIO);
11262 	}
11263 
11264 	/*
11265 	 * Using sd_ssc_send to handle uscsi cmd
11266 	 */
11267 	ssc = sd_ssc_init(un);
11268 	rval = sd_ssc_send(ssc, incmd, flag, dataspace, path_flag);
11269 	sd_ssc_fini(ssc);
11270 
11271 	return (rval);
11272 }
11273 
11274 /*
11275  *    Function: sd_ssc_init
11276  *
11277  * Description: Uscsi end-user call this function to initialize necessary
11278  *              fields, such as uscsi_cmd and sd_uscsi_info struct.
11279  *
11280  *              The return value of sd_send_scsi_cmd will be treated as a
11281  *              fault in various conditions. Even it is not Zero, some
11282  *              callers may ignore the return value. That is to say, we can
11283  *              not make an accurate assessment in sdintr, since if a
11284  *              command is failed in sdintr it does not mean the caller of
11285  *              sd_send_scsi_cmd will treat it as a real failure.
11286  *
11287  *              To avoid printing too many error logs for a failed uscsi
11288  *              packet that the caller may not treat it as a failure, the
11289  *              sd will keep silent for handling all uscsi commands.
11290  *
11291  *              During detach->attach and attach-open, for some types of
11292  *              problems, the driver should be providing information about
11293  *              the problem encountered. Device use USCSI_SILENT, which
11294  *              suppresses all driver information. The result is that no
11295  *              information about the problem is available. Being
11296  *              completely silent during this time is inappropriate. The
11297  *              driver needs a more selective filter than USCSI_SILENT, so
11298  *              that information related to faults is provided.
11299  *
11300  *              To make the accurate accessment, the caller  of
11301  *              sd_send_scsi_USCSI_CMD should take the ownership and
11302  *              get necessary information to print error messages.
11303  *
11304  *              If we want to print necessary info of uscsi command, we need to
11305  *              keep the uscsi_cmd and sd_uscsi_info till we can make the
11306  *              assessment. We use sd_ssc_init to alloc necessary
11307  *              structs for sending an uscsi command and we are also
11308  *              responsible for free the memory by calling
11309  *              sd_ssc_fini.
11310  *
11311  *              The calling secquences will look like:
11312  *              sd_ssc_init->
11313  *
11314  *                  ...
11315  *
11316  *                  sd_send_scsi_USCSI_CMD->
11317  *                      sd_ssc_send-> - - - sdintr
11318  *                  ...
11319  *
11320  *                  if we think the return value should be treated as a
11321  *                  failure, we make the accessment here and print out
11322  *                  necessary by retrieving uscsi_cmd and sd_uscsi_info'
11323  *
11324  *                  ...
11325  *
11326  *              sd_ssc_fini
11327  *
11328  *
11329  *   Arguments: un - pointer to driver soft state (unit) structure for this
11330  *                   target.
11331  *
11332  * Return code: sd_ssc_t - pointer to allocated sd_ssc_t struct, it contains
11333  *                         uscsi_cmd and sd_uscsi_info.
11334  *                  NULL - if can not alloc memory for sd_ssc_t struct
11335  *
11336  *     Context: Kernel Thread.
11337  */
11338 static sd_ssc_t *
11339 sd_ssc_init(struct sd_lun *un)
11340 {
11341 	sd_ssc_t		*ssc;
11342 	struct uscsi_cmd	*ucmdp;
11343 	struct sd_uscsi_info	*uip;
11344 
11345 	ASSERT(un != NULL);
11346 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11347 
11348 	/*
11349 	 * Allocate sd_ssc_t structure
11350 	 */
11351 	ssc = kmem_zalloc(sizeof (sd_ssc_t), KM_SLEEP);
11352 
11353 	/*
11354 	 * Allocate uscsi_cmd by calling scsi_uscsi_alloc common routine
11355 	 */
11356 	ucmdp = scsi_uscsi_alloc();
11357 
11358 	/*
11359 	 * Allocate sd_uscsi_info structure
11360 	 */
11361 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11362 
11363 	ssc->ssc_uscsi_cmd = ucmdp;
11364 	ssc->ssc_uscsi_info = uip;
11365 	ssc->ssc_un = un;
11366 
11367 	return (ssc);
11368 }
11369 
11370 /*
11371  * Function: sd_ssc_fini
11372  *
11373  * Description: To free sd_ssc_t and it's hanging off
11374  *
11375  * Arguments: ssc - struct pointer of sd_ssc_t.
11376  */
11377 static void
11378 sd_ssc_fini(sd_ssc_t *ssc)
11379 {
11380 	scsi_uscsi_free(ssc->ssc_uscsi_cmd);
11381 
11382 	if (ssc->ssc_uscsi_info != NULL) {
11383 		kmem_free(ssc->ssc_uscsi_info, sizeof (struct sd_uscsi_info));
11384 		ssc->ssc_uscsi_info = NULL;
11385 	}
11386 
11387 	kmem_free(ssc, sizeof (sd_ssc_t));
11388 	ssc = NULL;
11389 }
11390 
11391 /*
11392  * Function: sd_ssc_send
11393  *
11394  * Description: Runs a USCSI command for user when called through sdioctl,
11395  *              or for the driver.
11396  *
11397  *   Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11398  *                    sd_uscsi_info in.
11399  *		incmd - ptr to a valid uscsi_cmd struct
11400  *		flag - bit flag, indicating open settings, 32/64 bit type
11401  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11402  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11403  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11404  *			to use the USCSI "direct" chain and bypass the normal
11405  *			command waitq.
11406  *
11407  * Return Code: 0 -  successful completion of the given command
11408  *		EIO - scsi_uscsi_handle_command() failed
11409  *		ENXIO  - soft state not found for specified dev
11410  *		EINVAL
11411  *		EFAULT - copyin/copyout error
11412  *		return code of scsi_uscsi_handle_command():
11413  *			EIO
11414  *			ENXIO
11415  *			EACCES
11416  *
11417  *     Context: Kernel Thread;
11418  *              Waits for command to complete. Can sleep.
11419  */
11420 static int
11421 sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd, int flag,
11422 	enum uio_seg dataspace, int path_flag)
11423 {
11424 	struct sd_uscsi_info	*uip;
11425 	struct uscsi_cmd	*uscmd;
11426 	struct sd_lun		*un;
11427 	dev_t			dev;
11428 
11429 	int	format = 0;
11430 	int	rval;
11431 
11432 	ASSERT(ssc != NULL);
11433 	un = ssc->ssc_un;
11434 	ASSERT(un != NULL);
11435 	uscmd = ssc->ssc_uscsi_cmd;
11436 	ASSERT(uscmd != NULL);
11437 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11438 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
11439 		/*
11440 		 * If enter here, it indicates that the previous uscsi
11441 		 * command has not been processed by sd_ssc_assessment.
11442 		 * This is violating our rules of FMA telemetry processing.
11443 		 * We should print out this message and the last undisposed
11444 		 * uscsi command.
11445 		 */
11446 		if (uscmd->uscsi_cdb != NULL) {
11447 			SD_INFO(SD_LOG_SDTEST, un,
11448 			    "sd_ssc_send is missing the alternative "
11449 			    "sd_ssc_assessment when running command 0x%x.\n",
11450 			    uscmd->uscsi_cdb[0]);
11451 		}
11452 		/*
11453 		 * Set the ssc_flags to SSC_FLAGS_UNKNOWN, which should be
11454 		 * the initial status.
11455 		 */
11456 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11457 	}
11458 
11459 	/*
11460 	 * We need to make sure sd_ssc_send will have sd_ssc_assessment
11461 	 * followed to avoid missing FMA telemetries.
11462 	 */
11463 	ssc->ssc_flags |= SSC_FLAGS_NEED_ASSESSMENT;
11464 
11465 #ifdef SDDEBUG
11466 	switch (dataspace) {
11467 	case UIO_USERSPACE:
11468 		SD_TRACE(SD_LOG_IO, un,
11469 		    "sd_ssc_send: entry: un:0x%p UIO_USERSPACE\n", un);
11470 		break;
11471 	case UIO_SYSSPACE:
11472 		SD_TRACE(SD_LOG_IO, un,
11473 		    "sd_ssc_send: entry: un:0x%p UIO_SYSSPACE\n", un);
11474 		break;
11475 	default:
11476 		SD_TRACE(SD_LOG_IO, un,
11477 		    "sd_ssc_send: entry: un:0x%p UNEXPECTED SPACE\n", un);
11478 		break;
11479 	}
11480 #endif
11481 
11482 	rval = scsi_uscsi_copyin((intptr_t)incmd, flag,
11483 	    SD_ADDRESS(un), &uscmd);
11484 	if (rval != 0) {
11485 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
11486 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
11487 		return (rval);
11488 	}
11489 
11490 	if ((uscmd->uscsi_cdb != NULL) &&
11491 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
11492 		mutex_enter(SD_MUTEX(un));
11493 		un->un_f_format_in_progress = TRUE;
11494 		mutex_exit(SD_MUTEX(un));
11495 		format = 1;
11496 	}
11497 
11498 	/*
11499 	 * Allocate an sd_uscsi_info struct and fill it with the info
11500 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
11501 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
11502 	 * since we allocate the buf here in this function, we do not
11503 	 * need to preserve the prior contents of b_private.
11504 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
11505 	 */
11506 	uip = ssc->ssc_uscsi_info;
11507 	uip->ui_flags = path_flag;
11508 	uip->ui_cmdp = uscmd;
11509 
11510 	/*
11511 	 * Commands sent with priority are intended for error recovery
11512 	 * situations, and do not have retries performed.
11513 	 */
11514 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
11515 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
11516 	}
11517 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
11518 
11519 	dev = SD_GET_DEV(un);
11520 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
11521 	    sd_uscsi_strategy, NULL, uip);
11522 
11523 	/*
11524 	 * mark ssc_flags right after handle_cmd to make sure
11525 	 * the uscsi has been sent
11526 	 */
11527 	ssc->ssc_flags |= SSC_FLAGS_CMD_ISSUED;
11528 
11529 #ifdef SDDEBUG
11530 	SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11531 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
11532 	    uscmd->uscsi_status, uscmd->uscsi_resid);
11533 	if (uscmd->uscsi_bufaddr != NULL) {
11534 		SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11535 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
11536 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
11537 		if (dataspace == UIO_SYSSPACE) {
11538 			SD_DUMP_MEMORY(un, SD_LOG_IO,
11539 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
11540 			    uscmd->uscsi_buflen, SD_LOG_HEX);
11541 		}
11542 	}
11543 #endif
11544 
11545 	if (format == 1) {
11546 		mutex_enter(SD_MUTEX(un));
11547 		un->un_f_format_in_progress = FALSE;
11548 		mutex_exit(SD_MUTEX(un));
11549 	}
11550 
11551 	(void) scsi_uscsi_copyout((intptr_t)incmd, uscmd);
11552 
11553 	return (rval);
11554 }
11555 
11556 /*
11557  *     Function: sd_ssc_print
11558  *
11559  * Description: Print information available to the console.
11560  *
11561  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11562  *                    sd_uscsi_info in.
11563  *            sd_severity - log level.
11564  *     Context: Kernel thread or interrupt context.
11565  */
11566 static void
11567 sd_ssc_print(sd_ssc_t *ssc, int sd_severity)
11568 {
11569 	struct uscsi_cmd	*ucmdp;
11570 	struct scsi_device	*devp;
11571 	dev_info_t 		*devinfo;
11572 	uchar_t			*sensep;
11573 	int			senlen;
11574 	union scsi_cdb		*cdbp;
11575 	uchar_t			com;
11576 	extern struct scsi_key_strings scsi_cmds[];
11577 
11578 	ASSERT(ssc != NULL);
11579 	ASSERT(ssc->ssc_un != NULL);
11580 
11581 	if (SD_FM_LOG(ssc->ssc_un) != SD_FM_LOG_EREPORT)
11582 		return;
11583 	ucmdp = ssc->ssc_uscsi_cmd;
11584 	devp = SD_SCSI_DEVP(ssc->ssc_un);
11585 	devinfo = SD_DEVINFO(ssc->ssc_un);
11586 	ASSERT(ucmdp != NULL);
11587 	ASSERT(devp != NULL);
11588 	ASSERT(devinfo != NULL);
11589 	sensep = (uint8_t *)ucmdp->uscsi_rqbuf;
11590 	senlen = ucmdp->uscsi_rqlen - ucmdp->uscsi_rqresid;
11591 	cdbp = (union scsi_cdb *)ucmdp->uscsi_cdb;
11592 
11593 	/* In certain case (like DOORLOCK), the cdb could be NULL. */
11594 	if (cdbp == NULL)
11595 		return;
11596 	/* We don't print log if no sense data available. */
11597 	if (senlen == 0)
11598 		sensep = NULL;
11599 	com = cdbp->scc_cmd;
11600 	scsi_generic_errmsg(devp, sd_label, sd_severity, 0, 0, com,
11601 	    scsi_cmds, sensep, ssc->ssc_un->un_additional_codes, NULL);
11602 }
11603 
11604 /*
11605  *     Function: sd_ssc_assessment
11606  *
11607  * Description: We use this function to make an assessment at the point
11608  *              where SD driver may encounter a potential error.
11609  *
11610  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11611  *                  sd_uscsi_info in.
11612  *            tp_assess - a hint of strategy for ereport posting.
11613  *            Possible values of tp_assess include:
11614  *                SD_FMT_IGNORE - we don't post any ereport because we're
11615  *                sure that it is ok to ignore the underlying problems.
11616  *                SD_FMT_IGNORE_COMPROMISE - we don't post any ereport for now
11617  *                but it might be not correct to ignore the underlying hardware
11618  *                error.
11619  *                SD_FMT_STATUS_CHECK - we will post an ereport with the
11620  *                payload driver-assessment of value "fail" or
11621  *                "fatal"(depending on what information we have here). This
11622  *                assessment value is usually set when SD driver think there
11623  *                is a potential error occurred(Typically, when return value
11624  *                of the SCSI command is EIO).
11625  *                SD_FMT_STANDARD - we will post an ereport with the payload
11626  *                driver-assessment of value "info". This assessment value is
11627  *                set when the SCSI command returned successfully and with
11628  *                sense data sent back.
11629  *
11630  *     Context: Kernel thread.
11631  */
11632 static void
11633 sd_ssc_assessment(sd_ssc_t *ssc, enum sd_type_assessment tp_assess)
11634 {
11635 	int senlen = 0;
11636 	struct uscsi_cmd *ucmdp = NULL;
11637 	struct sd_lun *un;
11638 
11639 	ASSERT(ssc != NULL);
11640 	un = ssc->ssc_un;
11641 	ASSERT(un != NULL);
11642 	ucmdp = ssc->ssc_uscsi_cmd;
11643 	ASSERT(ucmdp != NULL);
11644 
11645 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
11646 		ssc->ssc_flags &= ~SSC_FLAGS_NEED_ASSESSMENT;
11647 	} else {
11648 		/*
11649 		 * If enter here, it indicates that we have a wrong
11650 		 * calling sequence of sd_ssc_send and sd_ssc_assessment,
11651 		 * both of which should be called in a pair in case of
11652 		 * loss of FMA telemetries.
11653 		 */
11654 		if (ucmdp->uscsi_cdb != NULL) {
11655 			SD_INFO(SD_LOG_SDTEST, un,
11656 			    "sd_ssc_assessment is missing the "
11657 			    "alternative sd_ssc_send when running 0x%x, "
11658 			    "or there are superfluous sd_ssc_assessment for "
11659 			    "the same sd_ssc_send.\n",
11660 			    ucmdp->uscsi_cdb[0]);
11661 		}
11662 		/*
11663 		 * Set the ssc_flags to the initial value to avoid passing
11664 		 * down dirty flags to the following sd_ssc_send function.
11665 		 */
11666 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11667 		return;
11668 	}
11669 
11670 	/*
11671 	 * Only handle an issued command which is waiting for assessment.
11672 	 * A command which is not issued will not have
11673 	 * SSC_FLAGS_INVALID_DATA set, so it'ok we just return here.
11674 	 */
11675 	if (!(ssc->ssc_flags & SSC_FLAGS_CMD_ISSUED)) {
11676 		sd_ssc_print(ssc, SCSI_ERR_INFO);
11677 		return;
11678 	} else {
11679 		/*
11680 		 * For an issued command, we should clear this flag in
11681 		 * order to make the sd_ssc_t structure be used off
11682 		 * multiple uscsi commands.
11683 		 */
11684 		ssc->ssc_flags &= ~SSC_FLAGS_CMD_ISSUED;
11685 	}
11686 
11687 	/*
11688 	 * We will not deal with non-retryable(flag USCSI_DIAGNOSE set)
11689 	 * commands here. And we should clear the ssc_flags before return.
11690 	 */
11691 	if (ucmdp->uscsi_flags & USCSI_DIAGNOSE) {
11692 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11693 		return;
11694 	}
11695 
11696 	switch (tp_assess) {
11697 	case SD_FMT_IGNORE:
11698 	case SD_FMT_IGNORE_COMPROMISE:
11699 		break;
11700 	case SD_FMT_STATUS_CHECK:
11701 		/*
11702 		 * For a failed command(including the succeeded command
11703 		 * with invalid data sent back).
11704 		 */
11705 		sd_ssc_post(ssc, SD_FM_DRV_FATAL);
11706 		break;
11707 	case SD_FMT_STANDARD:
11708 		/*
11709 		 * Always for the succeeded commands probably with sense
11710 		 * data sent back.
11711 		 * Limitation:
11712 		 *	We can only handle a succeeded command with sense
11713 		 *	data sent back when auto-request-sense is enabled.
11714 		 */
11715 		senlen = ssc->ssc_uscsi_cmd->uscsi_rqlen -
11716 		    ssc->ssc_uscsi_cmd->uscsi_rqresid;
11717 		if ((ssc->ssc_uscsi_info->ui_pkt_state & STATE_ARQ_DONE) &&
11718 		    (un->un_f_arq_enabled == TRUE) &&
11719 		    senlen > 0 &&
11720 		    ssc->ssc_uscsi_cmd->uscsi_rqbuf != NULL) {
11721 			sd_ssc_post(ssc, SD_FM_DRV_NOTICE);
11722 		}
11723 		break;
11724 	default:
11725 		/*
11726 		 * Should not have other type of assessment.
11727 		 */
11728 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
11729 		    "sd_ssc_assessment got wrong "
11730 		    "sd_type_assessment %d.\n", tp_assess);
11731 		break;
11732 	}
11733 	/*
11734 	 * Clear up the ssc_flags before return.
11735 	 */
11736 	ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11737 }
11738 
11739 /*
11740  *    Function: sd_ssc_post
11741  *
11742  * Description: 1. read the driver property to get fm-scsi-log flag.
11743  *              2. print log if fm_log_capable is non-zero.
11744  *              3. call sd_ssc_ereport_post to post ereport if possible.
11745  *
11746  *    Context: May be called from kernel thread or interrupt context.
11747  */
11748 static void
11749 sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess)
11750 {
11751 	struct sd_lun	*un;
11752 	int		sd_severity;
11753 
11754 	ASSERT(ssc != NULL);
11755 	un = ssc->ssc_un;
11756 	ASSERT(un != NULL);
11757 
11758 	/*
11759 	 * We may enter here from sd_ssc_assessment(for USCSI command) or
11760 	 * by directly called from sdintr context.
11761 	 * We don't handle a non-disk drive(CD-ROM, removable media).
11762 	 * Clear the ssc_flags before return in case we've set
11763 	 * SSC_FLAGS_INVALID_XXX which should be skipped for a non-disk
11764 	 * driver.
11765 	 */
11766 	if (ISCD(un) || un->un_f_has_removable_media) {
11767 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11768 		return;
11769 	}
11770 
11771 	switch (sd_assess) {
11772 		case SD_FM_DRV_FATAL:
11773 			sd_severity = SCSI_ERR_FATAL;
11774 			break;
11775 		case SD_FM_DRV_RECOVERY:
11776 			sd_severity = SCSI_ERR_RECOVERED;
11777 			break;
11778 		case SD_FM_DRV_RETRY:
11779 			sd_severity = SCSI_ERR_RETRYABLE;
11780 			break;
11781 		case SD_FM_DRV_NOTICE:
11782 			sd_severity = SCSI_ERR_INFO;
11783 			break;
11784 		default:
11785 			sd_severity = SCSI_ERR_UNKNOWN;
11786 	}
11787 	/* print log */
11788 	sd_ssc_print(ssc, sd_severity);
11789 
11790 	/* always post ereport */
11791 	sd_ssc_ereport_post(ssc, sd_assess);
11792 }
11793 
11794 /*
11795  *    Function: sd_ssc_set_info
11796  *
11797  * Description: Mark ssc_flags and set ssc_info which would be the
11798  *              payload of uderr ereport. This function will cause
11799  *              sd_ssc_ereport_post to post uderr ereport only.
11800  *              Besides, when ssc_flags == SSC_FLAGS_INVALID_DATA(USCSI),
11801  *              the function will also call SD_ERROR or scsi_log for a
11802  *              CDROM/removable-media/DDI_FM_NOT_CAPABLE device.
11803  *
11804  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11805  *                  sd_uscsi_info in.
11806  *            ssc_flags - indicate the sub-category of a uderr.
11807  *            comp - this argument is meaningful only when
11808  *                   ssc_flags == SSC_FLAGS_INVALID_DATA, and its possible
11809  *                   values include:
11810  *                   > 0, SD_ERROR is used with comp as the driver logging
11811  *                   component;
11812  *                   = 0, scsi-log is used to log error telemetries;
11813  *                   < 0, no log available for this telemetry.
11814  *
11815  *    Context: Kernel thread or interrupt context
11816  */
11817 static void
11818 sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp, const char *fmt, ...)
11819 {
11820 	va_list	ap;
11821 
11822 	ASSERT(ssc != NULL);
11823 	ASSERT(ssc->ssc_un != NULL);
11824 
11825 	ssc->ssc_flags |= ssc_flags;
11826 	va_start(ap, fmt);
11827 	(void) vsnprintf(ssc->ssc_info, sizeof (ssc->ssc_info), fmt, ap);
11828 	va_end(ap);
11829 
11830 	/*
11831 	 * If SSC_FLAGS_INVALID_DATA is set, it should be a uscsi command
11832 	 * with invalid data sent back. For non-uscsi command, the
11833 	 * following code will be bypassed.
11834 	 */
11835 	if (ssc_flags & SSC_FLAGS_INVALID_DATA) {
11836 		if (SD_FM_LOG(ssc->ssc_un) == SD_FM_LOG_NSUP) {
11837 			/*
11838 			 * If the error belong to certain component and we
11839 			 * do not want it to show up on the console, we
11840 			 * will use SD_ERROR, otherwise scsi_log is
11841 			 * preferred.
11842 			 */
11843 			if (comp > 0) {
11844 				SD_ERROR(comp, ssc->ssc_un, ssc->ssc_info);
11845 			} else if (comp == 0) {
11846 				scsi_log(SD_DEVINFO(ssc->ssc_un), sd_label,
11847 				    CE_WARN, ssc->ssc_info);
11848 			}
11849 		}
11850 	}
11851 }
11852 
11853 /*
11854  *    Function: sd_buf_iodone
11855  *
11856  * Description: Frees the sd_xbuf & returns the buf to its originator.
11857  *
11858  *     Context: May be called from interrupt context.
11859  */
11860 /* ARGSUSED */
11861 static void
11862 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
11863 {
11864 	struct sd_xbuf *xp;
11865 
11866 	ASSERT(un != NULL);
11867 	ASSERT(bp != NULL);
11868 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11869 
11870 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
11871 
11872 	xp = SD_GET_XBUF(bp);
11873 	ASSERT(xp != NULL);
11874 
11875 	mutex_enter(SD_MUTEX(un));
11876 
11877 	/*
11878 	 * Grab time when the cmd completed.
11879 	 * This is used for determining if the system has been
11880 	 * idle long enough to make it idle to the PM framework.
11881 	 * This is for lowering the overhead, and therefore improving
11882 	 * performance per I/O operation.
11883 	 */
11884 	un->un_pm_idle_time = ddi_get_time();
11885 
11886 	un->un_ncmds_in_driver--;
11887 	ASSERT(un->un_ncmds_in_driver >= 0);
11888 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
11889 	    un->un_ncmds_in_driver);
11890 
11891 	mutex_exit(SD_MUTEX(un));
11892 
11893 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
11894 	biodone(bp);				/* bp is gone after this */
11895 
11896 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
11897 }
11898 
11899 
11900 /*
11901  *    Function: sd_uscsi_iodone
11902  *
11903  * Description: Frees the sd_xbuf & returns the buf to its originator.
11904  *
11905  *     Context: May be called from interrupt context.
11906  */
11907 /* ARGSUSED */
11908 static void
11909 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
11910 {
11911 	struct sd_xbuf *xp;
11912 
11913 	ASSERT(un != NULL);
11914 	ASSERT(bp != NULL);
11915 
11916 	xp = SD_GET_XBUF(bp);
11917 	ASSERT(xp != NULL);
11918 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11919 
11920 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
11921 
11922 	bp->b_private = xp->xb_private;
11923 
11924 	mutex_enter(SD_MUTEX(un));
11925 
11926 	/*
11927 	 * Grab time when the cmd completed.
11928 	 * This is used for determining if the system has been
11929 	 * idle long enough to make it idle to the PM framework.
11930 	 * This is for lowering the overhead, and therefore improving
11931 	 * performance per I/O operation.
11932 	 */
11933 	un->un_pm_idle_time = ddi_get_time();
11934 
11935 	un->un_ncmds_in_driver--;
11936 	ASSERT(un->un_ncmds_in_driver >= 0);
11937 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
11938 	    un->un_ncmds_in_driver);
11939 
11940 	mutex_exit(SD_MUTEX(un));
11941 
11942 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
11943 	    SENSE_LENGTH) {
11944 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
11945 		    MAX_SENSE_LENGTH);
11946 	} else {
11947 		kmem_free(xp, sizeof (struct sd_xbuf));
11948 	}
11949 
11950 	biodone(bp);
11951 
11952 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
11953 }
11954 
11955 
11956 /*
11957  *    Function: sd_mapblockaddr_iostart
11958  *
11959  * Description: Verify request lies within the partition limits for
11960  *		the indicated minor device.  Issue "overrun" buf if
11961  *		request would exceed partition range.  Converts
11962  *		partition-relative block address to absolute.
11963  *
11964  *     Context: Can sleep
11965  *
11966  *      Issues: This follows what the old code did, in terms of accessing
11967  *		some of the partition info in the unit struct without holding
11968  *		the mutext.  This is a general issue, if the partition info
11969  *		can be altered while IO is in progress... as soon as we send
11970  *		a buf, its partitioning can be invalid before it gets to the
11971  *		device.  Probably the right fix is to move partitioning out
11972  *		of the driver entirely.
11973  */
11974 
11975 static void
11976 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
11977 {
11978 	diskaddr_t	nblocks;	/* #blocks in the given partition */
11979 	daddr_t	blocknum;	/* Block number specified by the buf */
11980 	size_t	requested_nblocks;
11981 	size_t	available_nblocks;
11982 	int	partition;
11983 	diskaddr_t	partition_offset;
11984 	struct sd_xbuf *xp;
11985 
11986 	ASSERT(un != NULL);
11987 	ASSERT(bp != NULL);
11988 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11989 
11990 	SD_TRACE(SD_LOG_IO_PARTITION, un,
11991 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
11992 
11993 	xp = SD_GET_XBUF(bp);
11994 	ASSERT(xp != NULL);
11995 
11996 	/*
11997 	 * If the geometry is not indicated as valid, attempt to access
11998 	 * the unit & verify the geometry/label. This can be the case for
11999 	 * removable-media devices, of if the device was opened in
12000 	 * NDELAY/NONBLOCK mode.
12001 	 */
12002 	partition = SDPART(bp->b_edev);
12003 
12004 	if (!SD_IS_VALID_LABEL(un)) {
12005 		sd_ssc_t *ssc;
12006 		/*
12007 		 * Initialize sd_ssc_t for internal uscsi commands
12008 		 * In case of potential porformance issue, we need
12009 		 * to alloc memory only if there is invalid label
12010 		 */
12011 		ssc = sd_ssc_init(un);
12012 
12013 		if (sd_ready_and_valid(ssc, partition) != SD_READY_VALID) {
12014 			/*
12015 			 * For removable devices it is possible to start an
12016 			 * I/O without a media by opening the device in nodelay
12017 			 * mode. Also for writable CDs there can be many
12018 			 * scenarios where there is no geometry yet but volume
12019 			 * manager is trying to issue a read() just because
12020 			 * it can see TOC on the CD. So do not print a message
12021 			 * for removables.
12022 			 */
12023 			if (!un->un_f_has_removable_media) {
12024 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12025 				    "i/o to invalid geometry\n");
12026 			}
12027 			bioerror(bp, EIO);
12028 			bp->b_resid = bp->b_bcount;
12029 			SD_BEGIN_IODONE(index, un, bp);
12030 
12031 			sd_ssc_fini(ssc);
12032 			return;
12033 		}
12034 		sd_ssc_fini(ssc);
12035 	}
12036 
12037 	nblocks = 0;
12038 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
12039 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
12040 
12041 	/*
12042 	 * blocknum is the starting block number of the request. At this
12043 	 * point it is still relative to the start of the minor device.
12044 	 */
12045 	blocknum = xp->xb_blkno;
12046 
12047 	/*
12048 	 * Legacy: If the starting block number is one past the last block
12049 	 * in the partition, do not set B_ERROR in the buf.
12050 	 */
12051 	if (blocknum == nblocks)  {
12052 		goto error_exit;
12053 	}
12054 
12055 	/*
12056 	 * Confirm that the first block of the request lies within the
12057 	 * partition limits. Also the requested number of bytes must be
12058 	 * a multiple of the system block size.
12059 	 */
12060 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12061 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
12062 		bp->b_flags |= B_ERROR;
12063 		goto error_exit;
12064 	}
12065 
12066 	/*
12067 	 * If the requsted # blocks exceeds the available # blocks, that
12068 	 * is an overrun of the partition.
12069 	 */
12070 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
12071 	available_nblocks = (size_t)(nblocks - blocknum);
12072 	ASSERT(nblocks >= blocknum);
12073 
12074 	if (requested_nblocks > available_nblocks) {
12075 		/*
12076 		 * Allocate an "overrun" buf to allow the request to proceed
12077 		 * for the amount of space available in the partition. The
12078 		 * amount not transferred will be added into the b_resid
12079 		 * when the operation is complete. The overrun buf
12080 		 * replaces the original buf here, and the original buf
12081 		 * is saved inside the overrun buf, for later use.
12082 		 */
12083 		size_t resid = SD_SYSBLOCKS2BYTES(un,
12084 		    (offset_t)(requested_nblocks - available_nblocks));
12085 		size_t count = bp->b_bcount - resid;
12086 		/*
12087 		 * Note: count is an unsigned entity thus it'll NEVER
12088 		 * be less than 0 so ASSERT the original values are
12089 		 * correct.
12090 		 */
12091 		ASSERT(bp->b_bcount >= resid);
12092 
12093 		bp = sd_bioclone_alloc(bp, count, blocknum,
12094 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
12095 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12096 		ASSERT(xp != NULL);
12097 	}
12098 
12099 	/* At this point there should be no residual for this buf. */
12100 	ASSERT(bp->b_resid == 0);
12101 
12102 	/* Convert the block number to an absolute address. */
12103 	xp->xb_blkno += partition_offset;
12104 
12105 	SD_NEXT_IOSTART(index, un, bp);
12106 
12107 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12108 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12109 
12110 	return;
12111 
12112 error_exit:
12113 	bp->b_resid = bp->b_bcount;
12114 	SD_BEGIN_IODONE(index, un, bp);
12115 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12116 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12117 }
12118 
12119 
12120 /*
12121  *    Function: sd_mapblockaddr_iodone
12122  *
12123  * Description: Completion-side processing for partition management.
12124  *
12125  *     Context: May be called under interrupt context
12126  */
12127 
12128 static void
12129 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12130 {
12131 	/* int	partition; */	/* Not used, see below. */
12132 	ASSERT(un != NULL);
12133 	ASSERT(bp != NULL);
12134 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12135 
12136 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12137 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12138 
12139 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
12140 		/*
12141 		 * We have an "overrun" buf to deal with...
12142 		 */
12143 		struct sd_xbuf	*xp;
12144 		struct buf	*obp;	/* ptr to the original buf */
12145 
12146 		xp = SD_GET_XBUF(bp);
12147 		ASSERT(xp != NULL);
12148 
12149 		/* Retrieve the pointer to the original buf */
12150 		obp = (struct buf *)xp->xb_private;
12151 		ASSERT(obp != NULL);
12152 
12153 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12154 		bioerror(obp, bp->b_error);
12155 
12156 		sd_bioclone_free(bp);
12157 
12158 		/*
12159 		 * Get back the original buf.
12160 		 * Note that since the restoration of xb_blkno below
12161 		 * was removed, the sd_xbuf is not needed.
12162 		 */
12163 		bp = obp;
12164 		/*
12165 		 * xp = SD_GET_XBUF(bp);
12166 		 * ASSERT(xp != NULL);
12167 		 */
12168 	}
12169 
12170 	/*
12171 	 * Convert sd->xb_blkno back to a minor-device relative value.
12172 	 * Note: this has been commented out, as it is not needed in the
12173 	 * current implementation of the driver (ie, since this function
12174 	 * is at the top of the layering chains, so the info will be
12175 	 * discarded) and it is in the "hot" IO path.
12176 	 *
12177 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12178 	 * xp->xb_blkno -= un->un_offset[partition];
12179 	 */
12180 
12181 	SD_NEXT_IODONE(index, un, bp);
12182 
12183 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12184 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12185 }
12186 
12187 
12188 /*
12189  *    Function: sd_mapblocksize_iostart
12190  *
12191  * Description: Convert between system block size (un->un_sys_blocksize)
12192  *		and target block size (un->un_tgt_blocksize).
12193  *
12194  *     Context: Can sleep to allocate resources.
12195  *
12196  * Assumptions: A higher layer has already performed any partition validation,
12197  *		and converted the xp->xb_blkno to an absolute value relative
12198  *		to the start of the device.
12199  *
12200  *		It is also assumed that the higher layer has implemented
12201  *		an "overrun" mechanism for the case where the request would
12202  *		read/write beyond the end of a partition.  In this case we
12203  *		assume (and ASSERT) that bp->b_resid == 0.
12204  *
12205  *		Note: The implementation for this routine assumes the target
12206  *		block size remains constant between allocation and transport.
12207  */
12208 
12209 static void
12210 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12211 {
12212 	struct sd_mapblocksize_info	*bsp;
12213 	struct sd_xbuf			*xp;
12214 	offset_t first_byte;
12215 	daddr_t	start_block, end_block;
12216 	daddr_t	request_bytes;
12217 	ushort_t is_aligned = FALSE;
12218 
12219 	ASSERT(un != NULL);
12220 	ASSERT(bp != NULL);
12221 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12222 	ASSERT(bp->b_resid == 0);
12223 
12224 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12225 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12226 
12227 	/*
12228 	 * For a non-writable CD, a write request is an error
12229 	 */
12230 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12231 	    (un->un_f_mmc_writable_media == FALSE)) {
12232 		bioerror(bp, EIO);
12233 		bp->b_resid = bp->b_bcount;
12234 		SD_BEGIN_IODONE(index, un, bp);
12235 		return;
12236 	}
12237 
12238 	/*
12239 	 * We do not need a shadow buf if the device is using
12240 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12241 	 * In this case there is no layer-private data block allocated.
12242 	 */
12243 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
12244 	    (bp->b_bcount == 0)) {
12245 		goto done;
12246 	}
12247 
12248 #if defined(__i386) || defined(__amd64)
12249 	/* We do not support non-block-aligned transfers for ROD devices */
12250 	ASSERT(!ISROD(un));
12251 #endif
12252 
12253 	xp = SD_GET_XBUF(bp);
12254 	ASSERT(xp != NULL);
12255 
12256 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12257 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12258 	    un->un_tgt_blocksize, un->un_sys_blocksize);
12259 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12260 	    "request start block:0x%x\n", xp->xb_blkno);
12261 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12262 	    "request len:0x%x\n", bp->b_bcount);
12263 
12264 	/*
12265 	 * Allocate the layer-private data area for the mapblocksize layer.
12266 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12267 	 * struct to store the pointer to their layer-private data block, but
12268 	 * each layer also has the responsibility of restoring the prior
12269 	 * contents of xb_private before returning the buf/xbuf to the
12270 	 * higher layer that sent it.
12271 	 *
12272 	 * Here we save the prior contents of xp->xb_private into the
12273 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12274 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12275 	 * the layer-private area and returning the buf/xbuf to the layer
12276 	 * that sent it.
12277 	 *
12278 	 * Note that here we use kmem_zalloc for the allocation as there are
12279 	 * parts of the mapblocksize code that expect certain fields to be
12280 	 * zero unless explicitly set to a required value.
12281 	 */
12282 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12283 	bsp->mbs_oprivate = xp->xb_private;
12284 	xp->xb_private = bsp;
12285 
12286 	/*
12287 	 * This treats the data on the disk (target) as an array of bytes.
12288 	 * first_byte is the byte offset, from the beginning of the device,
12289 	 * to the location of the request. This is converted from a
12290 	 * un->un_sys_blocksize block address to a byte offset, and then back
12291 	 * to a block address based upon a un->un_tgt_blocksize block size.
12292 	 *
12293 	 * xp->xb_blkno should be absolute upon entry into this function,
12294 	 * but, but it is based upon partitions that use the "system"
12295 	 * block size. It must be adjusted to reflect the block size of
12296 	 * the target.
12297 	 *
12298 	 * Note that end_block is actually the block that follows the last
12299 	 * block of the request, but that's what is needed for the computation.
12300 	 */
12301 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
12302 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
12303 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
12304 	    un->un_tgt_blocksize;
12305 
12306 	/* request_bytes is rounded up to a multiple of the target block size */
12307 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
12308 
12309 	/*
12310 	 * See if the starting address of the request and the request
12311 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
12312 	 * then we do not need to allocate a shadow buf to handle the request.
12313 	 */
12314 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
12315 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
12316 		is_aligned = TRUE;
12317 	}
12318 
12319 	if ((bp->b_flags & B_READ) == 0) {
12320 		/*
12321 		 * Lock the range for a write operation. An aligned request is
12322 		 * considered a simple write; otherwise the request must be a
12323 		 * read-modify-write.
12324 		 */
12325 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
12326 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
12327 	}
12328 
12329 	/*
12330 	 * Alloc a shadow buf if the request is not aligned. Also, this is
12331 	 * where the READ command is generated for a read-modify-write. (The
12332 	 * write phase is deferred until after the read completes.)
12333 	 */
12334 	if (is_aligned == FALSE) {
12335 
12336 		struct sd_mapblocksize_info	*shadow_bsp;
12337 		struct sd_xbuf	*shadow_xp;
12338 		struct buf	*shadow_bp;
12339 
12340 		/*
12341 		 * Allocate the shadow buf and it associated xbuf. Note that
12342 		 * after this call the xb_blkno value in both the original
12343 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
12344 		 * same: absolute relative to the start of the device, and
12345 		 * adjusted for the target block size. The b_blkno in the
12346 		 * shadow buf will also be set to this value. We should never
12347 		 * change b_blkno in the original bp however.
12348 		 *
12349 		 * Note also that the shadow buf will always need to be a
12350 		 * READ command, regardless of whether the incoming command
12351 		 * is a READ or a WRITE.
12352 		 */
12353 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
12354 		    xp->xb_blkno,
12355 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
12356 
12357 		shadow_xp = SD_GET_XBUF(shadow_bp);
12358 
12359 		/*
12360 		 * Allocate the layer-private data for the shadow buf.
12361 		 * (No need to preserve xb_private in the shadow xbuf.)
12362 		 */
12363 		shadow_xp->xb_private = shadow_bsp =
12364 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12365 
12366 		/*
12367 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
12368 		 * to figure out where the start of the user data is (based upon
12369 		 * the system block size) in the data returned by the READ
12370 		 * command (which will be based upon the target blocksize). Note
12371 		 * that this is only really used if the request is unaligned.
12372 		 */
12373 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
12374 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
12375 		ASSERT((bsp->mbs_copy_offset >= 0) &&
12376 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
12377 
12378 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
12379 
12380 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
12381 
12382 		/* Transfer the wmap (if any) to the shadow buf */
12383 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
12384 		bsp->mbs_wmp = NULL;
12385 
12386 		/*
12387 		 * The shadow buf goes on from here in place of the
12388 		 * original buf.
12389 		 */
12390 		shadow_bsp->mbs_orig_bp = bp;
12391 		bp = shadow_bp;
12392 	}
12393 
12394 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12395 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
12396 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12397 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
12398 	    request_bytes);
12399 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12400 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
12401 
12402 done:
12403 	SD_NEXT_IOSTART(index, un, bp);
12404 
12405 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12406 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
12407 }
12408 
12409 
12410 /*
12411  *    Function: sd_mapblocksize_iodone
12412  *
12413  * Description: Completion side processing for block-size mapping.
12414  *
12415  *     Context: May be called under interrupt context
12416  */
12417 
12418 static void
12419 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
12420 {
12421 	struct sd_mapblocksize_info	*bsp;
12422 	struct sd_xbuf	*xp;
12423 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
12424 	struct buf	*orig_bp;	/* ptr to the original buf */
12425 	offset_t	shadow_end;
12426 	offset_t	request_end;
12427 	offset_t	shadow_start;
12428 	ssize_t		copy_offset;
12429 	size_t		copy_length;
12430 	size_t		shortfall;
12431 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
12432 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
12433 
12434 	ASSERT(un != NULL);
12435 	ASSERT(bp != NULL);
12436 
12437 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12438 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
12439 
12440 	/*
12441 	 * There is no shadow buf or layer-private data if the target is
12442 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
12443 	 */
12444 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
12445 	    (bp->b_bcount == 0)) {
12446 		goto exit;
12447 	}
12448 
12449 	xp = SD_GET_XBUF(bp);
12450 	ASSERT(xp != NULL);
12451 
12452 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
12453 	bsp = xp->xb_private;
12454 
12455 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
12456 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
12457 
12458 	if (is_write) {
12459 		/*
12460 		 * For a WRITE request we must free up the block range that
12461 		 * we have locked up.  This holds regardless of whether this is
12462 		 * an aligned write request or a read-modify-write request.
12463 		 */
12464 		sd_range_unlock(un, bsp->mbs_wmp);
12465 		bsp->mbs_wmp = NULL;
12466 	}
12467 
12468 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
12469 		/*
12470 		 * An aligned read or write command will have no shadow buf;
12471 		 * there is not much else to do with it.
12472 		 */
12473 		goto done;
12474 	}
12475 
12476 	orig_bp = bsp->mbs_orig_bp;
12477 	ASSERT(orig_bp != NULL);
12478 	orig_xp = SD_GET_XBUF(orig_bp);
12479 	ASSERT(orig_xp != NULL);
12480 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12481 
12482 	if (!is_write && has_wmap) {
12483 		/*
12484 		 * A READ with a wmap means this is the READ phase of a
12485 		 * read-modify-write. If an error occurred on the READ then
12486 		 * we do not proceed with the WRITE phase or copy any data.
12487 		 * Just release the write maps and return with an error.
12488 		 */
12489 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
12490 			orig_bp->b_resid = orig_bp->b_bcount;
12491 			bioerror(orig_bp, bp->b_error);
12492 			sd_range_unlock(un, bsp->mbs_wmp);
12493 			goto freebuf_done;
12494 		}
12495 	}
12496 
12497 	/*
12498 	 * Here is where we set up to copy the data from the shadow buf
12499 	 * into the space associated with the original buf.
12500 	 *
12501 	 * To deal with the conversion between block sizes, these
12502 	 * computations treat the data as an array of bytes, with the
12503 	 * first byte (byte 0) corresponding to the first byte in the
12504 	 * first block on the disk.
12505 	 */
12506 
12507 	/*
12508 	 * shadow_start and shadow_len indicate the location and size of
12509 	 * the data returned with the shadow IO request.
12510 	 */
12511 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
12512 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
12513 
12514 	/*
12515 	 * copy_offset gives the offset (in bytes) from the start of the first
12516 	 * block of the READ request to the beginning of the data.  We retrieve
12517 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
12518 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
12519 	 * data to be copied (in bytes).
12520 	 */
12521 	copy_offset  = bsp->mbs_copy_offset;
12522 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
12523 	copy_length  = orig_bp->b_bcount;
12524 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
12525 
12526 	/*
12527 	 * Set up the resid and error fields of orig_bp as appropriate.
12528 	 */
12529 	if (shadow_end >= request_end) {
12530 		/* We got all the requested data; set resid to zero */
12531 		orig_bp->b_resid = 0;
12532 	} else {
12533 		/*
12534 		 * We failed to get enough data to fully satisfy the original
12535 		 * request. Just copy back whatever data we got and set
12536 		 * up the residual and error code as required.
12537 		 *
12538 		 * 'shortfall' is the amount by which the data received with the
12539 		 * shadow buf has "fallen short" of the requested amount.
12540 		 */
12541 		shortfall = (size_t)(request_end - shadow_end);
12542 
12543 		if (shortfall > orig_bp->b_bcount) {
12544 			/*
12545 			 * We did not get enough data to even partially
12546 			 * fulfill the original request.  The residual is
12547 			 * equal to the amount requested.
12548 			 */
12549 			orig_bp->b_resid = orig_bp->b_bcount;
12550 		} else {
12551 			/*
12552 			 * We did not get all the data that we requested
12553 			 * from the device, but we will try to return what
12554 			 * portion we did get.
12555 			 */
12556 			orig_bp->b_resid = shortfall;
12557 		}
12558 		ASSERT(copy_length >= orig_bp->b_resid);
12559 		copy_length  -= orig_bp->b_resid;
12560 	}
12561 
12562 	/* Propagate the error code from the shadow buf to the original buf */
12563 	bioerror(orig_bp, bp->b_error);
12564 
12565 	if (is_write) {
12566 		goto freebuf_done;	/* No data copying for a WRITE */
12567 	}
12568 
12569 	if (has_wmap) {
12570 		/*
12571 		 * This is a READ command from the READ phase of a
12572 		 * read-modify-write request. We have to copy the data given
12573 		 * by the user OVER the data returned by the READ command,
12574 		 * then convert the command from a READ to a WRITE and send
12575 		 * it back to the target.
12576 		 */
12577 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
12578 		    copy_length);
12579 
12580 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
12581 
12582 		/*
12583 		 * Dispatch the WRITE command to the taskq thread, which
12584 		 * will in turn send the command to the target. When the
12585 		 * WRITE command completes, we (sd_mapblocksize_iodone())
12586 		 * will get called again as part of the iodone chain
12587 		 * processing for it. Note that we will still be dealing
12588 		 * with the shadow buf at that point.
12589 		 */
12590 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
12591 		    KM_NOSLEEP) != 0) {
12592 			/*
12593 			 * Dispatch was successful so we are done. Return
12594 			 * without going any higher up the iodone chain. Do
12595 			 * not free up any layer-private data until after the
12596 			 * WRITE completes.
12597 			 */
12598 			return;
12599 		}
12600 
12601 		/*
12602 		 * Dispatch of the WRITE command failed; set up the error
12603 		 * condition and send this IO back up the iodone chain.
12604 		 */
12605 		bioerror(orig_bp, EIO);
12606 		orig_bp->b_resid = orig_bp->b_bcount;
12607 
12608 	} else {
12609 		/*
12610 		 * This is a regular READ request (ie, not a RMW). Copy the
12611 		 * data from the shadow buf into the original buf. The
12612 		 * copy_offset compensates for any "misalignment" between the
12613 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
12614 		 * original buf (with its un->un_sys_blocksize blocks).
12615 		 */
12616 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
12617 		    copy_length);
12618 	}
12619 
12620 freebuf_done:
12621 
12622 	/*
12623 	 * At this point we still have both the shadow buf AND the original
12624 	 * buf to deal with, as well as the layer-private data area in each.
12625 	 * Local variables are as follows:
12626 	 *
12627 	 * bp -- points to shadow buf
12628 	 * xp -- points to xbuf of shadow buf
12629 	 * bsp -- points to layer-private data area of shadow buf
12630 	 * orig_bp -- points to original buf
12631 	 *
12632 	 * First free the shadow buf and its associated xbuf, then free the
12633 	 * layer-private data area from the shadow buf. There is no need to
12634 	 * restore xb_private in the shadow xbuf.
12635 	 */
12636 	sd_shadow_buf_free(bp);
12637 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
12638 
12639 	/*
12640 	 * Now update the local variables to point to the original buf, xbuf,
12641 	 * and layer-private area.
12642 	 */
12643 	bp = orig_bp;
12644 	xp = SD_GET_XBUF(bp);
12645 	ASSERT(xp != NULL);
12646 	ASSERT(xp == orig_xp);
12647 	bsp = xp->xb_private;
12648 	ASSERT(bsp != NULL);
12649 
12650 done:
12651 	/*
12652 	 * Restore xb_private to whatever it was set to by the next higher
12653 	 * layer in the chain, then free the layer-private data area.
12654 	 */
12655 	xp->xb_private = bsp->mbs_oprivate;
12656 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
12657 
12658 exit:
12659 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
12660 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
12661 
12662 	SD_NEXT_IODONE(index, un, bp);
12663 }
12664 
12665 
12666 /*
12667  *    Function: sd_checksum_iostart
12668  *
12669  * Description: A stub function for a layer that's currently not used.
12670  *		For now just a placeholder.
12671  *
12672  *     Context: Kernel thread context
12673  */
12674 
12675 static void
12676 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
12677 {
12678 	ASSERT(un != NULL);
12679 	ASSERT(bp != NULL);
12680 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12681 	SD_NEXT_IOSTART(index, un, bp);
12682 }
12683 
12684 
12685 /*
12686  *    Function: sd_checksum_iodone
12687  *
12688  * Description: A stub function for a layer that's currently not used.
12689  *		For now just a placeholder.
12690  *
12691  *     Context: May be called under interrupt context
12692  */
12693 
12694 static void
12695 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
12696 {
12697 	ASSERT(un != NULL);
12698 	ASSERT(bp != NULL);
12699 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12700 	SD_NEXT_IODONE(index, un, bp);
12701 }
12702 
12703 
12704 /*
12705  *    Function: sd_checksum_uscsi_iostart
12706  *
12707  * Description: A stub function for a layer that's currently not used.
12708  *		For now just a placeholder.
12709  *
12710  *     Context: Kernel thread context
12711  */
12712 
12713 static void
12714 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
12715 {
12716 	ASSERT(un != NULL);
12717 	ASSERT(bp != NULL);
12718 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12719 	SD_NEXT_IOSTART(index, un, bp);
12720 }
12721 
12722 
12723 /*
12724  *    Function: sd_checksum_uscsi_iodone
12725  *
12726  * Description: A stub function for a layer that's currently not used.
12727  *		For now just a placeholder.
12728  *
12729  *     Context: May be called under interrupt context
12730  */
12731 
12732 static void
12733 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12734 {
12735 	ASSERT(un != NULL);
12736 	ASSERT(bp != NULL);
12737 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12738 	SD_NEXT_IODONE(index, un, bp);
12739 }
12740 
12741 
12742 /*
12743  *    Function: sd_pm_iostart
12744  *
12745  * Description: iostart-side routine for Power mangement.
12746  *
12747  *     Context: Kernel thread context
12748  */
12749 
12750 static void
12751 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
12752 {
12753 	ASSERT(un != NULL);
12754 	ASSERT(bp != NULL);
12755 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12756 	ASSERT(!mutex_owned(&un->un_pm_mutex));
12757 
12758 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
12759 
12760 	if (sd_pm_entry(un) != DDI_SUCCESS) {
12761 		/*
12762 		 * Set up to return the failed buf back up the 'iodone'
12763 		 * side of the calling chain.
12764 		 */
12765 		bioerror(bp, EIO);
12766 		bp->b_resid = bp->b_bcount;
12767 
12768 		SD_BEGIN_IODONE(index, un, bp);
12769 
12770 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
12771 		return;
12772 	}
12773 
12774 	SD_NEXT_IOSTART(index, un, bp);
12775 
12776 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
12777 }
12778 
12779 
12780 /*
12781  *    Function: sd_pm_iodone
12782  *
12783  * Description: iodone-side routine for power mangement.
12784  *
12785  *     Context: may be called from interrupt context
12786  */
12787 
12788 static void
12789 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
12790 {
12791 	ASSERT(un != NULL);
12792 	ASSERT(bp != NULL);
12793 	ASSERT(!mutex_owned(&un->un_pm_mutex));
12794 
12795 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
12796 
12797 	/*
12798 	 * After attach the following flag is only read, so don't
12799 	 * take the penalty of acquiring a mutex for it.
12800 	 */
12801 	if (un->un_f_pm_is_enabled == TRUE) {
12802 		sd_pm_exit(un);
12803 	}
12804 
12805 	SD_NEXT_IODONE(index, un, bp);
12806 
12807 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
12808 }
12809 
12810 
12811 /*
12812  *    Function: sd_core_iostart
12813  *
12814  * Description: Primary driver function for enqueuing buf(9S) structs from
12815  *		the system and initiating IO to the target device
12816  *
12817  *     Context: Kernel thread context. Can sleep.
12818  *
12819  * Assumptions:  - The given xp->xb_blkno is absolute
12820  *		   (ie, relative to the start of the device).
12821  *		 - The IO is to be done using the native blocksize of
12822  *		   the device, as specified in un->un_tgt_blocksize.
12823  */
12824 /* ARGSUSED */
12825 static void
12826 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
12827 {
12828 	struct sd_xbuf *xp;
12829 
12830 	ASSERT(un != NULL);
12831 	ASSERT(bp != NULL);
12832 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12833 	ASSERT(bp->b_resid == 0);
12834 
12835 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
12836 
12837 	xp = SD_GET_XBUF(bp);
12838 	ASSERT(xp != NULL);
12839 
12840 	mutex_enter(SD_MUTEX(un));
12841 
12842 	/*
12843 	 * If we are currently in the failfast state, fail any new IO
12844 	 * that has B_FAILFAST set, then return.
12845 	 */
12846 	if ((bp->b_flags & B_FAILFAST) &&
12847 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
12848 		mutex_exit(SD_MUTEX(un));
12849 		bioerror(bp, EIO);
12850 		bp->b_resid = bp->b_bcount;
12851 		SD_BEGIN_IODONE(index, un, bp);
12852 		return;
12853 	}
12854 
12855 	if (SD_IS_DIRECT_PRIORITY(xp)) {
12856 		/*
12857 		 * Priority command -- transport it immediately.
12858 		 *
12859 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
12860 		 * because all direct priority commands should be associated
12861 		 * with error recovery actions which we don't want to retry.
12862 		 */
12863 		sd_start_cmds(un, bp);
12864 	} else {
12865 		/*
12866 		 * Normal command -- add it to the wait queue, then start
12867 		 * transporting commands from the wait queue.
12868 		 */
12869 		sd_add_buf_to_waitq(un, bp);
12870 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
12871 		sd_start_cmds(un, NULL);
12872 	}
12873 
12874 	mutex_exit(SD_MUTEX(un));
12875 
12876 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
12877 }
12878 
12879 
12880 /*
12881  *    Function: sd_init_cdb_limits
12882  *
12883  * Description: This is to handle scsi_pkt initialization differences
12884  *		between the driver platforms.
12885  *
12886  *		Legacy behaviors:
12887  *
12888  *		If the block number or the sector count exceeds the
12889  *		capabilities of a Group 0 command, shift over to a
12890  *		Group 1 command. We don't blindly use Group 1
12891  *		commands because a) some drives (CDC Wren IVs) get a
12892  *		bit confused, and b) there is probably a fair amount
12893  *		of speed difference for a target to receive and decode
12894  *		a 10 byte command instead of a 6 byte command.
12895  *
12896  *		The xfer time difference of 6 vs 10 byte CDBs is
12897  *		still significant so this code is still worthwhile.
12898  *		10 byte CDBs are very inefficient with the fas HBA driver
12899  *		and older disks. Each CDB byte took 1 usec with some
12900  *		popular disks.
12901  *
12902  *     Context: Must be called at attach time
12903  */
12904 
12905 static void
12906 sd_init_cdb_limits(struct sd_lun *un)
12907 {
12908 	int hba_cdb_limit;
12909 
12910 	/*
12911 	 * Use CDB_GROUP1 commands for most devices except for
12912 	 * parallel SCSI fixed drives in which case we get better
12913 	 * performance using CDB_GROUP0 commands (where applicable).
12914 	 */
12915 	un->un_mincdb = SD_CDB_GROUP1;
12916 #if !defined(__fibre)
12917 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
12918 	    !un->un_f_has_removable_media) {
12919 		un->un_mincdb = SD_CDB_GROUP0;
12920 	}
12921 #endif
12922 
12923 	/*
12924 	 * Try to read the max-cdb-length supported by HBA.
12925 	 */
12926 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
12927 	if (0 >= un->un_max_hba_cdb) {
12928 		un->un_max_hba_cdb = CDB_GROUP4;
12929 		hba_cdb_limit = SD_CDB_GROUP4;
12930 	} else if (0 < un->un_max_hba_cdb &&
12931 	    un->un_max_hba_cdb < CDB_GROUP1) {
12932 		hba_cdb_limit = SD_CDB_GROUP0;
12933 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
12934 	    un->un_max_hba_cdb < CDB_GROUP5) {
12935 		hba_cdb_limit = SD_CDB_GROUP1;
12936 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
12937 	    un->un_max_hba_cdb < CDB_GROUP4) {
12938 		hba_cdb_limit = SD_CDB_GROUP5;
12939 	} else {
12940 		hba_cdb_limit = SD_CDB_GROUP4;
12941 	}
12942 
12943 	/*
12944 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
12945 	 * commands for fixed disks unless we are building for a 32 bit
12946 	 * kernel.
12947 	 */
12948 #ifdef _LP64
12949 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
12950 	    min(hba_cdb_limit, SD_CDB_GROUP4);
12951 #else
12952 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
12953 	    min(hba_cdb_limit, SD_CDB_GROUP1);
12954 #endif
12955 
12956 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
12957 	    ? sizeof (struct scsi_arq_status) : 1);
12958 	un->un_cmd_timeout = (ushort_t)sd_io_time;
12959 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
12960 }
12961 
12962 
12963 /*
12964  *    Function: sd_initpkt_for_buf
12965  *
12966  * Description: Allocate and initialize for transport a scsi_pkt struct,
12967  *		based upon the info specified in the given buf struct.
12968  *
12969  *		Assumes the xb_blkno in the request is absolute (ie,
12970  *		relative to the start of the device (NOT partition!).
12971  *		Also assumes that the request is using the native block
12972  *		size of the device (as returned by the READ CAPACITY
12973  *		command).
12974  *
12975  * Return Code: SD_PKT_ALLOC_SUCCESS
12976  *		SD_PKT_ALLOC_FAILURE
12977  *		SD_PKT_ALLOC_FAILURE_NO_DMA
12978  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
12979  *
12980  *     Context: Kernel thread and may be called from software interrupt context
12981  *		as part of a sdrunout callback. This function may not block or
12982  *		call routines that block
12983  */
12984 
12985 static int
12986 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
12987 {
12988 	struct sd_xbuf	*xp;
12989 	struct scsi_pkt *pktp = NULL;
12990 	struct sd_lun	*un;
12991 	size_t		blockcount;
12992 	daddr_t		startblock;
12993 	int		rval;
12994 	int		cmd_flags;
12995 
12996 	ASSERT(bp != NULL);
12997 	ASSERT(pktpp != NULL);
12998 	xp = SD_GET_XBUF(bp);
12999 	ASSERT(xp != NULL);
13000 	un = SD_GET_UN(bp);
13001 	ASSERT(un != NULL);
13002 	ASSERT(mutex_owned(SD_MUTEX(un)));
13003 	ASSERT(bp->b_resid == 0);
13004 
13005 	SD_TRACE(SD_LOG_IO_CORE, un,
13006 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13007 
13008 	mutex_exit(SD_MUTEX(un));
13009 
13010 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13011 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13012 		/*
13013 		 * Already have a scsi_pkt -- just need DMA resources.
13014 		 * We must recompute the CDB in case the mapping returns
13015 		 * a nonzero pkt_resid.
13016 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13017 		 * that is being retried, the unmap/remap of the DMA resouces
13018 		 * will result in the entire transfer starting over again
13019 		 * from the very first block.
13020 		 */
13021 		ASSERT(xp->xb_pktp != NULL);
13022 		pktp = xp->xb_pktp;
13023 	} else {
13024 		pktp = NULL;
13025 	}
13026 #endif /* __i386 || __amd64 */
13027 
13028 	startblock = xp->xb_blkno;	/* Absolute block num. */
13029 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13030 
13031 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13032 
13033 	/*
13034 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13035 	 * call scsi_init_pkt, and build the CDB.
13036 	 */
13037 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13038 	    cmd_flags, sdrunout, (caddr_t)un,
13039 	    startblock, blockcount);
13040 
13041 	if (rval == 0) {
13042 		/*
13043 		 * Success.
13044 		 *
13045 		 * If partial DMA is being used and required for this transfer.
13046 		 * set it up here.
13047 		 */
13048 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13049 		    (pktp->pkt_resid != 0)) {
13050 
13051 			/*
13052 			 * Save the CDB length and pkt_resid for the
13053 			 * next xfer
13054 			 */
13055 			xp->xb_dma_resid = pktp->pkt_resid;
13056 
13057 			/* rezero resid */
13058 			pktp->pkt_resid = 0;
13059 
13060 		} else {
13061 			xp->xb_dma_resid = 0;
13062 		}
13063 
13064 		pktp->pkt_flags = un->un_tagflags;
13065 		pktp->pkt_time  = un->un_cmd_timeout;
13066 		pktp->pkt_comp  = sdintr;
13067 
13068 		pktp->pkt_private = bp;
13069 		*pktpp = pktp;
13070 
13071 		SD_TRACE(SD_LOG_IO_CORE, un,
13072 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13073 
13074 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13075 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13076 #endif
13077 
13078 		mutex_enter(SD_MUTEX(un));
13079 		return (SD_PKT_ALLOC_SUCCESS);
13080 
13081 	}
13082 
13083 	/*
13084 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13085 	 * from sd_setup_rw_pkt.
13086 	 */
13087 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13088 
13089 	if (rval == SD_PKT_ALLOC_FAILURE) {
13090 		*pktpp = NULL;
13091 		/*
13092 		 * Set the driver state to RWAIT to indicate the driver
13093 		 * is waiting on resource allocations. The driver will not
13094 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13095 		 */
13096 		mutex_enter(SD_MUTEX(un));
13097 		New_state(un, SD_STATE_RWAIT);
13098 
13099 		SD_ERROR(SD_LOG_IO_CORE, un,
13100 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13101 
13102 		if ((bp->b_flags & B_ERROR) != 0) {
13103 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13104 		}
13105 		return (SD_PKT_ALLOC_FAILURE);
13106 	} else {
13107 		/*
13108 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13109 		 *
13110 		 * This should never happen.  Maybe someone messed with the
13111 		 * kernel's minphys?
13112 		 */
13113 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13114 		    "Request rejected: too large for CDB: "
13115 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13116 		SD_ERROR(SD_LOG_IO_CORE, un,
13117 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13118 		mutex_enter(SD_MUTEX(un));
13119 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13120 
13121 	}
13122 }
13123 
13124 
13125 /*
13126  *    Function: sd_destroypkt_for_buf
13127  *
13128  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13129  *
13130  *     Context: Kernel thread or interrupt context
13131  */
13132 
13133 static void
13134 sd_destroypkt_for_buf(struct buf *bp)
13135 {
13136 	ASSERT(bp != NULL);
13137 	ASSERT(SD_GET_UN(bp) != NULL);
13138 
13139 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13140 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13141 
13142 	ASSERT(SD_GET_PKTP(bp) != NULL);
13143 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13144 
13145 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13146 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13147 }
13148 
13149 /*
13150  *    Function: sd_setup_rw_pkt
13151  *
13152  * Description: Determines appropriate CDB group for the requested LBA
13153  *		and transfer length, calls scsi_init_pkt, and builds
13154  *		the CDB.  Do not use for partial DMA transfers except
13155  *		for the initial transfer since the CDB size must
13156  *		remain constant.
13157  *
13158  *     Context: Kernel thread and may be called from software interrupt
13159  *		context as part of a sdrunout callback. This function may not
13160  *		block or call routines that block
13161  */
13162 
13163 
13164 int
13165 sd_setup_rw_pkt(struct sd_lun *un,
13166     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13167     int (*callback)(caddr_t), caddr_t callback_arg,
13168     diskaddr_t lba, uint32_t blockcount)
13169 {
13170 	struct scsi_pkt *return_pktp;
13171 	union scsi_cdb *cdbp;
13172 	struct sd_cdbinfo *cp = NULL;
13173 	int i;
13174 
13175 	/*
13176 	 * See which size CDB to use, based upon the request.
13177 	 */
13178 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13179 
13180 		/*
13181 		 * Check lba and block count against sd_cdbtab limits.
13182 		 * In the partial DMA case, we have to use the same size
13183 		 * CDB for all the transfers.  Check lba + blockcount
13184 		 * against the max LBA so we know that segment of the
13185 		 * transfer can use the CDB we select.
13186 		 */
13187 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13188 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13189 
13190 			/*
13191 			 * The command will fit into the CDB type
13192 			 * specified by sd_cdbtab[i].
13193 			 */
13194 			cp = sd_cdbtab + i;
13195 
13196 			/*
13197 			 * Call scsi_init_pkt so we can fill in the
13198 			 * CDB.
13199 			 */
13200 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13201 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13202 			    flags, callback, callback_arg);
13203 
13204 			if (return_pktp != NULL) {
13205 
13206 				/*
13207 				 * Return new value of pkt
13208 				 */
13209 				*pktpp = return_pktp;
13210 
13211 				/*
13212 				 * To be safe, zero the CDB insuring there is
13213 				 * no leftover data from a previous command.
13214 				 */
13215 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13216 
13217 				/*
13218 				 * Handle partial DMA mapping
13219 				 */
13220 				if (return_pktp->pkt_resid != 0) {
13221 
13222 					/*
13223 					 * Not going to xfer as many blocks as
13224 					 * originally expected
13225 					 */
13226 					blockcount -=
13227 					    SD_BYTES2TGTBLOCKS(un,
13228 					    return_pktp->pkt_resid);
13229 				}
13230 
13231 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13232 
13233 				/*
13234 				 * Set command byte based on the CDB
13235 				 * type we matched.
13236 				 */
13237 				cdbp->scc_cmd = cp->sc_grpmask |
13238 				    ((bp->b_flags & B_READ) ?
13239 				    SCMD_READ : SCMD_WRITE);
13240 
13241 				SD_FILL_SCSI1_LUN(un, return_pktp);
13242 
13243 				/*
13244 				 * Fill in LBA and length
13245 				 */
13246 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13247 				    (cp->sc_grpcode == CDB_GROUP4) ||
13248 				    (cp->sc_grpcode == CDB_GROUP0) ||
13249 				    (cp->sc_grpcode == CDB_GROUP5));
13250 
13251 				if (cp->sc_grpcode == CDB_GROUP1) {
13252 					FORMG1ADDR(cdbp, lba);
13253 					FORMG1COUNT(cdbp, blockcount);
13254 					return (0);
13255 				} else if (cp->sc_grpcode == CDB_GROUP4) {
13256 					FORMG4LONGADDR(cdbp, lba);
13257 					FORMG4COUNT(cdbp, blockcount);
13258 					return (0);
13259 				} else if (cp->sc_grpcode == CDB_GROUP0) {
13260 					FORMG0ADDR(cdbp, lba);
13261 					FORMG0COUNT(cdbp, blockcount);
13262 					return (0);
13263 				} else if (cp->sc_grpcode == CDB_GROUP5) {
13264 					FORMG5ADDR(cdbp, lba);
13265 					FORMG5COUNT(cdbp, blockcount);
13266 					return (0);
13267 				}
13268 
13269 				/*
13270 				 * It should be impossible to not match one
13271 				 * of the CDB types above, so we should never
13272 				 * reach this point.  Set the CDB command byte
13273 				 * to test-unit-ready to avoid writing
13274 				 * to somewhere we don't intend.
13275 				 */
13276 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
13277 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13278 			} else {
13279 				/*
13280 				 * Couldn't get scsi_pkt
13281 				 */
13282 				return (SD_PKT_ALLOC_FAILURE);
13283 			}
13284 		}
13285 	}
13286 
13287 	/*
13288 	 * None of the available CDB types were suitable.  This really
13289 	 * should never happen:  on a 64 bit system we support
13290 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
13291 	 * and on a 32 bit system we will refuse to bind to a device
13292 	 * larger than 2TB so addresses will never be larger than 32 bits.
13293 	 */
13294 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13295 }
13296 
13297 /*
13298  *    Function: sd_setup_next_rw_pkt
13299  *
13300  * Description: Setup packet for partial DMA transfers, except for the
13301  * 		initial transfer.  sd_setup_rw_pkt should be used for
13302  *		the initial transfer.
13303  *
13304  *     Context: Kernel thread and may be called from interrupt context.
13305  */
13306 
13307 int
13308 sd_setup_next_rw_pkt(struct sd_lun *un,
13309     struct scsi_pkt *pktp, struct buf *bp,
13310     diskaddr_t lba, uint32_t blockcount)
13311 {
13312 	uchar_t com;
13313 	union scsi_cdb *cdbp;
13314 	uchar_t cdb_group_id;
13315 
13316 	ASSERT(pktp != NULL);
13317 	ASSERT(pktp->pkt_cdbp != NULL);
13318 
13319 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
13320 	com = cdbp->scc_cmd;
13321 	cdb_group_id = CDB_GROUPID(com);
13322 
13323 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
13324 	    (cdb_group_id == CDB_GROUPID_1) ||
13325 	    (cdb_group_id == CDB_GROUPID_4) ||
13326 	    (cdb_group_id == CDB_GROUPID_5));
13327 
13328 	/*
13329 	 * Move pkt to the next portion of the xfer.
13330 	 * func is NULL_FUNC so we do not have to release
13331 	 * the disk mutex here.
13332 	 */
13333 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
13334 	    NULL_FUNC, NULL) == pktp) {
13335 		/* Success.  Handle partial DMA */
13336 		if (pktp->pkt_resid != 0) {
13337 			blockcount -=
13338 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
13339 		}
13340 
13341 		cdbp->scc_cmd = com;
13342 		SD_FILL_SCSI1_LUN(un, pktp);
13343 		if (cdb_group_id == CDB_GROUPID_1) {
13344 			FORMG1ADDR(cdbp, lba);
13345 			FORMG1COUNT(cdbp, blockcount);
13346 			return (0);
13347 		} else if (cdb_group_id == CDB_GROUPID_4) {
13348 			FORMG4LONGADDR(cdbp, lba);
13349 			FORMG4COUNT(cdbp, blockcount);
13350 			return (0);
13351 		} else if (cdb_group_id == CDB_GROUPID_0) {
13352 			FORMG0ADDR(cdbp, lba);
13353 			FORMG0COUNT(cdbp, blockcount);
13354 			return (0);
13355 		} else if (cdb_group_id == CDB_GROUPID_5) {
13356 			FORMG5ADDR(cdbp, lba);
13357 			FORMG5COUNT(cdbp, blockcount);
13358 			return (0);
13359 		}
13360 
13361 		/* Unreachable */
13362 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13363 	}
13364 
13365 	/*
13366 	 * Error setting up next portion of cmd transfer.
13367 	 * Something is definitely very wrong and this
13368 	 * should not happen.
13369 	 */
13370 	return (SD_PKT_ALLOC_FAILURE);
13371 }
13372 
13373 /*
13374  *    Function: sd_initpkt_for_uscsi
13375  *
13376  * Description: Allocate and initialize for transport a scsi_pkt struct,
13377  *		based upon the info specified in the given uscsi_cmd struct.
13378  *
13379  * Return Code: SD_PKT_ALLOC_SUCCESS
13380  *		SD_PKT_ALLOC_FAILURE
13381  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13382  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13383  *
13384  *     Context: Kernel thread and may be called from software interrupt context
13385  *		as part of a sdrunout callback. This function may not block or
13386  *		call routines that block
13387  */
13388 
13389 static int
13390 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
13391 {
13392 	struct uscsi_cmd *uscmd;
13393 	struct sd_xbuf	*xp;
13394 	struct scsi_pkt	*pktp;
13395 	struct sd_lun	*un;
13396 	uint32_t	flags = 0;
13397 
13398 	ASSERT(bp != NULL);
13399 	ASSERT(pktpp != NULL);
13400 	xp = SD_GET_XBUF(bp);
13401 	ASSERT(xp != NULL);
13402 	un = SD_GET_UN(bp);
13403 	ASSERT(un != NULL);
13404 	ASSERT(mutex_owned(SD_MUTEX(un)));
13405 
13406 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13407 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13408 	ASSERT(uscmd != NULL);
13409 
13410 	SD_TRACE(SD_LOG_IO_CORE, un,
13411 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
13412 
13413 	/*
13414 	 * Allocate the scsi_pkt for the command.
13415 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
13416 	 *	 during scsi_init_pkt time and will continue to use the
13417 	 *	 same path as long as the same scsi_pkt is used without
13418 	 *	 intervening scsi_dma_free(). Since uscsi command does
13419 	 *	 not call scsi_dmafree() before retry failed command, it
13420 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
13421 	 *	 set such that scsi_vhci can use other available path for
13422 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
13423 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
13424 	 */
13425 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
13426 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13427 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13428 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
13429 		    - sizeof (struct scsi_extended_sense)), 0,
13430 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
13431 		    sdrunout, (caddr_t)un);
13432 	} else {
13433 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13434 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13435 		    sizeof (struct scsi_arq_status), 0,
13436 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
13437 		    sdrunout, (caddr_t)un);
13438 	}
13439 
13440 	if (pktp == NULL) {
13441 		*pktpp = NULL;
13442 		/*
13443 		 * Set the driver state to RWAIT to indicate the driver
13444 		 * is waiting on resource allocations. The driver will not
13445 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13446 		 */
13447 		New_state(un, SD_STATE_RWAIT);
13448 
13449 		SD_ERROR(SD_LOG_IO_CORE, un,
13450 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
13451 
13452 		if ((bp->b_flags & B_ERROR) != 0) {
13453 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13454 		}
13455 		return (SD_PKT_ALLOC_FAILURE);
13456 	}
13457 
13458 	/*
13459 	 * We do not do DMA breakup for USCSI commands, so return failure
13460 	 * here if all the needed DMA resources were not allocated.
13461 	 */
13462 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
13463 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
13464 		scsi_destroy_pkt(pktp);
13465 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
13466 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
13467 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
13468 	}
13469 
13470 	/* Init the cdb from the given uscsi struct */
13471 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
13472 	    uscmd->uscsi_cdb[0], 0, 0, 0);
13473 
13474 	SD_FILL_SCSI1_LUN(un, pktp);
13475 
13476 	/*
13477 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
13478 	 * for listing of the supported flags.
13479 	 */
13480 
13481 	if (uscmd->uscsi_flags & USCSI_SILENT) {
13482 		flags |= FLAG_SILENT;
13483 	}
13484 
13485 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
13486 		flags |= FLAG_DIAGNOSE;
13487 	}
13488 
13489 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
13490 		flags |= FLAG_ISOLATE;
13491 	}
13492 
13493 	if (un->un_f_is_fibre == FALSE) {
13494 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
13495 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
13496 		}
13497 	}
13498 
13499 	/*
13500 	 * Set the pkt flags here so we save time later.
13501 	 * Note: These flags are NOT in the uscsi man page!!!
13502 	 */
13503 	if (uscmd->uscsi_flags & USCSI_HEAD) {
13504 		flags |= FLAG_HEAD;
13505 	}
13506 
13507 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
13508 		flags |= FLAG_NOINTR;
13509 	}
13510 
13511 	/*
13512 	 * For tagged queueing, things get a bit complicated.
13513 	 * Check first for head of queue and last for ordered queue.
13514 	 * If neither head nor order, use the default driver tag flags.
13515 	 */
13516 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
13517 		if (uscmd->uscsi_flags & USCSI_HTAG) {
13518 			flags |= FLAG_HTAG;
13519 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
13520 			flags |= FLAG_OTAG;
13521 		} else {
13522 			flags |= un->un_tagflags & FLAG_TAGMASK;
13523 		}
13524 	}
13525 
13526 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
13527 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
13528 	}
13529 
13530 	pktp->pkt_flags = flags;
13531 
13532 	/* Transfer uscsi information to scsi_pkt */
13533 	(void) scsi_uscsi_pktinit(uscmd, pktp);
13534 
13535 	/* Copy the caller's CDB into the pkt... */
13536 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
13537 
13538 	if (uscmd->uscsi_timeout == 0) {
13539 		pktp->pkt_time = un->un_uscsi_timeout;
13540 	} else {
13541 		pktp->pkt_time = uscmd->uscsi_timeout;
13542 	}
13543 
13544 	/* need it later to identify USCSI request in sdintr */
13545 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
13546 
13547 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
13548 
13549 	pktp->pkt_private = bp;
13550 	pktp->pkt_comp = sdintr;
13551 	*pktpp = pktp;
13552 
13553 	SD_TRACE(SD_LOG_IO_CORE, un,
13554 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
13555 
13556 	return (SD_PKT_ALLOC_SUCCESS);
13557 }
13558 
13559 
13560 /*
13561  *    Function: sd_destroypkt_for_uscsi
13562  *
13563  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
13564  *		IOs.. Also saves relevant info into the associated uscsi_cmd
13565  *		struct.
13566  *
13567  *     Context: May be called under interrupt context
13568  */
13569 
13570 static void
13571 sd_destroypkt_for_uscsi(struct buf *bp)
13572 {
13573 	struct uscsi_cmd *uscmd;
13574 	struct sd_xbuf	*xp;
13575 	struct scsi_pkt	*pktp;
13576 	struct sd_lun	*un;
13577 	struct sd_uscsi_info *suip;
13578 
13579 	ASSERT(bp != NULL);
13580 	xp = SD_GET_XBUF(bp);
13581 	ASSERT(xp != NULL);
13582 	un = SD_GET_UN(bp);
13583 	ASSERT(un != NULL);
13584 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13585 	pktp = SD_GET_PKTP(bp);
13586 	ASSERT(pktp != NULL);
13587 
13588 	SD_TRACE(SD_LOG_IO_CORE, un,
13589 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
13590 
13591 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13592 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13593 	ASSERT(uscmd != NULL);
13594 
13595 	/* Save the status and the residual into the uscsi_cmd struct */
13596 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
13597 	uscmd->uscsi_resid  = bp->b_resid;
13598 
13599 	/* Transfer scsi_pkt information to uscsi */
13600 	(void) scsi_uscsi_pktfini(pktp, uscmd);
13601 
13602 	/*
13603 	 * If enabled, copy any saved sense data into the area specified
13604 	 * by the uscsi command.
13605 	 */
13606 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
13607 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
13608 		/*
13609 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
13610 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
13611 		 */
13612 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
13613 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
13614 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
13615 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
13616 			    MAX_SENSE_LENGTH);
13617 		} else {
13618 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
13619 			    SENSE_LENGTH);
13620 		}
13621 	}
13622 	/*
13623 	 * The following assignments are for SCSI FMA.
13624 	 */
13625 	ASSERT(xp->xb_private != NULL);
13626 	suip = (struct sd_uscsi_info *)xp->xb_private;
13627 	suip->ui_pkt_reason = pktp->pkt_reason;
13628 	suip->ui_pkt_state = pktp->pkt_state;
13629 	suip->ui_pkt_statistics = pktp->pkt_statistics;
13630 	suip->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
13631 
13632 	/* We are done with the scsi_pkt; free it now */
13633 	ASSERT(SD_GET_PKTP(bp) != NULL);
13634 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13635 
13636 	SD_TRACE(SD_LOG_IO_CORE, un,
13637 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
13638 }
13639 
13640 
13641 /*
13642  *    Function: sd_bioclone_alloc
13643  *
13644  * Description: Allocate a buf(9S) and init it as per the given buf
13645  *		and the various arguments.  The associated sd_xbuf
13646  *		struct is (nearly) duplicated.  The struct buf *bp
13647  *		argument is saved in new_xp->xb_private.
13648  *
13649  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
13650  *		datalen - size of data area for the shadow bp
13651  *		blkno - starting LBA
13652  *		func - function pointer for b_iodone in the shadow buf. (May
13653  *			be NULL if none.)
13654  *
13655  * Return Code: Pointer to allocates buf(9S) struct
13656  *
13657  *     Context: Can sleep.
13658  */
13659 
13660 static struct buf *
13661 sd_bioclone_alloc(struct buf *bp, size_t datalen,
13662 	daddr_t blkno, int (*func)(struct buf *))
13663 {
13664 	struct	sd_lun	*un;
13665 	struct	sd_xbuf	*xp;
13666 	struct	sd_xbuf	*new_xp;
13667 	struct	buf	*new_bp;
13668 
13669 	ASSERT(bp != NULL);
13670 	xp = SD_GET_XBUF(bp);
13671 	ASSERT(xp != NULL);
13672 	un = SD_GET_UN(bp);
13673 	ASSERT(un != NULL);
13674 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13675 
13676 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
13677 	    NULL, KM_SLEEP);
13678 
13679 	new_bp->b_lblkno	= blkno;
13680 
13681 	/*
13682 	 * Allocate an xbuf for the shadow bp and copy the contents of the
13683 	 * original xbuf into it.
13684 	 */
13685 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
13686 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
13687 
13688 	/*
13689 	 * The given bp is automatically saved in the xb_private member
13690 	 * of the new xbuf.  Callers are allowed to depend on this.
13691 	 */
13692 	new_xp->xb_private = bp;
13693 
13694 	new_bp->b_private  = new_xp;
13695 
13696 	return (new_bp);
13697 }
13698 
13699 /*
13700  *    Function: sd_shadow_buf_alloc
13701  *
13702  * Description: Allocate a buf(9S) and init it as per the given buf
13703  *		and the various arguments.  The associated sd_xbuf
13704  *		struct is (nearly) duplicated.  The struct buf *bp
13705  *		argument is saved in new_xp->xb_private.
13706  *
13707  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
13708  *		datalen - size of data area for the shadow bp
13709  *		bflags - B_READ or B_WRITE (pseudo flag)
13710  *		blkno - starting LBA
13711  *		func - function pointer for b_iodone in the shadow buf. (May
13712  *			be NULL if none.)
13713  *
13714  * Return Code: Pointer to allocates buf(9S) struct
13715  *
13716  *     Context: Can sleep.
13717  */
13718 
13719 static struct buf *
13720 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
13721 	daddr_t blkno, int (*func)(struct buf *))
13722 {
13723 	struct	sd_lun	*un;
13724 	struct	sd_xbuf	*xp;
13725 	struct	sd_xbuf	*new_xp;
13726 	struct	buf	*new_bp;
13727 
13728 	ASSERT(bp != NULL);
13729 	xp = SD_GET_XBUF(bp);
13730 	ASSERT(xp != NULL);
13731 	un = SD_GET_UN(bp);
13732 	ASSERT(un != NULL);
13733 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13734 
13735 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
13736 		bp_mapin(bp);
13737 	}
13738 
13739 	bflags &= (B_READ | B_WRITE);
13740 #if defined(__i386) || defined(__amd64)
13741 	new_bp = getrbuf(KM_SLEEP);
13742 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
13743 	new_bp->b_bcount = datalen;
13744 	new_bp->b_flags = bflags |
13745 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
13746 #else
13747 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
13748 	    datalen, bflags, SLEEP_FUNC, NULL);
13749 #endif
13750 	new_bp->av_forw	= NULL;
13751 	new_bp->av_back	= NULL;
13752 	new_bp->b_dev	= bp->b_dev;
13753 	new_bp->b_blkno	= blkno;
13754 	new_bp->b_iodone = func;
13755 	new_bp->b_edev	= bp->b_edev;
13756 	new_bp->b_resid	= 0;
13757 
13758 	/* We need to preserve the B_FAILFAST flag */
13759 	if (bp->b_flags & B_FAILFAST) {
13760 		new_bp->b_flags |= B_FAILFAST;
13761 	}
13762 
13763 	/*
13764 	 * Allocate an xbuf for the shadow bp and copy the contents of the
13765 	 * original xbuf into it.
13766 	 */
13767 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
13768 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
13769 
13770 	/* Need later to copy data between the shadow buf & original buf! */
13771 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
13772 
13773 	/*
13774 	 * The given bp is automatically saved in the xb_private member
13775 	 * of the new xbuf.  Callers are allowed to depend on this.
13776 	 */
13777 	new_xp->xb_private = bp;
13778 
13779 	new_bp->b_private  = new_xp;
13780 
13781 	return (new_bp);
13782 }
13783 
13784 /*
13785  *    Function: sd_bioclone_free
13786  *
13787  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
13788  *		in the larger than partition operation.
13789  *
13790  *     Context: May be called under interrupt context
13791  */
13792 
13793 static void
13794 sd_bioclone_free(struct buf *bp)
13795 {
13796 	struct sd_xbuf	*xp;
13797 
13798 	ASSERT(bp != NULL);
13799 	xp = SD_GET_XBUF(bp);
13800 	ASSERT(xp != NULL);
13801 
13802 	/*
13803 	 * Call bp_mapout() before freeing the buf,  in case a lower
13804 	 * layer or HBA  had done a bp_mapin().  we must do this here
13805 	 * as we are the "originator" of the shadow buf.
13806 	 */
13807 	bp_mapout(bp);
13808 
13809 	/*
13810 	 * Null out b_iodone before freeing the bp, to ensure that the driver
13811 	 * never gets confused by a stale value in this field. (Just a little
13812 	 * extra defensiveness here.)
13813 	 */
13814 	bp->b_iodone = NULL;
13815 
13816 	freerbuf(bp);
13817 
13818 	kmem_free(xp, sizeof (struct sd_xbuf));
13819 }
13820 
13821 /*
13822  *    Function: sd_shadow_buf_free
13823  *
13824  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
13825  *
13826  *     Context: May be called under interrupt context
13827  */
13828 
13829 static void
13830 sd_shadow_buf_free(struct buf *bp)
13831 {
13832 	struct sd_xbuf	*xp;
13833 
13834 	ASSERT(bp != NULL);
13835 	xp = SD_GET_XBUF(bp);
13836 	ASSERT(xp != NULL);
13837 
13838 #if defined(__sparc)
13839 	/*
13840 	 * Call bp_mapout() before freeing the buf,  in case a lower
13841 	 * layer or HBA  had done a bp_mapin().  we must do this here
13842 	 * as we are the "originator" of the shadow buf.
13843 	 */
13844 	bp_mapout(bp);
13845 #endif
13846 
13847 	/*
13848 	 * Null out b_iodone before freeing the bp, to ensure that the driver
13849 	 * never gets confused by a stale value in this field. (Just a little
13850 	 * extra defensiveness here.)
13851 	 */
13852 	bp->b_iodone = NULL;
13853 
13854 #if defined(__i386) || defined(__amd64)
13855 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
13856 	freerbuf(bp);
13857 #else
13858 	scsi_free_consistent_buf(bp);
13859 #endif
13860 
13861 	kmem_free(xp, sizeof (struct sd_xbuf));
13862 }
13863 
13864 
13865 /*
13866  *    Function: sd_print_transport_rejected_message
13867  *
13868  * Description: This implements the ludicrously complex rules for printing
13869  *		a "transport rejected" message.  This is to address the
13870  *		specific problem of having a flood of this error message
13871  *		produced when a failover occurs.
13872  *
13873  *     Context: Any.
13874  */
13875 
13876 static void
13877 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
13878 	int code)
13879 {
13880 	ASSERT(un != NULL);
13881 	ASSERT(mutex_owned(SD_MUTEX(un)));
13882 	ASSERT(xp != NULL);
13883 
13884 	/*
13885 	 * Print the "transport rejected" message under the following
13886 	 * conditions:
13887 	 *
13888 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
13889 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
13890 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
13891 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
13892 	 *   scsi_transport(9F) (which indicates that the target might have
13893 	 *   gone off-line).  This uses the un->un_tran_fatal_count
13894 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
13895 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
13896 	 *   from scsi_transport().
13897 	 *
13898 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
13899 	 * the preceeding cases in order for the message to be printed.
13900 	 */
13901 	if (((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) &&
13902 	    (SD_FM_LOG(un) == SD_FM_LOG_NSUP)) {
13903 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
13904 		    (code != TRAN_FATAL_ERROR) ||
13905 		    (un->un_tran_fatal_count == 1)) {
13906 			switch (code) {
13907 			case TRAN_BADPKT:
13908 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13909 				    "transport rejected bad packet\n");
13910 				break;
13911 			case TRAN_FATAL_ERROR:
13912 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13913 				    "transport rejected fatal error\n");
13914 				break;
13915 			default:
13916 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13917 				    "transport rejected (%d)\n", code);
13918 				break;
13919 			}
13920 		}
13921 	}
13922 }
13923 
13924 
13925 /*
13926  *    Function: sd_add_buf_to_waitq
13927  *
13928  * Description: Add the given buf(9S) struct to the wait queue for the
13929  *		instance.  If sorting is enabled, then the buf is added
13930  *		to the queue via an elevator sort algorithm (a la
13931  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
13932  *		If sorting is not enabled, then the buf is just added
13933  *		to the end of the wait queue.
13934  *
13935  * Return Code: void
13936  *
13937  *     Context: Does not sleep/block, therefore technically can be called
13938  *		from any context.  However if sorting is enabled then the
13939  *		execution time is indeterminate, and may take long if
13940  *		the wait queue grows large.
13941  */
13942 
13943 static void
13944 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
13945 {
13946 	struct buf *ap;
13947 
13948 	ASSERT(bp != NULL);
13949 	ASSERT(un != NULL);
13950 	ASSERT(mutex_owned(SD_MUTEX(un)));
13951 
13952 	/* If the queue is empty, add the buf as the only entry & return. */
13953 	if (un->un_waitq_headp == NULL) {
13954 		ASSERT(un->un_waitq_tailp == NULL);
13955 		un->un_waitq_headp = un->un_waitq_tailp = bp;
13956 		bp->av_forw = NULL;
13957 		return;
13958 	}
13959 
13960 	ASSERT(un->un_waitq_tailp != NULL);
13961 
13962 	/*
13963 	 * If sorting is disabled, just add the buf to the tail end of
13964 	 * the wait queue and return.
13965 	 */
13966 	if (un->un_f_disksort_disabled) {
13967 		un->un_waitq_tailp->av_forw = bp;
13968 		un->un_waitq_tailp = bp;
13969 		bp->av_forw = NULL;
13970 		return;
13971 	}
13972 
13973 	/*
13974 	 * Sort thru the list of requests currently on the wait queue
13975 	 * and add the new buf request at the appropriate position.
13976 	 *
13977 	 * The un->un_waitq_headp is an activity chain pointer on which
13978 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
13979 	 * first queue holds those requests which are positioned after
13980 	 * the current SD_GET_BLKNO() (in the first request); the second holds
13981 	 * requests which came in after their SD_GET_BLKNO() number was passed.
13982 	 * Thus we implement a one way scan, retracting after reaching
13983 	 * the end of the drive to the first request on the second
13984 	 * queue, at which time it becomes the first queue.
13985 	 * A one-way scan is natural because of the way UNIX read-ahead
13986 	 * blocks are allocated.
13987 	 *
13988 	 * If we lie after the first request, then we must locate the
13989 	 * second request list and add ourselves to it.
13990 	 */
13991 	ap = un->un_waitq_headp;
13992 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
13993 		while (ap->av_forw != NULL) {
13994 			/*
13995 			 * Look for an "inversion" in the (normally
13996 			 * ascending) block numbers. This indicates
13997 			 * the start of the second request list.
13998 			 */
13999 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14000 				/*
14001 				 * Search the second request list for the
14002 				 * first request at a larger block number.
14003 				 * We go before that; however if there is
14004 				 * no such request, we go at the end.
14005 				 */
14006 				do {
14007 					if (SD_GET_BLKNO(bp) <
14008 					    SD_GET_BLKNO(ap->av_forw)) {
14009 						goto insert;
14010 					}
14011 					ap = ap->av_forw;
14012 				} while (ap->av_forw != NULL);
14013 				goto insert;		/* after last */
14014 			}
14015 			ap = ap->av_forw;
14016 		}
14017 
14018 		/*
14019 		 * No inversions... we will go after the last, and
14020 		 * be the first request in the second request list.
14021 		 */
14022 		goto insert;
14023 	}
14024 
14025 	/*
14026 	 * Request is at/after the current request...
14027 	 * sort in the first request list.
14028 	 */
14029 	while (ap->av_forw != NULL) {
14030 		/*
14031 		 * We want to go after the current request (1) if
14032 		 * there is an inversion after it (i.e. it is the end
14033 		 * of the first request list), or (2) if the next
14034 		 * request is a larger block no. than our request.
14035 		 */
14036 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14037 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14038 			goto insert;
14039 		}
14040 		ap = ap->av_forw;
14041 	}
14042 
14043 	/*
14044 	 * Neither a second list nor a larger request, therefore
14045 	 * we go at the end of the first list (which is the same
14046 	 * as the end of the whole schebang).
14047 	 */
14048 insert:
14049 	bp->av_forw = ap->av_forw;
14050 	ap->av_forw = bp;
14051 
14052 	/*
14053 	 * If we inserted onto the tail end of the waitq, make sure the
14054 	 * tail pointer is updated.
14055 	 */
14056 	if (ap == un->un_waitq_tailp) {
14057 		un->un_waitq_tailp = bp;
14058 	}
14059 }
14060 
14061 
14062 /*
14063  *    Function: sd_start_cmds
14064  *
14065  * Description: Remove and transport cmds from the driver queues.
14066  *
14067  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14068  *
14069  *		immed_bp - ptr to a buf to be transported immediately. Only
14070  *		the immed_bp is transported; bufs on the waitq are not
14071  *		processed and the un_retry_bp is not checked.  If immed_bp is
14072  *		NULL, then normal queue processing is performed.
14073  *
14074  *     Context: May be called from kernel thread context, interrupt context,
14075  *		or runout callback context. This function may not block or
14076  *		call routines that block.
14077  */
14078 
14079 static void
14080 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14081 {
14082 	struct	sd_xbuf	*xp;
14083 	struct	buf	*bp;
14084 	void	(*statp)(kstat_io_t *);
14085 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14086 	void	(*saved_statp)(kstat_io_t *);
14087 #endif
14088 	int	rval;
14089 	struct sd_fm_internal *sfip = NULL;
14090 
14091 	ASSERT(un != NULL);
14092 	ASSERT(mutex_owned(SD_MUTEX(un)));
14093 	ASSERT(un->un_ncmds_in_transport >= 0);
14094 	ASSERT(un->un_throttle >= 0);
14095 
14096 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14097 
14098 	do {
14099 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14100 		saved_statp = NULL;
14101 #endif
14102 
14103 		/*
14104 		 * If we are syncing or dumping, fail the command to
14105 		 * avoid recursively calling back into scsi_transport().
14106 		 * The dump I/O itself uses a separate code path so this
14107 		 * only prevents non-dump I/O from being sent while dumping.
14108 		 * File system sync takes place before dumping begins.
14109 		 * During panic, filesystem I/O is allowed provided
14110 		 * un_in_callback is <= 1.  This is to prevent recursion
14111 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14112 		 * sd_start_cmds and so on.  See panic.c for more information
14113 		 * about the states the system can be in during panic.
14114 		 */
14115 		if ((un->un_state == SD_STATE_DUMPING) ||
14116 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14117 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14118 			    "sd_start_cmds: panicking\n");
14119 			goto exit;
14120 		}
14121 
14122 		if ((bp = immed_bp) != NULL) {
14123 			/*
14124 			 * We have a bp that must be transported immediately.
14125 			 * It's OK to transport the immed_bp here without doing
14126 			 * the throttle limit check because the immed_bp is
14127 			 * always used in a retry/recovery case. This means
14128 			 * that we know we are not at the throttle limit by
14129 			 * virtue of the fact that to get here we must have
14130 			 * already gotten a command back via sdintr(). This also
14131 			 * relies on (1) the command on un_retry_bp preventing
14132 			 * further commands from the waitq from being issued;
14133 			 * and (2) the code in sd_retry_command checking the
14134 			 * throttle limit before issuing a delayed or immediate
14135 			 * retry. This holds even if the throttle limit is
14136 			 * currently ratcheted down from its maximum value.
14137 			 */
14138 			statp = kstat_runq_enter;
14139 			if (bp == un->un_retry_bp) {
14140 				ASSERT((un->un_retry_statp == NULL) ||
14141 				    (un->un_retry_statp == kstat_waitq_enter) ||
14142 				    (un->un_retry_statp ==
14143 				    kstat_runq_back_to_waitq));
14144 				/*
14145 				 * If the waitq kstat was incremented when
14146 				 * sd_set_retry_bp() queued this bp for a retry,
14147 				 * then we must set up statp so that the waitq
14148 				 * count will get decremented correctly below.
14149 				 * Also we must clear un->un_retry_statp to
14150 				 * ensure that we do not act on a stale value
14151 				 * in this field.
14152 				 */
14153 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14154 				    (un->un_retry_statp ==
14155 				    kstat_runq_back_to_waitq)) {
14156 					statp = kstat_waitq_to_runq;
14157 				}
14158 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14159 				saved_statp = un->un_retry_statp;
14160 #endif
14161 				un->un_retry_statp = NULL;
14162 
14163 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14164 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14165 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14166 				    un, un->un_retry_bp, un->un_throttle,
14167 				    un->un_ncmds_in_transport);
14168 			} else {
14169 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14170 				    "processing priority bp:0x%p\n", bp);
14171 			}
14172 
14173 		} else if ((bp = un->un_waitq_headp) != NULL) {
14174 			/*
14175 			 * A command on the waitq is ready to go, but do not
14176 			 * send it if:
14177 			 *
14178 			 * (1) the throttle limit has been reached, or
14179 			 * (2) a retry is pending, or
14180 			 * (3) a START_STOP_UNIT callback pending, or
14181 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14182 			 *	command is pending.
14183 			 *
14184 			 * For all of these conditions, IO processing will
14185 			 * restart after the condition is cleared.
14186 			 */
14187 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14188 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14189 				    "sd_start_cmds: exiting, "
14190 				    "throttle limit reached!\n");
14191 				goto exit;
14192 			}
14193 			if (un->un_retry_bp != NULL) {
14194 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14195 				    "sd_start_cmds: exiting, retry pending!\n");
14196 				goto exit;
14197 			}
14198 			if (un->un_startstop_timeid != NULL) {
14199 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14200 				    "sd_start_cmds: exiting, "
14201 				    "START_STOP pending!\n");
14202 				goto exit;
14203 			}
14204 			if (un->un_direct_priority_timeid != NULL) {
14205 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14206 				    "sd_start_cmds: exiting, "
14207 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14208 				goto exit;
14209 			}
14210 
14211 			/* Dequeue the command */
14212 			un->un_waitq_headp = bp->av_forw;
14213 			if (un->un_waitq_headp == NULL) {
14214 				un->un_waitq_tailp = NULL;
14215 			}
14216 			bp->av_forw = NULL;
14217 			statp = kstat_waitq_to_runq;
14218 			SD_TRACE(SD_LOG_IO_CORE, un,
14219 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14220 
14221 		} else {
14222 			/* No work to do so bail out now */
14223 			SD_TRACE(SD_LOG_IO_CORE, un,
14224 			    "sd_start_cmds: no more work, exiting!\n");
14225 			goto exit;
14226 		}
14227 
14228 		/*
14229 		 * Reset the state to normal. This is the mechanism by which
14230 		 * the state transitions from either SD_STATE_RWAIT or
14231 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14232 		 * If state is SD_STATE_PM_CHANGING then this command is
14233 		 * part of the device power control and the state must
14234 		 * not be put back to normal. Doing so would would
14235 		 * allow new commands to proceed when they shouldn't,
14236 		 * the device may be going off.
14237 		 */
14238 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14239 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14240 			New_state(un, SD_STATE_NORMAL);
14241 		}
14242 
14243 		xp = SD_GET_XBUF(bp);
14244 		ASSERT(xp != NULL);
14245 
14246 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14247 		/*
14248 		 * Allocate the scsi_pkt if we need one, or attach DMA
14249 		 * resources if we have a scsi_pkt that needs them. The
14250 		 * latter should only occur for commands that are being
14251 		 * retried.
14252 		 */
14253 		if ((xp->xb_pktp == NULL) ||
14254 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
14255 #else
14256 		if (xp->xb_pktp == NULL) {
14257 #endif
14258 			/*
14259 			 * There is no scsi_pkt allocated for this buf. Call
14260 			 * the initpkt function to allocate & init one.
14261 			 *
14262 			 * The scsi_init_pkt runout callback functionality is
14263 			 * implemented as follows:
14264 			 *
14265 			 * 1) The initpkt function always calls
14266 			 *    scsi_init_pkt(9F) with sdrunout specified as the
14267 			 *    callback routine.
14268 			 * 2) A successful packet allocation is initialized and
14269 			 *    the I/O is transported.
14270 			 * 3) The I/O associated with an allocation resource
14271 			 *    failure is left on its queue to be retried via
14272 			 *    runout or the next I/O.
14273 			 * 4) The I/O associated with a DMA error is removed
14274 			 *    from the queue and failed with EIO. Processing of
14275 			 *    the transport queues is also halted to be
14276 			 *    restarted via runout or the next I/O.
14277 			 * 5) The I/O associated with a CDB size or packet
14278 			 *    size error is removed from the queue and failed
14279 			 *    with EIO. Processing of the transport queues is
14280 			 *    continued.
14281 			 *
14282 			 * Note: there is no interface for canceling a runout
14283 			 * callback. To prevent the driver from detaching or
14284 			 * suspending while a runout is pending the driver
14285 			 * state is set to SD_STATE_RWAIT
14286 			 *
14287 			 * Note: using the scsi_init_pkt callback facility can
14288 			 * result in an I/O request persisting at the head of
14289 			 * the list which cannot be satisfied even after
14290 			 * multiple retries. In the future the driver may
14291 			 * implement some kind of maximum runout count before
14292 			 * failing an I/O.
14293 			 *
14294 			 * Note: the use of funcp below may seem superfluous,
14295 			 * but it helps warlock figure out the correct
14296 			 * initpkt function calls (see [s]sd.wlcmd).
14297 			 */
14298 			struct scsi_pkt	*pktp;
14299 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
14300 
14301 			ASSERT(bp != un->un_rqs_bp);
14302 
14303 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
14304 			switch ((*funcp)(bp, &pktp)) {
14305 			case  SD_PKT_ALLOC_SUCCESS:
14306 				xp->xb_pktp = pktp;
14307 				SD_TRACE(SD_LOG_IO_CORE, un,
14308 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
14309 				    pktp);
14310 				goto got_pkt;
14311 
14312 			case SD_PKT_ALLOC_FAILURE:
14313 				/*
14314 				 * Temporary (hopefully) resource depletion.
14315 				 * Since retries and RQS commands always have a
14316 				 * scsi_pkt allocated, these cases should never
14317 				 * get here. So the only cases this needs to
14318 				 * handle is a bp from the waitq (which we put
14319 				 * back onto the waitq for sdrunout), or a bp
14320 				 * sent as an immed_bp (which we just fail).
14321 				 */
14322 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14323 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
14324 
14325 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14326 
14327 				if (bp == immed_bp) {
14328 					/*
14329 					 * If SD_XB_DMA_FREED is clear, then
14330 					 * this is a failure to allocate a
14331 					 * scsi_pkt, and we must fail the
14332 					 * command.
14333 					 */
14334 					if ((xp->xb_pkt_flags &
14335 					    SD_XB_DMA_FREED) == 0) {
14336 						break;
14337 					}
14338 
14339 					/*
14340 					 * If this immediate command is NOT our
14341 					 * un_retry_bp, then we must fail it.
14342 					 */
14343 					if (bp != un->un_retry_bp) {
14344 						break;
14345 					}
14346 
14347 					/*
14348 					 * We get here if this cmd is our
14349 					 * un_retry_bp that was DMAFREED, but
14350 					 * scsi_init_pkt() failed to reallocate
14351 					 * DMA resources when we attempted to
14352 					 * retry it. This can happen when an
14353 					 * mpxio failover is in progress, but
14354 					 * we don't want to just fail the
14355 					 * command in this case.
14356 					 *
14357 					 * Use timeout(9F) to restart it after
14358 					 * a 100ms delay.  We don't want to
14359 					 * let sdrunout() restart it, because
14360 					 * sdrunout() is just supposed to start
14361 					 * commands that are sitting on the
14362 					 * wait queue.  The un_retry_bp stays
14363 					 * set until the command completes, but
14364 					 * sdrunout can be called many times
14365 					 * before that happens.  Since sdrunout
14366 					 * cannot tell if the un_retry_bp is
14367 					 * already in the transport, it could
14368 					 * end up calling scsi_transport() for
14369 					 * the un_retry_bp multiple times.
14370 					 *
14371 					 * Also: don't schedule the callback
14372 					 * if some other callback is already
14373 					 * pending.
14374 					 */
14375 					if (un->un_retry_statp == NULL) {
14376 						/*
14377 						 * restore the kstat pointer to
14378 						 * keep kstat counts coherent
14379 						 * when we do retry the command.
14380 						 */
14381 						un->un_retry_statp =
14382 						    saved_statp;
14383 					}
14384 
14385 					if ((un->un_startstop_timeid == NULL) &&
14386 					    (un->un_retry_timeid == NULL) &&
14387 					    (un->un_direct_priority_timeid ==
14388 					    NULL)) {
14389 
14390 						un->un_retry_timeid =
14391 						    timeout(
14392 						    sd_start_retry_command,
14393 						    un, SD_RESTART_TIMEOUT);
14394 					}
14395 					goto exit;
14396 				}
14397 
14398 #else
14399 				if (bp == immed_bp) {
14400 					break;	/* Just fail the command */
14401 				}
14402 #endif
14403 
14404 				/* Add the buf back to the head of the waitq */
14405 				bp->av_forw = un->un_waitq_headp;
14406 				un->un_waitq_headp = bp;
14407 				if (un->un_waitq_tailp == NULL) {
14408 					un->un_waitq_tailp = bp;
14409 				}
14410 				goto exit;
14411 
14412 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
14413 				/*
14414 				 * HBA DMA resource failure. Fail the command
14415 				 * and continue processing of the queues.
14416 				 */
14417 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14418 				    "sd_start_cmds: "
14419 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
14420 				break;
14421 
14422 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
14423 				/*
14424 				 * Note:x86: Partial DMA mapping not supported
14425 				 * for USCSI commands, and all the needed DMA
14426 				 * resources were not allocated.
14427 				 */
14428 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14429 				    "sd_start_cmds: "
14430 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
14431 				break;
14432 
14433 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
14434 				/*
14435 				 * Note:x86: Request cannot fit into CDB based
14436 				 * on lba and len.
14437 				 */
14438 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14439 				    "sd_start_cmds: "
14440 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
14441 				break;
14442 
14443 			default:
14444 				/* Should NEVER get here! */
14445 				panic("scsi_initpkt error");
14446 				/*NOTREACHED*/
14447 			}
14448 
14449 			/*
14450 			 * Fatal error in allocating a scsi_pkt for this buf.
14451 			 * Update kstats & return the buf with an error code.
14452 			 * We must use sd_return_failed_command_no_restart() to
14453 			 * avoid a recursive call back into sd_start_cmds().
14454 			 * However this also means that we must keep processing
14455 			 * the waitq here in order to avoid stalling.
14456 			 */
14457 			if (statp == kstat_waitq_to_runq) {
14458 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
14459 			}
14460 			sd_return_failed_command_no_restart(un, bp, EIO);
14461 			if (bp == immed_bp) {
14462 				/* immed_bp is gone by now, so clear this */
14463 				immed_bp = NULL;
14464 			}
14465 			continue;
14466 		}
14467 got_pkt:
14468 		if (bp == immed_bp) {
14469 			/* goto the head of the class.... */
14470 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
14471 		}
14472 
14473 		un->un_ncmds_in_transport++;
14474 		SD_UPDATE_KSTATS(un, statp, bp);
14475 
14476 		/*
14477 		 * Call scsi_transport() to send the command to the target.
14478 		 * According to SCSA architecture, we must drop the mutex here
14479 		 * before calling scsi_transport() in order to avoid deadlock.
14480 		 * Note that the scsi_pkt's completion routine can be executed
14481 		 * (from interrupt context) even before the call to
14482 		 * scsi_transport() returns.
14483 		 */
14484 		SD_TRACE(SD_LOG_IO_CORE, un,
14485 		    "sd_start_cmds: calling scsi_transport()\n");
14486 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
14487 
14488 		mutex_exit(SD_MUTEX(un));
14489 		rval = scsi_transport(xp->xb_pktp);
14490 		mutex_enter(SD_MUTEX(un));
14491 
14492 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14493 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
14494 
14495 		switch (rval) {
14496 		case TRAN_ACCEPT:
14497 			/* Clear this with every pkt accepted by the HBA */
14498 			un->un_tran_fatal_count = 0;
14499 			break;	/* Success; try the next cmd (if any) */
14500 
14501 		case TRAN_BUSY:
14502 			un->un_ncmds_in_transport--;
14503 			ASSERT(un->un_ncmds_in_transport >= 0);
14504 
14505 			/*
14506 			 * Don't retry request sense, the sense data
14507 			 * is lost when another request is sent.
14508 			 * Free up the rqs buf and retry
14509 			 * the original failed cmd.  Update kstat.
14510 			 */
14511 			if (bp == un->un_rqs_bp) {
14512 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14513 				bp = sd_mark_rqs_idle(un, xp);
14514 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
14515 				    NULL, NULL, EIO, un->un_busy_timeout / 500,
14516 				    kstat_waitq_enter);
14517 				goto exit;
14518 			}
14519 
14520 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14521 			/*
14522 			 * Free the DMA resources for the  scsi_pkt. This will
14523 			 * allow mpxio to select another path the next time
14524 			 * we call scsi_transport() with this scsi_pkt.
14525 			 * See sdintr() for the rationalization behind this.
14526 			 */
14527 			if ((un->un_f_is_fibre == TRUE) &&
14528 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14529 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
14530 				scsi_dmafree(xp->xb_pktp);
14531 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14532 			}
14533 #endif
14534 
14535 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
14536 				/*
14537 				 * Commands that are SD_PATH_DIRECT_PRIORITY
14538 				 * are for error recovery situations. These do
14539 				 * not use the normal command waitq, so if they
14540 				 * get a TRAN_BUSY we cannot put them back onto
14541 				 * the waitq for later retry. One possible
14542 				 * problem is that there could already be some
14543 				 * other command on un_retry_bp that is waiting
14544 				 * for this one to complete, so we would be
14545 				 * deadlocked if we put this command back onto
14546 				 * the waitq for later retry (since un_retry_bp
14547 				 * must complete before the driver gets back to
14548 				 * commands on the waitq).
14549 				 *
14550 				 * To avoid deadlock we must schedule a callback
14551 				 * that will restart this command after a set
14552 				 * interval.  This should keep retrying for as
14553 				 * long as the underlying transport keeps
14554 				 * returning TRAN_BUSY (just like for other
14555 				 * commands).  Use the same timeout interval as
14556 				 * for the ordinary TRAN_BUSY retry.
14557 				 */
14558 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14559 				    "sd_start_cmds: scsi_transport() returned "
14560 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
14561 
14562 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14563 				un->un_direct_priority_timeid =
14564 				    timeout(sd_start_direct_priority_command,
14565 				    bp, un->un_busy_timeout / 500);
14566 
14567 				goto exit;
14568 			}
14569 
14570 			/*
14571 			 * For TRAN_BUSY, we want to reduce the throttle value,
14572 			 * unless we are retrying a command.
14573 			 */
14574 			if (bp != un->un_retry_bp) {
14575 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
14576 			}
14577 
14578 			/*
14579 			 * Set up the bp to be tried again 10 ms later.
14580 			 * Note:x86: Is there a timeout value in the sd_lun
14581 			 * for this condition?
14582 			 */
14583 			sd_set_retry_bp(un, bp, un->un_busy_timeout / 500,
14584 			    kstat_runq_back_to_waitq);
14585 			goto exit;
14586 
14587 		case TRAN_FATAL_ERROR:
14588 			un->un_tran_fatal_count++;
14589 			/* FALLTHRU */
14590 
14591 		case TRAN_BADPKT:
14592 		default:
14593 			un->un_ncmds_in_transport--;
14594 			ASSERT(un->un_ncmds_in_transport >= 0);
14595 
14596 			/*
14597 			 * If this is our REQUEST SENSE command with a
14598 			 * transport error, we must get back the pointers
14599 			 * to the original buf, and mark the REQUEST
14600 			 * SENSE command as "available".
14601 			 */
14602 			if (bp == un->un_rqs_bp) {
14603 				bp = sd_mark_rqs_idle(un, xp);
14604 				xp = SD_GET_XBUF(bp);
14605 			} else {
14606 				/*
14607 				 * Legacy behavior: do not update transport
14608 				 * error count for request sense commands.
14609 				 */
14610 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
14611 			}
14612 
14613 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14614 			sd_print_transport_rejected_message(un, xp, rval);
14615 
14616 			/*
14617 			 * This command will be terminated by SD driver due
14618 			 * to a fatal transport error. We should post
14619 			 * ereport.io.scsi.cmd.disk.tran with driver-assessment
14620 			 * of "fail" for any command to indicate this
14621 			 * situation.
14622 			 */
14623 			if (xp->xb_ena > 0) {
14624 				ASSERT(un->un_fm_private != NULL);
14625 				sfip = un->un_fm_private;
14626 				sfip->fm_ssc.ssc_flags |= SSC_FLAGS_TRAN_ABORT;
14627 				sd_ssc_extract_info(&sfip->fm_ssc, un,
14628 				    xp->xb_pktp, bp, xp);
14629 				sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
14630 			}
14631 
14632 			/*
14633 			 * We must use sd_return_failed_command_no_restart() to
14634 			 * avoid a recursive call back into sd_start_cmds().
14635 			 * However this also means that we must keep processing
14636 			 * the waitq here in order to avoid stalling.
14637 			 */
14638 			sd_return_failed_command_no_restart(un, bp, EIO);
14639 
14640 			/*
14641 			 * Notify any threads waiting in sd_ddi_suspend() that
14642 			 * a command completion has occurred.
14643 			 */
14644 			if (un->un_state == SD_STATE_SUSPENDED) {
14645 				cv_broadcast(&un->un_disk_busy_cv);
14646 			}
14647 
14648 			if (bp == immed_bp) {
14649 				/* immed_bp is gone by now, so clear this */
14650 				immed_bp = NULL;
14651 			}
14652 			break;
14653 		}
14654 
14655 	} while (immed_bp == NULL);
14656 
14657 exit:
14658 	ASSERT(mutex_owned(SD_MUTEX(un)));
14659 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
14660 }
14661 
14662 
14663 /*
14664  *    Function: sd_return_command
14665  *
14666  * Description: Returns a command to its originator (with or without an
14667  *		error).  Also starts commands waiting to be transported
14668  *		to the target.
14669  *
14670  *     Context: May be called from interrupt, kernel, or timeout context
14671  */
14672 
14673 static void
14674 sd_return_command(struct sd_lun *un, struct buf *bp)
14675 {
14676 	struct sd_xbuf *xp;
14677 	struct scsi_pkt *pktp;
14678 	struct sd_fm_internal *sfip;
14679 
14680 	ASSERT(bp != NULL);
14681 	ASSERT(un != NULL);
14682 	ASSERT(mutex_owned(SD_MUTEX(un)));
14683 	ASSERT(bp != un->un_rqs_bp);
14684 	xp = SD_GET_XBUF(bp);
14685 	ASSERT(xp != NULL);
14686 
14687 	pktp = SD_GET_PKTP(bp);
14688 	sfip = (struct sd_fm_internal *)un->un_fm_private;
14689 	ASSERT(sfip != NULL);
14690 
14691 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
14692 
14693 	/*
14694 	 * Note: check for the "sdrestart failed" case.
14695 	 */
14696 	if ((un->un_partial_dma_supported == 1) &&
14697 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
14698 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
14699 	    (xp->xb_pktp->pkt_resid == 0)) {
14700 
14701 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
14702 			/*
14703 			 * Successfully set up next portion of cmd
14704 			 * transfer, try sending it
14705 			 */
14706 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14707 			    NULL, NULL, 0, (clock_t)0, NULL);
14708 			sd_start_cmds(un, NULL);
14709 			return;	/* Note:x86: need a return here? */
14710 		}
14711 	}
14712 
14713 	/*
14714 	 * If this is the failfast bp, clear it from un_failfast_bp. This
14715 	 * can happen if upon being re-tried the failfast bp either
14716 	 * succeeded or encountered another error (possibly even a different
14717 	 * error than the one that precipitated the failfast state, but in
14718 	 * that case it would have had to exhaust retries as well). Regardless,
14719 	 * this should not occur whenever the instance is in the active
14720 	 * failfast state.
14721 	 */
14722 	if (bp == un->un_failfast_bp) {
14723 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
14724 		un->un_failfast_bp = NULL;
14725 	}
14726 
14727 	/*
14728 	 * Clear the failfast state upon successful completion of ANY cmd.
14729 	 */
14730 	if (bp->b_error == 0) {
14731 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
14732 		/*
14733 		 * If this is a successful command, but used to be retried,
14734 		 * we will take it as a recovered command and post an
14735 		 * ereport with driver-assessment of "recovered".
14736 		 */
14737 		if (xp->xb_ena > 0) {
14738 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
14739 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RECOVERY);
14740 		}
14741 	} else {
14742 		/*
14743 		 * If this is a failed non-USCSI command we will post an
14744 		 * ereport with driver-assessment set accordingly("fail" or
14745 		 * "fatal").
14746 		 */
14747 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
14748 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
14749 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
14750 		}
14751 	}
14752 
14753 	/*
14754 	 * This is used if the command was retried one or more times. Show that
14755 	 * we are done with it, and allow processing of the waitq to resume.
14756 	 */
14757 	if (bp == un->un_retry_bp) {
14758 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14759 		    "sd_return_command: un:0x%p: "
14760 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
14761 		un->un_retry_bp = NULL;
14762 		un->un_retry_statp = NULL;
14763 	}
14764 
14765 	SD_UPDATE_RDWR_STATS(un, bp);
14766 	SD_UPDATE_PARTITION_STATS(un, bp);
14767 
14768 	switch (un->un_state) {
14769 	case SD_STATE_SUSPENDED:
14770 		/*
14771 		 * Notify any threads waiting in sd_ddi_suspend() that
14772 		 * a command completion has occurred.
14773 		 */
14774 		cv_broadcast(&un->un_disk_busy_cv);
14775 		break;
14776 	default:
14777 		sd_start_cmds(un, NULL);
14778 		break;
14779 	}
14780 
14781 	/* Return this command up the iodone chain to its originator. */
14782 	mutex_exit(SD_MUTEX(un));
14783 
14784 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
14785 	xp->xb_pktp = NULL;
14786 
14787 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
14788 
14789 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14790 	mutex_enter(SD_MUTEX(un));
14791 
14792 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
14793 }
14794 
14795 
14796 /*
14797  *    Function: sd_return_failed_command
14798  *
14799  * Description: Command completion when an error occurred.
14800  *
14801  *     Context: May be called from interrupt context
14802  */
14803 
14804 static void
14805 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
14806 {
14807 	ASSERT(bp != NULL);
14808 	ASSERT(un != NULL);
14809 	ASSERT(mutex_owned(SD_MUTEX(un)));
14810 
14811 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14812 	    "sd_return_failed_command: entry\n");
14813 
14814 	/*
14815 	 * b_resid could already be nonzero due to a partial data
14816 	 * transfer, so do not change it here.
14817 	 */
14818 	SD_BIOERROR(bp, errcode);
14819 
14820 	sd_return_command(un, bp);
14821 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14822 	    "sd_return_failed_command: exit\n");
14823 }
14824 
14825 
14826 /*
14827  *    Function: sd_return_failed_command_no_restart
14828  *
14829  * Description: Same as sd_return_failed_command, but ensures that no
14830  *		call back into sd_start_cmds will be issued.
14831  *
14832  *     Context: May be called from interrupt context
14833  */
14834 
14835 static void
14836 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
14837 	int errcode)
14838 {
14839 	struct sd_xbuf *xp;
14840 
14841 	ASSERT(bp != NULL);
14842 	ASSERT(un != NULL);
14843 	ASSERT(mutex_owned(SD_MUTEX(un)));
14844 	xp = SD_GET_XBUF(bp);
14845 	ASSERT(xp != NULL);
14846 	ASSERT(errcode != 0);
14847 
14848 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14849 	    "sd_return_failed_command_no_restart: entry\n");
14850 
14851 	/*
14852 	 * b_resid could already be nonzero due to a partial data
14853 	 * transfer, so do not change it here.
14854 	 */
14855 	SD_BIOERROR(bp, errcode);
14856 
14857 	/*
14858 	 * If this is the failfast bp, clear it. This can happen if the
14859 	 * failfast bp encounterd a fatal error when we attempted to
14860 	 * re-try it (such as a scsi_transport(9F) failure).  However
14861 	 * we should NOT be in an active failfast state if the failfast
14862 	 * bp is not NULL.
14863 	 */
14864 	if (bp == un->un_failfast_bp) {
14865 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
14866 		un->un_failfast_bp = NULL;
14867 	}
14868 
14869 	if (bp == un->un_retry_bp) {
14870 		/*
14871 		 * This command was retried one or more times. Show that we are
14872 		 * done with it, and allow processing of the waitq to resume.
14873 		 */
14874 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14875 		    "sd_return_failed_command_no_restart: "
14876 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
14877 		un->un_retry_bp = NULL;
14878 		un->un_retry_statp = NULL;
14879 	}
14880 
14881 	SD_UPDATE_RDWR_STATS(un, bp);
14882 	SD_UPDATE_PARTITION_STATS(un, bp);
14883 
14884 	mutex_exit(SD_MUTEX(un));
14885 
14886 	if (xp->xb_pktp != NULL) {
14887 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
14888 		xp->xb_pktp = NULL;
14889 	}
14890 
14891 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
14892 
14893 	mutex_enter(SD_MUTEX(un));
14894 
14895 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14896 	    "sd_return_failed_command_no_restart: exit\n");
14897 }
14898 
14899 
14900 /*
14901  *    Function: sd_retry_command
14902  *
14903  * Description: queue up a command for retry, or (optionally) fail it
14904  *		if retry counts are exhausted.
14905  *
14906  *   Arguments: un - Pointer to the sd_lun struct for the target.
14907  *
14908  *		bp - Pointer to the buf for the command to be retried.
14909  *
14910  *		retry_check_flag - Flag to see which (if any) of the retry
14911  *		   counts should be decremented/checked. If the indicated
14912  *		   retry count is exhausted, then the command will not be
14913  *		   retried; it will be failed instead. This should use a
14914  *		   value equal to one of the following:
14915  *
14916  *			SD_RETRIES_NOCHECK
14917  *			SD_RESD_RETRIES_STANDARD
14918  *			SD_RETRIES_VICTIM
14919  *
14920  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
14921  *		   if the check should be made to see of FLAG_ISOLATE is set
14922  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
14923  *		   not retried, it is simply failed.
14924  *
14925  *		user_funcp - Ptr to function to call before dispatching the
14926  *		   command. May be NULL if no action needs to be performed.
14927  *		   (Primarily intended for printing messages.)
14928  *
14929  *		user_arg - Optional argument to be passed along to
14930  *		   the user_funcp call.
14931  *
14932  *		failure_code - errno return code to set in the bp if the
14933  *		   command is going to be failed.
14934  *
14935  *		retry_delay - Retry delay interval in (clock_t) units. May
14936  *		   be zero which indicates that the retry should be retried
14937  *		   immediately (ie, without an intervening delay).
14938  *
14939  *		statp - Ptr to kstat function to be updated if the command
14940  *		   is queued for a delayed retry. May be NULL if no kstat
14941  *		   update is desired.
14942  *
14943  *     Context: May be called from interrupt context.
14944  */
14945 
14946 static void
14947 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
14948 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
14949 	code), void *user_arg, int failure_code,  clock_t retry_delay,
14950 	void (*statp)(kstat_io_t *))
14951 {
14952 	struct sd_xbuf	*xp;
14953 	struct scsi_pkt	*pktp;
14954 	struct sd_fm_internal *sfip;
14955 
14956 	ASSERT(un != NULL);
14957 	ASSERT(mutex_owned(SD_MUTEX(un)));
14958 	ASSERT(bp != NULL);
14959 	xp = SD_GET_XBUF(bp);
14960 	ASSERT(xp != NULL);
14961 	pktp = SD_GET_PKTP(bp);
14962 	ASSERT(pktp != NULL);
14963 
14964 	sfip = (struct sd_fm_internal *)un->un_fm_private;
14965 	ASSERT(sfip != NULL);
14966 
14967 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14968 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
14969 
14970 	/*
14971 	 * If we are syncing or dumping, fail the command to avoid
14972 	 * recursively calling back into scsi_transport().
14973 	 */
14974 	if (ddi_in_panic()) {
14975 		goto fail_command_no_log;
14976 	}
14977 
14978 	/*
14979 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
14980 	 * log an error and fail the command.
14981 	 */
14982 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14983 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
14984 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
14985 		sd_dump_memory(un, SD_LOG_IO, "CDB",
14986 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
14987 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
14988 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
14989 		goto fail_command;
14990 	}
14991 
14992 	/*
14993 	 * If we are suspended, then put the command onto head of the
14994 	 * wait queue since we don't want to start more commands, and
14995 	 * clear the un_retry_bp. Next time when we are resumed, will
14996 	 * handle the command in the wait queue.
14997 	 */
14998 	switch (un->un_state) {
14999 	case SD_STATE_SUSPENDED:
15000 	case SD_STATE_DUMPING:
15001 		bp->av_forw = un->un_waitq_headp;
15002 		un->un_waitq_headp = bp;
15003 		if (un->un_waitq_tailp == NULL) {
15004 			un->un_waitq_tailp = bp;
15005 		}
15006 		if (bp == un->un_retry_bp) {
15007 			un->un_retry_bp = NULL;
15008 			un->un_retry_statp = NULL;
15009 		}
15010 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15011 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15012 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15013 		return;
15014 	default:
15015 		break;
15016 	}
15017 
15018 	/*
15019 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15020 	 * is set; if it is then we do not want to retry the command.
15021 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15022 	 */
15023 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15024 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15025 			goto fail_command;
15026 		}
15027 	}
15028 
15029 
15030 	/*
15031 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15032 	 * command timeout or a selection timeout has occurred. This means
15033 	 * that we were unable to establish an kind of communication with
15034 	 * the target, and subsequent retries and/or commands are likely
15035 	 * to encounter similar results and take a long time to complete.
15036 	 *
15037 	 * If this is a failfast error condition, we need to update the
15038 	 * failfast state, even if this bp does not have B_FAILFAST set.
15039 	 */
15040 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15041 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15042 			ASSERT(un->un_failfast_bp == NULL);
15043 			/*
15044 			 * If we are already in the active failfast state, and
15045 			 * another failfast error condition has been detected,
15046 			 * then fail this command if it has B_FAILFAST set.
15047 			 * If B_FAILFAST is clear, then maintain the legacy
15048 			 * behavior of retrying heroically, even tho this will
15049 			 * take a lot more time to fail the command.
15050 			 */
15051 			if (bp->b_flags & B_FAILFAST) {
15052 				goto fail_command;
15053 			}
15054 		} else {
15055 			/*
15056 			 * We're not in the active failfast state, but we
15057 			 * have a failfast error condition, so we must begin
15058 			 * transition to the next state. We do this regardless
15059 			 * of whether or not this bp has B_FAILFAST set.
15060 			 */
15061 			if (un->un_failfast_bp == NULL) {
15062 				/*
15063 				 * This is the first bp to meet a failfast
15064 				 * condition so save it on un_failfast_bp &
15065 				 * do normal retry processing. Do not enter
15066 				 * active failfast state yet. This marks
15067 				 * entry into the "failfast pending" state.
15068 				 */
15069 				un->un_failfast_bp = bp;
15070 
15071 			} else if (un->un_failfast_bp == bp) {
15072 				/*
15073 				 * This is the second time *this* bp has
15074 				 * encountered a failfast error condition,
15075 				 * so enter active failfast state & flush
15076 				 * queues as appropriate.
15077 				 */
15078 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15079 				un->un_failfast_bp = NULL;
15080 				sd_failfast_flushq(un);
15081 
15082 				/*
15083 				 * Fail this bp now if B_FAILFAST set;
15084 				 * otherwise continue with retries. (It would
15085 				 * be pretty ironic if this bp succeeded on a
15086 				 * subsequent retry after we just flushed all
15087 				 * the queues).
15088 				 */
15089 				if (bp->b_flags & B_FAILFAST) {
15090 					goto fail_command;
15091 				}
15092 
15093 #if !defined(lint) && !defined(__lint)
15094 			} else {
15095 				/*
15096 				 * If neither of the preceeding conditionals
15097 				 * was true, it means that there is some
15098 				 * *other* bp that has met an inital failfast
15099 				 * condition and is currently either being
15100 				 * retried or is waiting to be retried. In
15101 				 * that case we should perform normal retry
15102 				 * processing on *this* bp, since there is a
15103 				 * chance that the current failfast condition
15104 				 * is transient and recoverable. If that does
15105 				 * not turn out to be the case, then retries
15106 				 * will be cleared when the wait queue is
15107 				 * flushed anyway.
15108 				 */
15109 #endif
15110 			}
15111 		}
15112 	} else {
15113 		/*
15114 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15115 		 * likely were able to at least establish some level of
15116 		 * communication with the target and subsequent commands
15117 		 * and/or retries are likely to get through to the target,
15118 		 * In this case we want to be aggressive about clearing
15119 		 * the failfast state. Note that this does not affect
15120 		 * the "failfast pending" condition.
15121 		 */
15122 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15123 	}
15124 
15125 
15126 	/*
15127 	 * Check the specified retry count to see if we can still do
15128 	 * any retries with this pkt before we should fail it.
15129 	 */
15130 	switch (retry_check_flag & SD_RETRIES_MASK) {
15131 	case SD_RETRIES_VICTIM:
15132 		/*
15133 		 * Check the victim retry count. If exhausted, then fall
15134 		 * thru & check against the standard retry count.
15135 		 */
15136 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15137 			/* Increment count & proceed with the retry */
15138 			xp->xb_victim_retry_count++;
15139 			break;
15140 		}
15141 		/* Victim retries exhausted, fall back to std. retries... */
15142 		/* FALLTHRU */
15143 
15144 	case SD_RETRIES_STANDARD:
15145 		if (xp->xb_retry_count >= un->un_retry_count) {
15146 			/* Retries exhausted, fail the command */
15147 			SD_TRACE(SD_LOG_IO_CORE, un,
15148 			    "sd_retry_command: retries exhausted!\n");
15149 			/*
15150 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15151 			 * commands with nonzero pkt_resid.
15152 			 */
15153 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15154 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15155 			    (pktp->pkt_resid != 0)) {
15156 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15157 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15158 					SD_UPDATE_B_RESID(bp, pktp);
15159 				}
15160 			}
15161 			goto fail_command;
15162 		}
15163 		xp->xb_retry_count++;
15164 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15165 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15166 		break;
15167 
15168 	case SD_RETRIES_UA:
15169 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15170 			/* Retries exhausted, fail the command */
15171 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15172 			    "Unit Attention retries exhausted. "
15173 			    "Check the target.\n");
15174 			goto fail_command;
15175 		}
15176 		xp->xb_ua_retry_count++;
15177 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15178 		    "sd_retry_command: retry count:%d\n",
15179 		    xp->xb_ua_retry_count);
15180 		break;
15181 
15182 	case SD_RETRIES_BUSY:
15183 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15184 			/* Retries exhausted, fail the command */
15185 			SD_TRACE(SD_LOG_IO_CORE, un,
15186 			    "sd_retry_command: retries exhausted!\n");
15187 			goto fail_command;
15188 		}
15189 		xp->xb_retry_count++;
15190 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15191 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15192 		break;
15193 
15194 	case SD_RETRIES_NOCHECK:
15195 	default:
15196 		/* No retry count to check. Just proceed with the retry */
15197 		break;
15198 	}
15199 
15200 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15201 
15202 	/*
15203 	 * If this is a non-USCSI command being retried
15204 	 * during execution last time, we should post an ereport with
15205 	 * driver-assessment of the value "retry".
15206 	 * For partial DMA, request sense and STATUS_QFULL, there are no
15207 	 * hardware errors, we bypass ereport posting.
15208 	 */
15209 	if (failure_code != 0) {
15210 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15211 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15212 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RETRY);
15213 		}
15214 	}
15215 
15216 	/*
15217 	 * If we were given a zero timeout, we must attempt to retry the
15218 	 * command immediately (ie, without a delay).
15219 	 */
15220 	if (retry_delay == 0) {
15221 		/*
15222 		 * Check some limiting conditions to see if we can actually
15223 		 * do the immediate retry.  If we cannot, then we must
15224 		 * fall back to queueing up a delayed retry.
15225 		 */
15226 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15227 			/*
15228 			 * We are at the throttle limit for the target,
15229 			 * fall back to delayed retry.
15230 			 */
15231 			retry_delay = un->un_busy_timeout;
15232 			statp = kstat_waitq_enter;
15233 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15234 			    "sd_retry_command: immed. retry hit "
15235 			    "throttle!\n");
15236 		} else {
15237 			/*
15238 			 * We're clear to proceed with the immediate retry.
15239 			 * First call the user-provided function (if any)
15240 			 */
15241 			if (user_funcp != NULL) {
15242 				(*user_funcp)(un, bp, user_arg,
15243 				    SD_IMMEDIATE_RETRY_ISSUED);
15244 #ifdef __lock_lint
15245 				sd_print_incomplete_msg(un, bp, user_arg,
15246 				    SD_IMMEDIATE_RETRY_ISSUED);
15247 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15248 				    SD_IMMEDIATE_RETRY_ISSUED);
15249 				sd_print_sense_failed_msg(un, bp, user_arg,
15250 				    SD_IMMEDIATE_RETRY_ISSUED);
15251 #endif
15252 			}
15253 
15254 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15255 			    "sd_retry_command: issuing immediate retry\n");
15256 
15257 			/*
15258 			 * Call sd_start_cmds() to transport the command to
15259 			 * the target.
15260 			 */
15261 			sd_start_cmds(un, bp);
15262 
15263 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15264 			    "sd_retry_command exit\n");
15265 			return;
15266 		}
15267 	}
15268 
15269 	/*
15270 	 * Set up to retry the command after a delay.
15271 	 * First call the user-provided function (if any)
15272 	 */
15273 	if (user_funcp != NULL) {
15274 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
15275 	}
15276 
15277 	sd_set_retry_bp(un, bp, retry_delay, statp);
15278 
15279 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15280 	return;
15281 
15282 fail_command:
15283 
15284 	if (user_funcp != NULL) {
15285 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
15286 	}
15287 
15288 fail_command_no_log:
15289 
15290 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15291 	    "sd_retry_command: returning failed command\n");
15292 
15293 	sd_return_failed_command(un, bp, failure_code);
15294 
15295 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15296 }
15297 
15298 
15299 /*
15300  *    Function: sd_set_retry_bp
15301  *
15302  * Description: Set up the given bp for retry.
15303  *
15304  *   Arguments: un - ptr to associated softstate
15305  *		bp - ptr to buf(9S) for the command
15306  *		retry_delay - time interval before issuing retry (may be 0)
15307  *		statp - optional pointer to kstat function
15308  *
15309  *     Context: May be called under interrupt context
15310  */
15311 
15312 static void
15313 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
15314 	void (*statp)(kstat_io_t *))
15315 {
15316 	ASSERT(un != NULL);
15317 	ASSERT(mutex_owned(SD_MUTEX(un)));
15318 	ASSERT(bp != NULL);
15319 
15320 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15321 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
15322 
15323 	/*
15324 	 * Indicate that the command is being retried. This will not allow any
15325 	 * other commands on the wait queue to be transported to the target
15326 	 * until this command has been completed (success or failure). The
15327 	 * "retry command" is not transported to the target until the given
15328 	 * time delay expires, unless the user specified a 0 retry_delay.
15329 	 *
15330 	 * Note: the timeout(9F) callback routine is what actually calls
15331 	 * sd_start_cmds() to transport the command, with the exception of a
15332 	 * zero retry_delay. The only current implementor of a zero retry delay
15333 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
15334 	 */
15335 	if (un->un_retry_bp == NULL) {
15336 		ASSERT(un->un_retry_statp == NULL);
15337 		un->un_retry_bp = bp;
15338 
15339 		/*
15340 		 * If the user has not specified a delay the command should
15341 		 * be queued and no timeout should be scheduled.
15342 		 */
15343 		if (retry_delay == 0) {
15344 			/*
15345 			 * Save the kstat pointer that will be used in the
15346 			 * call to SD_UPDATE_KSTATS() below, so that
15347 			 * sd_start_cmds() can correctly decrement the waitq
15348 			 * count when it is time to transport this command.
15349 			 */
15350 			un->un_retry_statp = statp;
15351 			goto done;
15352 		}
15353 	}
15354 
15355 	if (un->un_retry_bp == bp) {
15356 		/*
15357 		 * Save the kstat pointer that will be used in the call to
15358 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
15359 		 * correctly decrement the waitq count when it is time to
15360 		 * transport this command.
15361 		 */
15362 		un->un_retry_statp = statp;
15363 
15364 		/*
15365 		 * Schedule a timeout if:
15366 		 *   1) The user has specified a delay.
15367 		 *   2) There is not a START_STOP_UNIT callback pending.
15368 		 *
15369 		 * If no delay has been specified, then it is up to the caller
15370 		 * to ensure that IO processing continues without stalling.
15371 		 * Effectively, this means that the caller will issue the
15372 		 * required call to sd_start_cmds(). The START_STOP_UNIT
15373 		 * callback does this after the START STOP UNIT command has
15374 		 * completed. In either of these cases we should not schedule
15375 		 * a timeout callback here.  Also don't schedule the timeout if
15376 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
15377 		 */
15378 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
15379 		    (un->un_direct_priority_timeid == NULL)) {
15380 			un->un_retry_timeid =
15381 			    timeout(sd_start_retry_command, un, retry_delay);
15382 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15383 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
15384 			    " bp:0x%p un_retry_timeid:0x%p\n",
15385 			    un, bp, un->un_retry_timeid);
15386 		}
15387 	} else {
15388 		/*
15389 		 * We only get in here if there is already another command
15390 		 * waiting to be retried.  In this case, we just put the
15391 		 * given command onto the wait queue, so it can be transported
15392 		 * after the current retry command has completed.
15393 		 *
15394 		 * Also we have to make sure that if the command at the head
15395 		 * of the wait queue is the un_failfast_bp, that we do not
15396 		 * put ahead of it any other commands that are to be retried.
15397 		 */
15398 		if ((un->un_failfast_bp != NULL) &&
15399 		    (un->un_failfast_bp == un->un_waitq_headp)) {
15400 			/*
15401 			 * Enqueue this command AFTER the first command on
15402 			 * the wait queue (which is also un_failfast_bp).
15403 			 */
15404 			bp->av_forw = un->un_waitq_headp->av_forw;
15405 			un->un_waitq_headp->av_forw = bp;
15406 			if (un->un_waitq_headp == un->un_waitq_tailp) {
15407 				un->un_waitq_tailp = bp;
15408 			}
15409 		} else {
15410 			/* Enqueue this command at the head of the waitq. */
15411 			bp->av_forw = un->un_waitq_headp;
15412 			un->un_waitq_headp = bp;
15413 			if (un->un_waitq_tailp == NULL) {
15414 				un->un_waitq_tailp = bp;
15415 			}
15416 		}
15417 
15418 		if (statp == NULL) {
15419 			statp = kstat_waitq_enter;
15420 		}
15421 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15422 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
15423 	}
15424 
15425 done:
15426 	if (statp != NULL) {
15427 		SD_UPDATE_KSTATS(un, statp, bp);
15428 	}
15429 
15430 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15431 	    "sd_set_retry_bp: exit un:0x%p\n", un);
15432 }
15433 
15434 
15435 /*
15436  *    Function: sd_start_retry_command
15437  *
15438  * Description: Start the command that has been waiting on the target's
15439  *		retry queue.  Called from timeout(9F) context after the
15440  *		retry delay interval has expired.
15441  *
15442  *   Arguments: arg - pointer to associated softstate for the device.
15443  *
15444  *     Context: timeout(9F) thread context.  May not sleep.
15445  */
15446 
15447 static void
15448 sd_start_retry_command(void *arg)
15449 {
15450 	struct sd_lun *un = arg;
15451 
15452 	ASSERT(un != NULL);
15453 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15454 
15455 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15456 	    "sd_start_retry_command: entry\n");
15457 
15458 	mutex_enter(SD_MUTEX(un));
15459 
15460 	un->un_retry_timeid = NULL;
15461 
15462 	if (un->un_retry_bp != NULL) {
15463 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15464 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
15465 		    un, un->un_retry_bp);
15466 		sd_start_cmds(un, un->un_retry_bp);
15467 	}
15468 
15469 	mutex_exit(SD_MUTEX(un));
15470 
15471 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15472 	    "sd_start_retry_command: exit\n");
15473 }
15474 
15475 
15476 /*
15477  *    Function: sd_start_direct_priority_command
15478  *
15479  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
15480  *		received TRAN_BUSY when we called scsi_transport() to send it
15481  *		to the underlying HBA. This function is called from timeout(9F)
15482  *		context after the delay interval has expired.
15483  *
15484  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
15485  *
15486  *     Context: timeout(9F) thread context.  May not sleep.
15487  */
15488 
15489 static void
15490 sd_start_direct_priority_command(void *arg)
15491 {
15492 	struct buf	*priority_bp = arg;
15493 	struct sd_lun	*un;
15494 
15495 	ASSERT(priority_bp != NULL);
15496 	un = SD_GET_UN(priority_bp);
15497 	ASSERT(un != NULL);
15498 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15499 
15500 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15501 	    "sd_start_direct_priority_command: entry\n");
15502 
15503 	mutex_enter(SD_MUTEX(un));
15504 	un->un_direct_priority_timeid = NULL;
15505 	sd_start_cmds(un, priority_bp);
15506 	mutex_exit(SD_MUTEX(un));
15507 
15508 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15509 	    "sd_start_direct_priority_command: exit\n");
15510 }
15511 
15512 
15513 /*
15514  *    Function: sd_send_request_sense_command
15515  *
15516  * Description: Sends a REQUEST SENSE command to the target
15517  *
15518  *     Context: May be called from interrupt context.
15519  */
15520 
15521 static void
15522 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
15523 	struct scsi_pkt *pktp)
15524 {
15525 	ASSERT(bp != NULL);
15526 	ASSERT(un != NULL);
15527 	ASSERT(mutex_owned(SD_MUTEX(un)));
15528 
15529 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
15530 	    "entry: buf:0x%p\n", bp);
15531 
15532 	/*
15533 	 * If we are syncing or dumping, then fail the command to avoid a
15534 	 * recursive callback into scsi_transport(). Also fail the command
15535 	 * if we are suspended (legacy behavior).
15536 	 */
15537 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
15538 	    (un->un_state == SD_STATE_DUMPING)) {
15539 		sd_return_failed_command(un, bp, EIO);
15540 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15541 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
15542 		return;
15543 	}
15544 
15545 	/*
15546 	 * Retry the failed command and don't issue the request sense if:
15547 	 *    1) the sense buf is busy
15548 	 *    2) we have 1 or more outstanding commands on the target
15549 	 *    (the sense data will be cleared or invalidated any way)
15550 	 *
15551 	 * Note: There could be an issue with not checking a retry limit here,
15552 	 * the problem is determining which retry limit to check.
15553 	 */
15554 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
15555 		/* Don't retry if the command is flagged as non-retryable */
15556 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15557 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15558 			    NULL, NULL, 0, un->un_busy_timeout,
15559 			    kstat_waitq_enter);
15560 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15561 			    "sd_send_request_sense_command: "
15562 			    "at full throttle, retrying exit\n");
15563 		} else {
15564 			sd_return_failed_command(un, bp, EIO);
15565 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15566 			    "sd_send_request_sense_command: "
15567 			    "at full throttle, non-retryable exit\n");
15568 		}
15569 		return;
15570 	}
15571 
15572 	sd_mark_rqs_busy(un, bp);
15573 	sd_start_cmds(un, un->un_rqs_bp);
15574 
15575 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15576 	    "sd_send_request_sense_command: exit\n");
15577 }
15578 
15579 
15580 /*
15581  *    Function: sd_mark_rqs_busy
15582  *
15583  * Description: Indicate that the request sense bp for this instance is
15584  *		in use.
15585  *
15586  *     Context: May be called under interrupt context
15587  */
15588 
15589 static void
15590 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
15591 {
15592 	struct sd_xbuf	*sense_xp;
15593 
15594 	ASSERT(un != NULL);
15595 	ASSERT(bp != NULL);
15596 	ASSERT(mutex_owned(SD_MUTEX(un)));
15597 	ASSERT(un->un_sense_isbusy == 0);
15598 
15599 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
15600 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
15601 
15602 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
15603 	ASSERT(sense_xp != NULL);
15604 
15605 	SD_INFO(SD_LOG_IO, un,
15606 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
15607 
15608 	ASSERT(sense_xp->xb_pktp != NULL);
15609 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
15610 	    == (FLAG_SENSING | FLAG_HEAD));
15611 
15612 	un->un_sense_isbusy = 1;
15613 	un->un_rqs_bp->b_resid = 0;
15614 	sense_xp->xb_pktp->pkt_resid  = 0;
15615 	sense_xp->xb_pktp->pkt_reason = 0;
15616 
15617 	/* So we can get back the bp at interrupt time! */
15618 	sense_xp->xb_sense_bp = bp;
15619 
15620 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
15621 
15622 	/*
15623 	 * Mark this buf as awaiting sense data. (This is already set in
15624 	 * the pkt_flags for the RQS packet.)
15625 	 */
15626 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
15627 
15628 	/* Request sense down same path */
15629 	if (scsi_pkt_allocated_correctly((SD_GET_XBUF(bp))->xb_pktp) &&
15630 	    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance)
15631 		sense_xp->xb_pktp->pkt_path_instance =
15632 		    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance;
15633 
15634 	sense_xp->xb_retry_count	= 0;
15635 	sense_xp->xb_victim_retry_count = 0;
15636 	sense_xp->xb_ua_retry_count	= 0;
15637 	sense_xp->xb_nr_retry_count 	= 0;
15638 	sense_xp->xb_dma_resid  = 0;
15639 
15640 	/* Clean up the fields for auto-request sense */
15641 	sense_xp->xb_sense_status = 0;
15642 	sense_xp->xb_sense_state  = 0;
15643 	sense_xp->xb_sense_resid  = 0;
15644 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
15645 
15646 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
15647 }
15648 
15649 
15650 /*
15651  *    Function: sd_mark_rqs_idle
15652  *
15653  * Description: SD_MUTEX must be held continuously through this routine
15654  *		to prevent reuse of the rqs struct before the caller can
15655  *		complete it's processing.
15656  *
15657  * Return Code: Pointer to the RQS buf
15658  *
15659  *     Context: May be called under interrupt context
15660  */
15661 
15662 static struct buf *
15663 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
15664 {
15665 	struct buf *bp;
15666 	ASSERT(un != NULL);
15667 	ASSERT(sense_xp != NULL);
15668 	ASSERT(mutex_owned(SD_MUTEX(un)));
15669 	ASSERT(un->un_sense_isbusy != 0);
15670 
15671 	un->un_sense_isbusy = 0;
15672 	bp = sense_xp->xb_sense_bp;
15673 	sense_xp->xb_sense_bp = NULL;
15674 
15675 	/* This pkt is no longer interested in getting sense data */
15676 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
15677 
15678 	return (bp);
15679 }
15680 
15681 
15682 
15683 /*
15684  *    Function: sd_alloc_rqs
15685  *
15686  * Description: Set up the unit to receive auto request sense data
15687  *
15688  * Return Code: DDI_SUCCESS or DDI_FAILURE
15689  *
15690  *     Context: Called under attach(9E) context
15691  */
15692 
15693 static int
15694 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
15695 {
15696 	struct sd_xbuf *xp;
15697 
15698 	ASSERT(un != NULL);
15699 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15700 	ASSERT(un->un_rqs_bp == NULL);
15701 	ASSERT(un->un_rqs_pktp == NULL);
15702 
15703 	/*
15704 	 * First allocate the required buf and scsi_pkt structs, then set up
15705 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
15706 	 */
15707 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
15708 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
15709 	if (un->un_rqs_bp == NULL) {
15710 		return (DDI_FAILURE);
15711 	}
15712 
15713 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
15714 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
15715 
15716 	if (un->un_rqs_pktp == NULL) {
15717 		sd_free_rqs(un);
15718 		return (DDI_FAILURE);
15719 	}
15720 
15721 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
15722 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
15723 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
15724 
15725 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
15726 
15727 	/* Set up the other needed members in the ARQ scsi_pkt. */
15728 	un->un_rqs_pktp->pkt_comp   = sdintr;
15729 	un->un_rqs_pktp->pkt_time   = sd_io_time;
15730 	un->un_rqs_pktp->pkt_flags |=
15731 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
15732 
15733 	/*
15734 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
15735 	 * provide any intpkt, destroypkt routines as we take care of
15736 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
15737 	 */
15738 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
15739 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
15740 	xp->xb_pktp = un->un_rqs_pktp;
15741 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
15742 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
15743 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
15744 
15745 	/*
15746 	 * Save the pointer to the request sense private bp so it can
15747 	 * be retrieved in sdintr.
15748 	 */
15749 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
15750 	ASSERT(un->un_rqs_bp->b_private == xp);
15751 
15752 	/*
15753 	 * See if the HBA supports auto-request sense for the specified
15754 	 * target/lun. If it does, then try to enable it (if not already
15755 	 * enabled).
15756 	 *
15757 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
15758 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
15759 	 * return success.  However, in both of these cases ARQ is always
15760 	 * enabled and scsi_ifgetcap will always return true. The best approach
15761 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
15762 	 *
15763 	 * The 3rd case is the HBA (adp) always return enabled on
15764 	 * scsi_ifgetgetcap even when it's not enable, the best approach
15765 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
15766 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
15767 	 */
15768 
15769 	if (un->un_f_is_fibre == TRUE) {
15770 		un->un_f_arq_enabled = TRUE;
15771 	} else {
15772 #if defined(__i386) || defined(__amd64)
15773 		/*
15774 		 * Circumvent the Adaptec bug, remove this code when
15775 		 * the bug is fixed
15776 		 */
15777 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
15778 #endif
15779 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
15780 		case 0:
15781 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
15782 			    "sd_alloc_rqs: HBA supports ARQ\n");
15783 			/*
15784 			 * ARQ is supported by this HBA but currently is not
15785 			 * enabled. Attempt to enable it and if successful then
15786 			 * mark this instance as ARQ enabled.
15787 			 */
15788 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
15789 			    == 1) {
15790 				/* Successfully enabled ARQ in the HBA */
15791 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
15792 				    "sd_alloc_rqs: ARQ enabled\n");
15793 				un->un_f_arq_enabled = TRUE;
15794 			} else {
15795 				/* Could not enable ARQ in the HBA */
15796 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
15797 				    "sd_alloc_rqs: failed ARQ enable\n");
15798 				un->un_f_arq_enabled = FALSE;
15799 			}
15800 			break;
15801 		case 1:
15802 			/*
15803 			 * ARQ is supported by this HBA and is already enabled.
15804 			 * Just mark ARQ as enabled for this instance.
15805 			 */
15806 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
15807 			    "sd_alloc_rqs: ARQ already enabled\n");
15808 			un->un_f_arq_enabled = TRUE;
15809 			break;
15810 		default:
15811 			/*
15812 			 * ARQ is not supported by this HBA; disable it for this
15813 			 * instance.
15814 			 */
15815 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
15816 			    "sd_alloc_rqs: HBA does not support ARQ\n");
15817 			un->un_f_arq_enabled = FALSE;
15818 			break;
15819 		}
15820 	}
15821 
15822 	return (DDI_SUCCESS);
15823 }
15824 
15825 
15826 /*
15827  *    Function: sd_free_rqs
15828  *
15829  * Description: Cleanup for the pre-instance RQS command.
15830  *
15831  *     Context: Kernel thread context
15832  */
15833 
15834 static void
15835 sd_free_rqs(struct sd_lun *un)
15836 {
15837 	ASSERT(un != NULL);
15838 
15839 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
15840 
15841 	/*
15842 	 * If consistent memory is bound to a scsi_pkt, the pkt
15843 	 * has to be destroyed *before* freeing the consistent memory.
15844 	 * Don't change the sequence of this operations.
15845 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
15846 	 * after it was freed in scsi_free_consistent_buf().
15847 	 */
15848 	if (un->un_rqs_pktp != NULL) {
15849 		scsi_destroy_pkt(un->un_rqs_pktp);
15850 		un->un_rqs_pktp = NULL;
15851 	}
15852 
15853 	if (un->un_rqs_bp != NULL) {
15854 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
15855 		if (xp != NULL) {
15856 			kmem_free(xp, sizeof (struct sd_xbuf));
15857 		}
15858 		scsi_free_consistent_buf(un->un_rqs_bp);
15859 		un->un_rqs_bp = NULL;
15860 	}
15861 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
15862 }
15863 
15864 
15865 
15866 /*
15867  *    Function: sd_reduce_throttle
15868  *
15869  * Description: Reduces the maximum # of outstanding commands on a
15870  *		target to the current number of outstanding commands.
15871  *		Queues a tiemout(9F) callback to restore the limit
15872  *		after a specified interval has elapsed.
15873  *		Typically used when we get a TRAN_BUSY return code
15874  *		back from scsi_transport().
15875  *
15876  *   Arguments: un - ptr to the sd_lun softstate struct
15877  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
15878  *
15879  *     Context: May be called from interrupt context
15880  */
15881 
15882 static void
15883 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
15884 {
15885 	ASSERT(un != NULL);
15886 	ASSERT(mutex_owned(SD_MUTEX(un)));
15887 	ASSERT(un->un_ncmds_in_transport >= 0);
15888 
15889 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
15890 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
15891 	    un, un->un_throttle, un->un_ncmds_in_transport);
15892 
15893 	if (un->un_throttle > 1) {
15894 		if (un->un_f_use_adaptive_throttle == TRUE) {
15895 			switch (throttle_type) {
15896 			case SD_THROTTLE_TRAN_BUSY:
15897 				if (un->un_busy_throttle == 0) {
15898 					un->un_busy_throttle = un->un_throttle;
15899 				}
15900 				break;
15901 			case SD_THROTTLE_QFULL:
15902 				un->un_busy_throttle = 0;
15903 				break;
15904 			default:
15905 				ASSERT(FALSE);
15906 			}
15907 
15908 			if (un->un_ncmds_in_transport > 0) {
15909 				un->un_throttle = un->un_ncmds_in_transport;
15910 			}
15911 
15912 		} else {
15913 			if (un->un_ncmds_in_transport == 0) {
15914 				un->un_throttle = 1;
15915 			} else {
15916 				un->un_throttle = un->un_ncmds_in_transport;
15917 			}
15918 		}
15919 	}
15920 
15921 	/* Reschedule the timeout if none is currently active */
15922 	if (un->un_reset_throttle_timeid == NULL) {
15923 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
15924 		    un, SD_THROTTLE_RESET_INTERVAL);
15925 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15926 		    "sd_reduce_throttle: timeout scheduled!\n");
15927 	}
15928 
15929 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
15930 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
15931 }
15932 
15933 
15934 
15935 /*
15936  *    Function: sd_restore_throttle
15937  *
15938  * Description: Callback function for timeout(9F).  Resets the current
15939  *		value of un->un_throttle to its default.
15940  *
15941  *   Arguments: arg - pointer to associated softstate for the device.
15942  *
15943  *     Context: May be called from interrupt context
15944  */
15945 
15946 static void
15947 sd_restore_throttle(void *arg)
15948 {
15949 	struct sd_lun	*un = arg;
15950 
15951 	ASSERT(un != NULL);
15952 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15953 
15954 	mutex_enter(SD_MUTEX(un));
15955 
15956 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
15957 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
15958 
15959 	un->un_reset_throttle_timeid = NULL;
15960 
15961 	if (un->un_f_use_adaptive_throttle == TRUE) {
15962 		/*
15963 		 * If un_busy_throttle is nonzero, then it contains the
15964 		 * value that un_throttle was when we got a TRAN_BUSY back
15965 		 * from scsi_transport(). We want to revert back to this
15966 		 * value.
15967 		 *
15968 		 * In the QFULL case, the throttle limit will incrementally
15969 		 * increase until it reaches max throttle.
15970 		 */
15971 		if (un->un_busy_throttle > 0) {
15972 			un->un_throttle = un->un_busy_throttle;
15973 			un->un_busy_throttle = 0;
15974 		} else {
15975 			/*
15976 			 * increase throttle by 10% open gate slowly, schedule
15977 			 * another restore if saved throttle has not been
15978 			 * reached
15979 			 */
15980 			short throttle;
15981 			if (sd_qfull_throttle_enable) {
15982 				throttle = un->un_throttle +
15983 				    max((un->un_throttle / 10), 1);
15984 				un->un_throttle =
15985 				    (throttle < un->un_saved_throttle) ?
15986 				    throttle : un->un_saved_throttle;
15987 				if (un->un_throttle < un->un_saved_throttle) {
15988 					un->un_reset_throttle_timeid =
15989 					    timeout(sd_restore_throttle,
15990 					    un,
15991 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
15992 				}
15993 			}
15994 		}
15995 
15996 		/*
15997 		 * If un_throttle has fallen below the low-water mark, we
15998 		 * restore the maximum value here (and allow it to ratchet
15999 		 * down again if necessary).
16000 		 */
16001 		if (un->un_throttle < un->un_min_throttle) {
16002 			un->un_throttle = un->un_saved_throttle;
16003 		}
16004 	} else {
16005 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16006 		    "restoring limit from 0x%x to 0x%x\n",
16007 		    un->un_throttle, un->un_saved_throttle);
16008 		un->un_throttle = un->un_saved_throttle;
16009 	}
16010 
16011 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16012 	    "sd_restore_throttle: calling sd_start_cmds!\n");
16013 
16014 	sd_start_cmds(un, NULL);
16015 
16016 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16017 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
16018 	    un, un->un_throttle);
16019 
16020 	mutex_exit(SD_MUTEX(un));
16021 
16022 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16023 }
16024 
16025 /*
16026  *    Function: sdrunout
16027  *
16028  * Description: Callback routine for scsi_init_pkt when a resource allocation
16029  *		fails.
16030  *
16031  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16032  *		soft state instance.
16033  *
16034  * Return Code: The scsi_init_pkt routine allows for the callback function to
16035  *		return a 0 indicating the callback should be rescheduled or a 1
16036  *		indicating not to reschedule. This routine always returns 1
16037  *		because the driver always provides a callback function to
16038  *		scsi_init_pkt. This results in a callback always being scheduled
16039  *		(via the scsi_init_pkt callback implementation) if a resource
16040  *		failure occurs.
16041  *
16042  *     Context: This callback function may not block or call routines that block
16043  *
16044  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16045  *		request persisting at the head of the list which cannot be
16046  *		satisfied even after multiple retries. In the future the driver
16047  *		may implement some time of maximum runout count before failing
16048  *		an I/O.
16049  */
16050 
16051 static int
16052 sdrunout(caddr_t arg)
16053 {
16054 	struct sd_lun	*un = (struct sd_lun *)arg;
16055 
16056 	ASSERT(un != NULL);
16057 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16058 
16059 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16060 
16061 	mutex_enter(SD_MUTEX(un));
16062 	sd_start_cmds(un, NULL);
16063 	mutex_exit(SD_MUTEX(un));
16064 	/*
16065 	 * This callback routine always returns 1 (i.e. do not reschedule)
16066 	 * because we always specify sdrunout as the callback handler for
16067 	 * scsi_init_pkt inside the call to sd_start_cmds.
16068 	 */
16069 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16070 	return (1);
16071 }
16072 
16073 
16074 /*
16075  *    Function: sdintr
16076  *
16077  * Description: Completion callback routine for scsi_pkt(9S) structs
16078  *		sent to the HBA driver via scsi_transport(9F).
16079  *
16080  *     Context: Interrupt context
16081  */
16082 
16083 static void
16084 sdintr(struct scsi_pkt *pktp)
16085 {
16086 	struct buf	*bp;
16087 	struct sd_xbuf	*xp;
16088 	struct sd_lun	*un;
16089 	size_t		actual_len;
16090 	sd_ssc_t	*sscp;
16091 
16092 	ASSERT(pktp != NULL);
16093 	bp = (struct buf *)pktp->pkt_private;
16094 	ASSERT(bp != NULL);
16095 	xp = SD_GET_XBUF(bp);
16096 	ASSERT(xp != NULL);
16097 	ASSERT(xp->xb_pktp != NULL);
16098 	un = SD_GET_UN(bp);
16099 	ASSERT(un != NULL);
16100 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16101 
16102 #ifdef SD_FAULT_INJECTION
16103 
16104 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16105 	/* SD FaultInjection */
16106 	sd_faultinjection(pktp);
16107 
16108 #endif /* SD_FAULT_INJECTION */
16109 
16110 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16111 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16112 
16113 	mutex_enter(SD_MUTEX(un));
16114 
16115 	ASSERT(un->un_fm_private != NULL);
16116 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16117 	ASSERT(sscp != NULL);
16118 
16119 	/* Reduce the count of the #commands currently in transport */
16120 	un->un_ncmds_in_transport--;
16121 	ASSERT(un->un_ncmds_in_transport >= 0);
16122 
16123 	/* Increment counter to indicate that the callback routine is active */
16124 	un->un_in_callback++;
16125 
16126 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16127 
16128 #ifdef	SDDEBUG
16129 	if (bp == un->un_retry_bp) {
16130 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16131 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16132 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16133 	}
16134 #endif
16135 
16136 	/*
16137 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
16138 	 * state if needed.
16139 	 */
16140 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16141 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16142 		    "Command failed to complete...Device is gone\n");
16143 		if (un->un_mediastate != DKIO_DEV_GONE) {
16144 			un->un_mediastate = DKIO_DEV_GONE;
16145 			cv_broadcast(&un->un_state_cv);
16146 		}
16147 		sd_return_failed_command(un, bp, EIO);
16148 		goto exit;
16149 	}
16150 
16151 	if (pktp->pkt_state & STATE_XARQ_DONE) {
16152 		SD_TRACE(SD_LOG_COMMON, un,
16153 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
16154 	}
16155 
16156 	/*
16157 	 * First see if the pkt has auto-request sense data with it....
16158 	 * Look at the packet state first so we don't take a performance
16159 	 * hit looking at the arq enabled flag unless absolutely necessary.
16160 	 */
16161 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16162 	    (un->un_f_arq_enabled == TRUE)) {
16163 		/*
16164 		 * The HBA did an auto request sense for this command so check
16165 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16166 		 * driver command that should not be retried.
16167 		 */
16168 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16169 			/*
16170 			 * Save the relevant sense info into the xp for the
16171 			 * original cmd.
16172 			 */
16173 			struct scsi_arq_status *asp;
16174 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16175 			xp->xb_sense_status =
16176 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16177 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16178 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16179 			if (pktp->pkt_state & STATE_XARQ_DONE) {
16180 				actual_len = MAX_SENSE_LENGTH -
16181 				    xp->xb_sense_resid;
16182 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16183 				    MAX_SENSE_LENGTH);
16184 			} else {
16185 				if (xp->xb_sense_resid > SENSE_LENGTH) {
16186 					actual_len = MAX_SENSE_LENGTH -
16187 					    xp->xb_sense_resid;
16188 				} else {
16189 					actual_len = SENSE_LENGTH -
16190 					    xp->xb_sense_resid;
16191 				}
16192 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16193 					if ((((struct uscsi_cmd *)
16194 					    (xp->xb_pktinfo))->uscsi_rqlen) >
16195 					    actual_len) {
16196 						xp->xb_sense_resid =
16197 						    (((struct uscsi_cmd *)
16198 						    (xp->xb_pktinfo))->
16199 						    uscsi_rqlen) - actual_len;
16200 					} else {
16201 						xp->xb_sense_resid = 0;
16202 					}
16203 				}
16204 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16205 				    SENSE_LENGTH);
16206 			}
16207 
16208 			/* fail the command */
16209 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16210 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
16211 			sd_return_failed_command(un, bp, EIO);
16212 			goto exit;
16213 		}
16214 
16215 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16216 		/*
16217 		 * We want to either retry or fail this command, so free
16218 		 * the DMA resources here.  If we retry the command then
16219 		 * the DMA resources will be reallocated in sd_start_cmds().
16220 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
16221 		 * causes the *entire* transfer to start over again from the
16222 		 * beginning of the request, even for PARTIAL chunks that
16223 		 * have already transferred successfully.
16224 		 */
16225 		if ((un->un_f_is_fibre == TRUE) &&
16226 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16227 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16228 			scsi_dmafree(pktp);
16229 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16230 		}
16231 #endif
16232 
16233 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16234 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
16235 
16236 		sd_handle_auto_request_sense(un, bp, xp, pktp);
16237 		goto exit;
16238 	}
16239 
16240 	/* Next see if this is the REQUEST SENSE pkt for the instance */
16241 	if (pktp->pkt_flags & FLAG_SENSING)  {
16242 		/* This pktp is from the unit's REQUEST_SENSE command */
16243 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16244 		    "sdintr: sd_handle_request_sense\n");
16245 		sd_handle_request_sense(un, bp, xp, pktp);
16246 		goto exit;
16247 	}
16248 
16249 	/*
16250 	 * Check to see if the command successfully completed as requested;
16251 	 * this is the most common case (and also the hot performance path).
16252 	 *
16253 	 * Requirements for successful completion are:
16254 	 * pkt_reason is CMD_CMPLT and packet status is status good.
16255 	 * In addition:
16256 	 * - A residual of zero indicates successful completion no matter what
16257 	 *   the command is.
16258 	 * - If the residual is not zero and the command is not a read or
16259 	 *   write, then it's still defined as successful completion. In other
16260 	 *   words, if the command is a read or write the residual must be
16261 	 *   zero for successful completion.
16262 	 * - If the residual is not zero and the command is a read or
16263 	 *   write, and it's a USCSICMD, then it's still defined as
16264 	 *   successful completion.
16265 	 */
16266 	if ((pktp->pkt_reason == CMD_CMPLT) &&
16267 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
16268 
16269 		/*
16270 		 * Since this command is returned with a good status, we
16271 		 * can reset the count for Sonoma failover.
16272 		 */
16273 		un->un_sonoma_failure_count = 0;
16274 
16275 		/*
16276 		 * Return all USCSI commands on good status
16277 		 */
16278 		if (pktp->pkt_resid == 0) {
16279 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16280 			    "sdintr: returning command for resid == 0\n");
16281 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
16282 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
16283 			SD_UPDATE_B_RESID(bp, pktp);
16284 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16285 			    "sdintr: returning command for resid != 0\n");
16286 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16287 			SD_UPDATE_B_RESID(bp, pktp);
16288 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16289 			    "sdintr: returning uscsi command\n");
16290 		} else {
16291 			goto not_successful;
16292 		}
16293 		sd_return_command(un, bp);
16294 
16295 		/*
16296 		 * Decrement counter to indicate that the callback routine
16297 		 * is done.
16298 		 */
16299 		un->un_in_callback--;
16300 		ASSERT(un->un_in_callback >= 0);
16301 		mutex_exit(SD_MUTEX(un));
16302 
16303 		return;
16304 	}
16305 
16306 not_successful:
16307 
16308 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16309 	/*
16310 	 * The following is based upon knowledge of the underlying transport
16311 	 * and its use of DMA resources.  This code should be removed when
16312 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
16313 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
16314 	 * and sd_start_cmds().
16315 	 *
16316 	 * Free any DMA resources associated with this command if there
16317 	 * is a chance it could be retried or enqueued for later retry.
16318 	 * If we keep the DMA binding then mpxio cannot reissue the
16319 	 * command on another path whenever a path failure occurs.
16320 	 *
16321 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
16322 	 * causes the *entire* transfer to start over again from the
16323 	 * beginning of the request, even for PARTIAL chunks that
16324 	 * have already transferred successfully.
16325 	 *
16326 	 * This is only done for non-uscsi commands (and also skipped for the
16327 	 * driver's internal RQS command). Also just do this for Fibre Channel
16328 	 * devices as these are the only ones that support mpxio.
16329 	 */
16330 	if ((un->un_f_is_fibre == TRUE) &&
16331 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16332 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16333 		scsi_dmafree(pktp);
16334 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16335 	}
16336 #endif
16337 
16338 	/*
16339 	 * The command did not successfully complete as requested so check
16340 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16341 	 * driver command that should not be retried so just return. If
16342 	 * FLAG_DIAGNOSE is not set the error will be processed below.
16343 	 */
16344 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16345 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16346 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
16347 		/*
16348 		 * Issue a request sense if a check condition caused the error
16349 		 * (we handle the auto request sense case above), otherwise
16350 		 * just fail the command.
16351 		 */
16352 		if ((pktp->pkt_reason == CMD_CMPLT) &&
16353 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
16354 			sd_send_request_sense_command(un, bp, pktp);
16355 		} else {
16356 			sd_return_failed_command(un, bp, EIO);
16357 		}
16358 		goto exit;
16359 	}
16360 
16361 	/*
16362 	 * The command did not successfully complete as requested so process
16363 	 * the error, retry, and/or attempt recovery.
16364 	 */
16365 	switch (pktp->pkt_reason) {
16366 	case CMD_CMPLT:
16367 		switch (SD_GET_PKT_STATUS(pktp)) {
16368 		case STATUS_GOOD:
16369 			/*
16370 			 * The command completed successfully with a non-zero
16371 			 * residual
16372 			 */
16373 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16374 			    "sdintr: STATUS_GOOD \n");
16375 			sd_pkt_status_good(un, bp, xp, pktp);
16376 			break;
16377 
16378 		case STATUS_CHECK:
16379 		case STATUS_TERMINATED:
16380 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16381 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
16382 			sd_pkt_status_check_condition(un, bp, xp, pktp);
16383 			break;
16384 
16385 		case STATUS_BUSY:
16386 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16387 			    "sdintr: STATUS_BUSY\n");
16388 			sd_pkt_status_busy(un, bp, xp, pktp);
16389 			break;
16390 
16391 		case STATUS_RESERVATION_CONFLICT:
16392 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16393 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
16394 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
16395 			break;
16396 
16397 		case STATUS_QFULL:
16398 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16399 			    "sdintr: STATUS_QFULL\n");
16400 			sd_pkt_status_qfull(un, bp, xp, pktp);
16401 			break;
16402 
16403 		case STATUS_MET:
16404 		case STATUS_INTERMEDIATE:
16405 		case STATUS_SCSI2:
16406 		case STATUS_INTERMEDIATE_MET:
16407 		case STATUS_ACA_ACTIVE:
16408 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16409 			    "Unexpected SCSI status received: 0x%x\n",
16410 			    SD_GET_PKT_STATUS(pktp));
16411 			/*
16412 			 * Mark the ssc_flags when detected invalid status
16413 			 * code for non-USCSI command.
16414 			 */
16415 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16416 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
16417 				    0, "stat-code");
16418 			}
16419 			sd_return_failed_command(un, bp, EIO);
16420 			break;
16421 
16422 		default:
16423 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16424 			    "Invalid SCSI status received: 0x%x\n",
16425 			    SD_GET_PKT_STATUS(pktp));
16426 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16427 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
16428 				    0, "stat-code");
16429 			}
16430 			sd_return_failed_command(un, bp, EIO);
16431 			break;
16432 
16433 		}
16434 		break;
16435 
16436 	case CMD_INCOMPLETE:
16437 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16438 		    "sdintr:  CMD_INCOMPLETE\n");
16439 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
16440 		break;
16441 	case CMD_TRAN_ERR:
16442 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16443 		    "sdintr: CMD_TRAN_ERR\n");
16444 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
16445 		break;
16446 	case CMD_RESET:
16447 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16448 		    "sdintr: CMD_RESET \n");
16449 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
16450 		break;
16451 	case CMD_ABORTED:
16452 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16453 		    "sdintr: CMD_ABORTED \n");
16454 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
16455 		break;
16456 	case CMD_TIMEOUT:
16457 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16458 		    "sdintr: CMD_TIMEOUT\n");
16459 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
16460 		break;
16461 	case CMD_UNX_BUS_FREE:
16462 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16463 		    "sdintr: CMD_UNX_BUS_FREE \n");
16464 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
16465 		break;
16466 	case CMD_TAG_REJECT:
16467 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16468 		    "sdintr: CMD_TAG_REJECT\n");
16469 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
16470 		break;
16471 	default:
16472 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16473 		    "sdintr: default\n");
16474 		/*
16475 		 * Mark the ssc_flags for detecting invliad pkt_reason.
16476 		 */
16477 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16478 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_PKT_REASON,
16479 			    0, "pkt-reason");
16480 		}
16481 		sd_pkt_reason_default(un, bp, xp, pktp);
16482 		break;
16483 	}
16484 
16485 exit:
16486 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
16487 
16488 	/* Decrement counter to indicate that the callback routine is done. */
16489 	un->un_in_callback--;
16490 	ASSERT(un->un_in_callback >= 0);
16491 
16492 	/*
16493 	 * At this point, the pkt has been dispatched, ie, it is either
16494 	 * being re-tried or has been returned to its caller and should
16495 	 * not be referenced.
16496 	 */
16497 
16498 	mutex_exit(SD_MUTEX(un));
16499 }
16500 
16501 
16502 /*
16503  *    Function: sd_print_incomplete_msg
16504  *
16505  * Description: Prints the error message for a CMD_INCOMPLETE error.
16506  *
16507  *   Arguments: un - ptr to associated softstate for the device.
16508  *		bp - ptr to the buf(9S) for the command.
16509  *		arg - message string ptr
16510  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
16511  *			or SD_NO_RETRY_ISSUED.
16512  *
16513  *     Context: May be called under interrupt context
16514  */
16515 
16516 static void
16517 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
16518 {
16519 	struct scsi_pkt	*pktp;
16520 	char	*msgp;
16521 	char	*cmdp = arg;
16522 
16523 	ASSERT(un != NULL);
16524 	ASSERT(mutex_owned(SD_MUTEX(un)));
16525 	ASSERT(bp != NULL);
16526 	ASSERT(arg != NULL);
16527 	pktp = SD_GET_PKTP(bp);
16528 	ASSERT(pktp != NULL);
16529 
16530 	switch (code) {
16531 	case SD_DELAYED_RETRY_ISSUED:
16532 	case SD_IMMEDIATE_RETRY_ISSUED:
16533 		msgp = "retrying";
16534 		break;
16535 	case SD_NO_RETRY_ISSUED:
16536 	default:
16537 		msgp = "giving up";
16538 		break;
16539 	}
16540 
16541 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16542 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16543 		    "incomplete %s- %s\n", cmdp, msgp);
16544 	}
16545 }
16546 
16547 
16548 
16549 /*
16550  *    Function: sd_pkt_status_good
16551  *
16552  * Description: Processing for a STATUS_GOOD code in pkt_status.
16553  *
16554  *     Context: May be called under interrupt context
16555  */
16556 
16557 static void
16558 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
16559 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16560 {
16561 	char	*cmdp;
16562 
16563 	ASSERT(un != NULL);
16564 	ASSERT(mutex_owned(SD_MUTEX(un)));
16565 	ASSERT(bp != NULL);
16566 	ASSERT(xp != NULL);
16567 	ASSERT(pktp != NULL);
16568 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
16569 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
16570 	ASSERT(pktp->pkt_resid != 0);
16571 
16572 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
16573 
16574 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16575 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
16576 	case SCMD_READ:
16577 		cmdp = "read";
16578 		break;
16579 	case SCMD_WRITE:
16580 		cmdp = "write";
16581 		break;
16582 	default:
16583 		SD_UPDATE_B_RESID(bp, pktp);
16584 		sd_return_command(un, bp);
16585 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
16586 		return;
16587 	}
16588 
16589 	/*
16590 	 * See if we can retry the read/write, preferrably immediately.
16591 	 * If retries are exhaused, then sd_retry_command() will update
16592 	 * the b_resid count.
16593 	 */
16594 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
16595 	    cmdp, EIO, (clock_t)0, NULL);
16596 
16597 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
16598 }
16599 
16600 
16601 
16602 
16603 
16604 /*
16605  *    Function: sd_handle_request_sense
16606  *
16607  * Description: Processing for non-auto Request Sense command.
16608  *
16609  *   Arguments: un - ptr to associated softstate
16610  *		sense_bp - ptr to buf(9S) for the RQS command
16611  *		sense_xp - ptr to the sd_xbuf for the RQS command
16612  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
16613  *
16614  *     Context: May be called under interrupt context
16615  */
16616 
16617 static void
16618 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
16619 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
16620 {
16621 	struct buf	*cmd_bp;	/* buf for the original command */
16622 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
16623 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
16624 	size_t		actual_len;	/* actual sense data length */
16625 
16626 	ASSERT(un != NULL);
16627 	ASSERT(mutex_owned(SD_MUTEX(un)));
16628 	ASSERT(sense_bp != NULL);
16629 	ASSERT(sense_xp != NULL);
16630 	ASSERT(sense_pktp != NULL);
16631 
16632 	/*
16633 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
16634 	 * RQS command and not the original command.
16635 	 */
16636 	ASSERT(sense_pktp == un->un_rqs_pktp);
16637 	ASSERT(sense_bp   == un->un_rqs_bp);
16638 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
16639 	    (FLAG_SENSING | FLAG_HEAD));
16640 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
16641 	    FLAG_SENSING) == FLAG_SENSING);
16642 
16643 	/* These are the bp, xp, and pktp for the original command */
16644 	cmd_bp = sense_xp->xb_sense_bp;
16645 	cmd_xp = SD_GET_XBUF(cmd_bp);
16646 	cmd_pktp = SD_GET_PKTP(cmd_bp);
16647 
16648 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
16649 		/*
16650 		 * The REQUEST SENSE command failed.  Release the REQUEST
16651 		 * SENSE command for re-use, get back the bp for the original
16652 		 * command, and attempt to re-try the original command if
16653 		 * FLAG_DIAGNOSE is not set in the original packet.
16654 		 */
16655 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16656 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16657 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
16658 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
16659 			    NULL, NULL, EIO, (clock_t)0, NULL);
16660 			return;
16661 		}
16662 	}
16663 
16664 	/*
16665 	 * Save the relevant sense info into the xp for the original cmd.
16666 	 *
16667 	 * Note: if the request sense failed the state info will be zero
16668 	 * as set in sd_mark_rqs_busy()
16669 	 */
16670 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
16671 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
16672 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
16673 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
16674 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
16675 	    SENSE_LENGTH)) {
16676 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
16677 		    MAX_SENSE_LENGTH);
16678 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
16679 	} else {
16680 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
16681 		    SENSE_LENGTH);
16682 		if (actual_len < SENSE_LENGTH) {
16683 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
16684 		} else {
16685 			cmd_xp->xb_sense_resid = 0;
16686 		}
16687 	}
16688 
16689 	/*
16690 	 *  Free up the RQS command....
16691 	 *  NOTE:
16692 	 *	Must do this BEFORE calling sd_validate_sense_data!
16693 	 *	sd_validate_sense_data may return the original command in
16694 	 *	which case the pkt will be freed and the flags can no
16695 	 *	longer be touched.
16696 	 *	SD_MUTEX is held through this process until the command
16697 	 *	is dispatched based upon the sense data, so there are
16698 	 *	no race conditions.
16699 	 */
16700 	(void) sd_mark_rqs_idle(un, sense_xp);
16701 
16702 	/*
16703 	 * For a retryable command see if we have valid sense data, if so then
16704 	 * turn it over to sd_decode_sense() to figure out the right course of
16705 	 * action. Just fail a non-retryable command.
16706 	 */
16707 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16708 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
16709 		    SD_SENSE_DATA_IS_VALID) {
16710 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
16711 		}
16712 	} else {
16713 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
16714 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
16715 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
16716 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
16717 		sd_return_failed_command(un, cmd_bp, EIO);
16718 	}
16719 }
16720 
16721 
16722 
16723 
16724 /*
16725  *    Function: sd_handle_auto_request_sense
16726  *
16727  * Description: Processing for auto-request sense information.
16728  *
16729  *   Arguments: un - ptr to associated softstate
16730  *		bp - ptr to buf(9S) for the command
16731  *		xp - ptr to the sd_xbuf for the command
16732  *		pktp - ptr to the scsi_pkt(9S) for the command
16733  *
16734  *     Context: May be called under interrupt context
16735  */
16736 
16737 static void
16738 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
16739 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16740 {
16741 	struct scsi_arq_status *asp;
16742 	size_t actual_len;
16743 
16744 	ASSERT(un != NULL);
16745 	ASSERT(mutex_owned(SD_MUTEX(un)));
16746 	ASSERT(bp != NULL);
16747 	ASSERT(xp != NULL);
16748 	ASSERT(pktp != NULL);
16749 	ASSERT(pktp != un->un_rqs_pktp);
16750 	ASSERT(bp   != un->un_rqs_bp);
16751 
16752 	/*
16753 	 * For auto-request sense, we get a scsi_arq_status back from
16754 	 * the HBA, with the sense data in the sts_sensedata member.
16755 	 * The pkt_scbp of the packet points to this scsi_arq_status.
16756 	 */
16757 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16758 
16759 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
16760 		/*
16761 		 * The auto REQUEST SENSE failed; see if we can re-try
16762 		 * the original command.
16763 		 */
16764 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16765 		    "auto request sense failed (reason=%s)\n",
16766 		    scsi_rname(asp->sts_rqpkt_reason));
16767 
16768 		sd_reset_target(un, pktp);
16769 
16770 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
16771 		    NULL, NULL, EIO, (clock_t)0, NULL);
16772 		return;
16773 	}
16774 
16775 	/* Save the relevant sense info into the xp for the original cmd. */
16776 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
16777 	xp->xb_sense_state  = asp->sts_rqpkt_state;
16778 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16779 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
16780 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
16781 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16782 		    MAX_SENSE_LENGTH);
16783 	} else {
16784 		if (xp->xb_sense_resid > SENSE_LENGTH) {
16785 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
16786 		} else {
16787 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
16788 		}
16789 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16790 			if ((((struct uscsi_cmd *)
16791 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
16792 				xp->xb_sense_resid = (((struct uscsi_cmd *)
16793 				    (xp->xb_pktinfo))->uscsi_rqlen) -
16794 				    actual_len;
16795 			} else {
16796 				xp->xb_sense_resid = 0;
16797 			}
16798 		}
16799 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
16800 	}
16801 
16802 	/*
16803 	 * See if we have valid sense data, if so then turn it over to
16804 	 * sd_decode_sense() to figure out the right course of action.
16805 	 */
16806 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
16807 	    SD_SENSE_DATA_IS_VALID) {
16808 		sd_decode_sense(un, bp, xp, pktp);
16809 	}
16810 }
16811 
16812 
16813 /*
16814  *    Function: sd_print_sense_failed_msg
16815  *
16816  * Description: Print log message when RQS has failed.
16817  *
16818  *   Arguments: un - ptr to associated softstate
16819  *		bp - ptr to buf(9S) for the command
16820  *		arg - generic message string ptr
16821  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16822  *			or SD_NO_RETRY_ISSUED
16823  *
16824  *     Context: May be called from interrupt context
16825  */
16826 
16827 static void
16828 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
16829 	int code)
16830 {
16831 	char	*msgp = arg;
16832 
16833 	ASSERT(un != NULL);
16834 	ASSERT(mutex_owned(SD_MUTEX(un)));
16835 	ASSERT(bp != NULL);
16836 
16837 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
16838 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
16839 	}
16840 }
16841 
16842 
16843 /*
16844  *    Function: sd_validate_sense_data
16845  *
16846  * Description: Check the given sense data for validity.
16847  *		If the sense data is not valid, the command will
16848  *		be either failed or retried!
16849  *
16850  * Return Code: SD_SENSE_DATA_IS_INVALID
16851  *		SD_SENSE_DATA_IS_VALID
16852  *
16853  *     Context: May be called from interrupt context
16854  */
16855 
16856 static int
16857 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
16858 	size_t actual_len)
16859 {
16860 	struct scsi_extended_sense *esp;
16861 	struct	scsi_pkt *pktp;
16862 	char	*msgp = NULL;
16863 	sd_ssc_t *sscp;
16864 
16865 	ASSERT(un != NULL);
16866 	ASSERT(mutex_owned(SD_MUTEX(un)));
16867 	ASSERT(bp != NULL);
16868 	ASSERT(bp != un->un_rqs_bp);
16869 	ASSERT(xp != NULL);
16870 	ASSERT(un->un_fm_private != NULL);
16871 
16872 	pktp = SD_GET_PKTP(bp);
16873 	ASSERT(pktp != NULL);
16874 
16875 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16876 	ASSERT(sscp != NULL);
16877 
16878 	/*
16879 	 * Check the status of the RQS command (auto or manual).
16880 	 */
16881 	switch (xp->xb_sense_status & STATUS_MASK) {
16882 	case STATUS_GOOD:
16883 		break;
16884 
16885 	case STATUS_RESERVATION_CONFLICT:
16886 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
16887 		return (SD_SENSE_DATA_IS_INVALID);
16888 
16889 	case STATUS_BUSY:
16890 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16891 		    "Busy Status on REQUEST SENSE\n");
16892 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
16893 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
16894 		return (SD_SENSE_DATA_IS_INVALID);
16895 
16896 	case STATUS_QFULL:
16897 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16898 		    "QFULL Status on REQUEST SENSE\n");
16899 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
16900 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
16901 		return (SD_SENSE_DATA_IS_INVALID);
16902 
16903 	case STATUS_CHECK:
16904 	case STATUS_TERMINATED:
16905 		msgp = "Check Condition on REQUEST SENSE\n";
16906 		goto sense_failed;
16907 
16908 	default:
16909 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
16910 		goto sense_failed;
16911 	}
16912 
16913 	/*
16914 	 * See if we got the minimum required amount of sense data.
16915 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
16916 	 * or less.
16917 	 */
16918 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
16919 	    (actual_len == 0)) {
16920 		msgp = "Request Sense couldn't get sense data\n";
16921 		goto sense_failed;
16922 	}
16923 
16924 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
16925 		msgp = "Not enough sense information\n";
16926 		/* Mark the ssc_flags for detecting invalid sense data */
16927 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16928 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
16929 			    "sense-data");
16930 		}
16931 		goto sense_failed;
16932 	}
16933 
16934 	/*
16935 	 * We require the extended sense data
16936 	 */
16937 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
16938 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
16939 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16940 			static char tmp[8];
16941 			static char buf[148];
16942 			char *p = (char *)(xp->xb_sense_data);
16943 			int i;
16944 
16945 			mutex_enter(&sd_sense_mutex);
16946 			(void) strcpy(buf, "undecodable sense information:");
16947 			for (i = 0; i < actual_len; i++) {
16948 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
16949 				(void) strcpy(&buf[strlen(buf)], tmp);
16950 			}
16951 			i = strlen(buf);
16952 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
16953 
16954 			if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
16955 				scsi_log(SD_DEVINFO(un), sd_label,
16956 				    CE_WARN, buf);
16957 			}
16958 			mutex_exit(&sd_sense_mutex);
16959 		}
16960 
16961 		/* Mark the ssc_flags for detecting invalid sense data */
16962 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16963 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
16964 			    "sense-data");
16965 		}
16966 
16967 		/* Note: Legacy behavior, fail the command with no retry */
16968 		sd_return_failed_command(un, bp, EIO);
16969 		return (SD_SENSE_DATA_IS_INVALID);
16970 	}
16971 
16972 	/*
16973 	 * Check that es_code is valid (es_class concatenated with es_code
16974 	 * make up the "response code" field.  es_class will always be 7, so
16975 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
16976 	 * format.
16977 	 */
16978 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
16979 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
16980 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
16981 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
16982 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
16983 		/* Mark the ssc_flags for detecting invalid sense data */
16984 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16985 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
16986 			    "sense-data");
16987 		}
16988 		goto sense_failed;
16989 	}
16990 
16991 	return (SD_SENSE_DATA_IS_VALID);
16992 
16993 sense_failed:
16994 	/*
16995 	 * If the request sense failed (for whatever reason), attempt
16996 	 * to retry the original command.
16997 	 */
16998 #if defined(__i386) || defined(__amd64)
16999 	/*
17000 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
17001 	 * sddef.h for Sparc platform, and x86 uses 1 binary
17002 	 * for both SCSI/FC.
17003 	 * The SD_RETRY_DELAY value need to be adjusted here
17004 	 * when SD_RETRY_DELAY change in sddef.h
17005 	 */
17006 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17007 	    sd_print_sense_failed_msg, msgp, EIO,
17008 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
17009 #else
17010 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17011 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
17012 #endif
17013 
17014 	return (SD_SENSE_DATA_IS_INVALID);
17015 }
17016 
17017 /*
17018  *    Function: sd_decode_sense
17019  *
17020  * Description: Take recovery action(s) when SCSI Sense Data is received.
17021  *
17022  *     Context: Interrupt context.
17023  */
17024 
17025 static void
17026 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17027 	struct scsi_pkt *pktp)
17028 {
17029 	uint8_t sense_key;
17030 
17031 	ASSERT(un != NULL);
17032 	ASSERT(mutex_owned(SD_MUTEX(un)));
17033 	ASSERT(bp != NULL);
17034 	ASSERT(bp != un->un_rqs_bp);
17035 	ASSERT(xp != NULL);
17036 	ASSERT(pktp != NULL);
17037 
17038 	sense_key = scsi_sense_key(xp->xb_sense_data);
17039 
17040 	switch (sense_key) {
17041 	case KEY_NO_SENSE:
17042 		sd_sense_key_no_sense(un, bp, xp, pktp);
17043 		break;
17044 	case KEY_RECOVERABLE_ERROR:
17045 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
17046 		    bp, xp, pktp);
17047 		break;
17048 	case KEY_NOT_READY:
17049 		sd_sense_key_not_ready(un, xp->xb_sense_data,
17050 		    bp, xp, pktp);
17051 		break;
17052 	case KEY_MEDIUM_ERROR:
17053 	case KEY_HARDWARE_ERROR:
17054 		sd_sense_key_medium_or_hardware_error(un,
17055 		    xp->xb_sense_data, bp, xp, pktp);
17056 		break;
17057 	case KEY_ILLEGAL_REQUEST:
17058 		sd_sense_key_illegal_request(un, bp, xp, pktp);
17059 		break;
17060 	case KEY_UNIT_ATTENTION:
17061 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
17062 		    bp, xp, pktp);
17063 		break;
17064 	case KEY_WRITE_PROTECT:
17065 	case KEY_VOLUME_OVERFLOW:
17066 	case KEY_MISCOMPARE:
17067 		sd_sense_key_fail_command(un, bp, xp, pktp);
17068 		break;
17069 	case KEY_BLANK_CHECK:
17070 		sd_sense_key_blank_check(un, bp, xp, pktp);
17071 		break;
17072 	case KEY_ABORTED_COMMAND:
17073 		sd_sense_key_aborted_command(un, bp, xp, pktp);
17074 		break;
17075 	case KEY_VENDOR_UNIQUE:
17076 	case KEY_COPY_ABORTED:
17077 	case KEY_EQUAL:
17078 	case KEY_RESERVED:
17079 	default:
17080 		sd_sense_key_default(un, xp->xb_sense_data,
17081 		    bp, xp, pktp);
17082 		break;
17083 	}
17084 }
17085 
17086 
17087 /*
17088  *    Function: sd_dump_memory
17089  *
17090  * Description: Debug logging routine to print the contents of a user provided
17091  *		buffer. The output of the buffer is broken up into 256 byte
17092  *		segments due to a size constraint of the scsi_log.
17093  *		implementation.
17094  *
17095  *   Arguments: un - ptr to softstate
17096  *		comp - component mask
17097  *		title - "title" string to preceed data when printed
17098  *		data - ptr to data block to be printed
17099  *		len - size of data block to be printed
17100  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
17101  *
17102  *     Context: May be called from interrupt context
17103  */
17104 
17105 #define	SD_DUMP_MEMORY_BUF_SIZE	256
17106 
17107 static char *sd_dump_format_string[] = {
17108 		" 0x%02x",
17109 		" %c"
17110 };
17111 
17112 static void
17113 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
17114     int len, int fmt)
17115 {
17116 	int	i, j;
17117 	int	avail_count;
17118 	int	start_offset;
17119 	int	end_offset;
17120 	size_t	entry_len;
17121 	char	*bufp;
17122 	char	*local_buf;
17123 	char	*format_string;
17124 
17125 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
17126 
17127 	/*
17128 	 * In the debug version of the driver, this function is called from a
17129 	 * number of places which are NOPs in the release driver.
17130 	 * The debug driver therefore has additional methods of filtering
17131 	 * debug output.
17132 	 */
17133 #ifdef SDDEBUG
17134 	/*
17135 	 * In the debug version of the driver we can reduce the amount of debug
17136 	 * messages by setting sd_error_level to something other than
17137 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17138 	 * sd_component_mask.
17139 	 */
17140 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17141 	    (sd_error_level != SCSI_ERR_ALL)) {
17142 		return;
17143 	}
17144 	if (((sd_component_mask & comp) == 0) ||
17145 	    (sd_error_level != SCSI_ERR_ALL)) {
17146 		return;
17147 	}
17148 #else
17149 	if (sd_error_level != SCSI_ERR_ALL) {
17150 		return;
17151 	}
17152 #endif
17153 
17154 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17155 	bufp = local_buf;
17156 	/*
17157 	 * Available length is the length of local_buf[], minus the
17158 	 * length of the title string, minus one for the ":", minus
17159 	 * one for the newline, minus one for the NULL terminator.
17160 	 * This gives the #bytes available for holding the printed
17161 	 * values from the given data buffer.
17162 	 */
17163 	if (fmt == SD_LOG_HEX) {
17164 		format_string = sd_dump_format_string[0];
17165 	} else /* SD_LOG_CHAR */ {
17166 		format_string = sd_dump_format_string[1];
17167 	}
17168 	/*
17169 	 * Available count is the number of elements from the given
17170 	 * data buffer that we can fit into the available length.
17171 	 * This is based upon the size of the format string used.
17172 	 * Make one entry and find it's size.
17173 	 */
17174 	(void) sprintf(bufp, format_string, data[0]);
17175 	entry_len = strlen(bufp);
17176 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17177 
17178 	j = 0;
17179 	while (j < len) {
17180 		bufp = local_buf;
17181 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17182 		start_offset = j;
17183 
17184 		end_offset = start_offset + avail_count;
17185 
17186 		(void) sprintf(bufp, "%s:", title);
17187 		bufp += strlen(bufp);
17188 		for (i = start_offset; ((i < end_offset) && (j < len));
17189 		    i++, j++) {
17190 			(void) sprintf(bufp, format_string, data[i]);
17191 			bufp += entry_len;
17192 		}
17193 		(void) sprintf(bufp, "\n");
17194 
17195 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17196 	}
17197 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
17198 }
17199 
17200 /*
17201  *    Function: sd_print_sense_msg
17202  *
17203  * Description: Log a message based upon the given sense data.
17204  *
17205  *   Arguments: un - ptr to associated softstate
17206  *		bp - ptr to buf(9S) for the command
17207  *		arg - ptr to associate sd_sense_info struct
17208  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17209  *			or SD_NO_RETRY_ISSUED
17210  *
17211  *     Context: May be called from interrupt context
17212  */
17213 
17214 static void
17215 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17216 {
17217 	struct sd_xbuf	*xp;
17218 	struct scsi_pkt	*pktp;
17219 	uint8_t *sensep;
17220 	daddr_t request_blkno;
17221 	diskaddr_t err_blkno;
17222 	int severity;
17223 	int pfa_flag;
17224 	extern struct scsi_key_strings scsi_cmds[];
17225 
17226 	ASSERT(un != NULL);
17227 	ASSERT(mutex_owned(SD_MUTEX(un)));
17228 	ASSERT(bp != NULL);
17229 	xp = SD_GET_XBUF(bp);
17230 	ASSERT(xp != NULL);
17231 	pktp = SD_GET_PKTP(bp);
17232 	ASSERT(pktp != NULL);
17233 	ASSERT(arg != NULL);
17234 
17235 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
17236 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
17237 
17238 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
17239 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
17240 		severity = SCSI_ERR_RETRYABLE;
17241 	}
17242 
17243 	/* Use absolute block number for the request block number */
17244 	request_blkno = xp->xb_blkno;
17245 
17246 	/*
17247 	 * Now try to get the error block number from the sense data
17248 	 */
17249 	sensep = xp->xb_sense_data;
17250 
17251 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
17252 	    (uint64_t *)&err_blkno)) {
17253 		/*
17254 		 * We retrieved the error block number from the information
17255 		 * portion of the sense data.
17256 		 *
17257 		 * For USCSI commands we are better off using the error
17258 		 * block no. as the requested block no. (This is the best
17259 		 * we can estimate.)
17260 		 */
17261 		if ((SD_IS_BUFIO(xp) == FALSE) &&
17262 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
17263 			request_blkno = err_blkno;
17264 		}
17265 	} else {
17266 		/*
17267 		 * Without the es_valid bit set (for fixed format) or an
17268 		 * information descriptor (for descriptor format) we cannot
17269 		 * be certain of the error blkno, so just use the
17270 		 * request_blkno.
17271 		 */
17272 		err_blkno = (diskaddr_t)request_blkno;
17273 	}
17274 
17275 	/*
17276 	 * The following will log the buffer contents for the release driver
17277 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
17278 	 * level is set to verbose.
17279 	 */
17280 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
17281 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17282 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
17283 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
17284 
17285 	if (pfa_flag == FALSE) {
17286 		/* This is normally only set for USCSI */
17287 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
17288 			return;
17289 		}
17290 
17291 		if ((SD_IS_BUFIO(xp) == TRUE) &&
17292 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
17293 		    (severity < sd_error_level))) {
17294 			return;
17295 		}
17296 	}
17297 	/*
17298 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
17299 	 */
17300 	if ((SD_IS_LSI(un)) &&
17301 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
17302 	    (scsi_sense_asc(sensep) == 0x94) &&
17303 	    (scsi_sense_ascq(sensep) == 0x01)) {
17304 		un->un_sonoma_failure_count++;
17305 		if (un->un_sonoma_failure_count > 1) {
17306 			return;
17307 		}
17308 	}
17309 
17310 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP ||
17311 	    ((scsi_sense_key(sensep) == KEY_RECOVERABLE_ERROR) &&
17312 	    (pktp->pkt_resid == 0))) {
17313 		scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
17314 		    request_blkno, err_blkno, scsi_cmds,
17315 		    (struct scsi_extended_sense *)sensep,
17316 		    un->un_additional_codes, NULL);
17317 	}
17318 }
17319 
17320 /*
17321  *    Function: sd_sense_key_no_sense
17322  *
17323  * Description: Recovery action when sense data was not received.
17324  *
17325  *     Context: May be called from interrupt context
17326  */
17327 
17328 static void
17329 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
17330 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17331 {
17332 	struct sd_sense_info	si;
17333 
17334 	ASSERT(un != NULL);
17335 	ASSERT(mutex_owned(SD_MUTEX(un)));
17336 	ASSERT(bp != NULL);
17337 	ASSERT(xp != NULL);
17338 	ASSERT(pktp != NULL);
17339 
17340 	si.ssi_severity = SCSI_ERR_FATAL;
17341 	si.ssi_pfa_flag = FALSE;
17342 
17343 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
17344 
17345 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17346 	    &si, EIO, (clock_t)0, NULL);
17347 }
17348 
17349 
17350 /*
17351  *    Function: sd_sense_key_recoverable_error
17352  *
17353  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
17354  *
17355  *     Context: May be called from interrupt context
17356  */
17357 
17358 static void
17359 sd_sense_key_recoverable_error(struct sd_lun *un,
17360 	uint8_t *sense_datap,
17361 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17362 {
17363 	struct sd_sense_info	si;
17364 	uint8_t asc = scsi_sense_asc(sense_datap);
17365 
17366 	ASSERT(un != NULL);
17367 	ASSERT(mutex_owned(SD_MUTEX(un)));
17368 	ASSERT(bp != NULL);
17369 	ASSERT(xp != NULL);
17370 	ASSERT(pktp != NULL);
17371 
17372 	/*
17373 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
17374 	 */
17375 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
17376 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
17377 		si.ssi_severity = SCSI_ERR_INFO;
17378 		si.ssi_pfa_flag = TRUE;
17379 	} else {
17380 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
17381 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
17382 		si.ssi_severity = SCSI_ERR_RECOVERED;
17383 		si.ssi_pfa_flag = FALSE;
17384 	}
17385 
17386 	if (pktp->pkt_resid == 0) {
17387 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17388 		sd_return_command(un, bp);
17389 		return;
17390 	}
17391 
17392 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17393 	    &si, EIO, (clock_t)0, NULL);
17394 }
17395 
17396 
17397 
17398 
17399 /*
17400  *    Function: sd_sense_key_not_ready
17401  *
17402  * Description: Recovery actions for a SCSI "Not Ready" sense key.
17403  *
17404  *     Context: May be called from interrupt context
17405  */
17406 
17407 static void
17408 sd_sense_key_not_ready(struct sd_lun *un,
17409 	uint8_t *sense_datap,
17410 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17411 {
17412 	struct sd_sense_info	si;
17413 	uint8_t asc = scsi_sense_asc(sense_datap);
17414 	uint8_t ascq = scsi_sense_ascq(sense_datap);
17415 
17416 	ASSERT(un != NULL);
17417 	ASSERT(mutex_owned(SD_MUTEX(un)));
17418 	ASSERT(bp != NULL);
17419 	ASSERT(xp != NULL);
17420 	ASSERT(pktp != NULL);
17421 
17422 	si.ssi_severity = SCSI_ERR_FATAL;
17423 	si.ssi_pfa_flag = FALSE;
17424 
17425 	/*
17426 	 * Update error stats after first NOT READY error. Disks may have
17427 	 * been powered down and may need to be restarted.  For CDROMs,
17428 	 * report NOT READY errors only if media is present.
17429 	 */
17430 	if ((ISCD(un) && (asc == 0x3A)) ||
17431 	    (xp->xb_nr_retry_count > 0)) {
17432 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17433 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
17434 	}
17435 
17436 	/*
17437 	 * Just fail if the "not ready" retry limit has been reached.
17438 	 */
17439 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
17440 		/* Special check for error message printing for removables. */
17441 		if (un->un_f_has_removable_media && (asc == 0x04) &&
17442 		    (ascq >= 0x04)) {
17443 			si.ssi_severity = SCSI_ERR_ALL;
17444 		}
17445 		goto fail_command;
17446 	}
17447 
17448 	/*
17449 	 * Check the ASC and ASCQ in the sense data as needed, to determine
17450 	 * what to do.
17451 	 */
17452 	switch (asc) {
17453 	case 0x04:	/* LOGICAL UNIT NOT READY */
17454 		/*
17455 		 * disk drives that don't spin up result in a very long delay
17456 		 * in format without warning messages. We will log a message
17457 		 * if the error level is set to verbose.
17458 		 */
17459 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
17460 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17461 			    "logical unit not ready, resetting disk\n");
17462 		}
17463 
17464 		/*
17465 		 * There are different requirements for CDROMs and disks for
17466 		 * the number of retries.  If a CD-ROM is giving this, it is
17467 		 * probably reading TOC and is in the process of getting
17468 		 * ready, so we should keep on trying for a long time to make
17469 		 * sure that all types of media are taken in account (for
17470 		 * some media the drive takes a long time to read TOC).  For
17471 		 * disks we do not want to retry this too many times as this
17472 		 * can cause a long hang in format when the drive refuses to
17473 		 * spin up (a very common failure).
17474 		 */
17475 		switch (ascq) {
17476 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
17477 			/*
17478 			 * Disk drives frequently refuse to spin up which
17479 			 * results in a very long hang in format without
17480 			 * warning messages.
17481 			 *
17482 			 * Note: This code preserves the legacy behavior of
17483 			 * comparing xb_nr_retry_count against zero for fibre
17484 			 * channel targets instead of comparing against the
17485 			 * un_reset_retry_count value.  The reason for this
17486 			 * discrepancy has been so utterly lost beneath the
17487 			 * Sands of Time that even Indiana Jones could not
17488 			 * find it.
17489 			 */
17490 			if (un->un_f_is_fibre == TRUE) {
17491 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
17492 				    (xp->xb_nr_retry_count > 0)) &&
17493 				    (un->un_startstop_timeid == NULL)) {
17494 					scsi_log(SD_DEVINFO(un), sd_label,
17495 					    CE_WARN, "logical unit not ready, "
17496 					    "resetting disk\n");
17497 					sd_reset_target(un, pktp);
17498 				}
17499 			} else {
17500 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
17501 				    (xp->xb_nr_retry_count >
17502 				    un->un_reset_retry_count)) &&
17503 				    (un->un_startstop_timeid == NULL)) {
17504 					scsi_log(SD_DEVINFO(un), sd_label,
17505 					    CE_WARN, "logical unit not ready, "
17506 					    "resetting disk\n");
17507 					sd_reset_target(un, pktp);
17508 				}
17509 			}
17510 			break;
17511 
17512 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
17513 			/*
17514 			 * If the target is in the process of becoming
17515 			 * ready, just proceed with the retry. This can
17516 			 * happen with CD-ROMs that take a long time to
17517 			 * read TOC after a power cycle or reset.
17518 			 */
17519 			goto do_retry;
17520 
17521 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
17522 			break;
17523 
17524 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
17525 			/*
17526 			 * Retries cannot help here so just fail right away.
17527 			 */
17528 			goto fail_command;
17529 
17530 		case 0x88:
17531 			/*
17532 			 * Vendor-unique code for T3/T4: it indicates a
17533 			 * path problem in a mutipathed config, but as far as
17534 			 * the target driver is concerned it equates to a fatal
17535 			 * error, so we should just fail the command right away
17536 			 * (without printing anything to the console). If this
17537 			 * is not a T3/T4, fall thru to the default recovery
17538 			 * action.
17539 			 * T3/T4 is FC only, don't need to check is_fibre
17540 			 */
17541 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
17542 				sd_return_failed_command(un, bp, EIO);
17543 				return;
17544 			}
17545 			/* FALLTHRU */
17546 
17547 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
17548 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
17549 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
17550 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
17551 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
17552 		default:    /* Possible future codes in SCSI spec? */
17553 			/*
17554 			 * For removable-media devices, do not retry if
17555 			 * ASCQ > 2 as these result mostly from USCSI commands
17556 			 * on MMC devices issued to check status of an
17557 			 * operation initiated in immediate mode.  Also for
17558 			 * ASCQ >= 4 do not print console messages as these
17559 			 * mainly represent a user-initiated operation
17560 			 * instead of a system failure.
17561 			 */
17562 			if (un->un_f_has_removable_media) {
17563 				si.ssi_severity = SCSI_ERR_ALL;
17564 				goto fail_command;
17565 			}
17566 			break;
17567 		}
17568 
17569 		/*
17570 		 * As part of our recovery attempt for the NOT READY
17571 		 * condition, we issue a START STOP UNIT command. However
17572 		 * we want to wait for a short delay before attempting this
17573 		 * as there may still be more commands coming back from the
17574 		 * target with the check condition. To do this we use
17575 		 * timeout(9F) to call sd_start_stop_unit_callback() after
17576 		 * the delay interval expires. (sd_start_stop_unit_callback()
17577 		 * dispatches sd_start_stop_unit_task(), which will issue
17578 		 * the actual START STOP UNIT command. The delay interval
17579 		 * is one-half of the delay that we will use to retry the
17580 		 * command that generated the NOT READY condition.
17581 		 *
17582 		 * Note that we could just dispatch sd_start_stop_unit_task()
17583 		 * from here and allow it to sleep for the delay interval,
17584 		 * but then we would be tying up the taskq thread
17585 		 * uncesessarily for the duration of the delay.
17586 		 *
17587 		 * Do not issue the START STOP UNIT if the current command
17588 		 * is already a START STOP UNIT.
17589 		 */
17590 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
17591 			break;
17592 		}
17593 
17594 		/*
17595 		 * Do not schedule the timeout if one is already pending.
17596 		 */
17597 		if (un->un_startstop_timeid != NULL) {
17598 			SD_INFO(SD_LOG_ERROR, un,
17599 			    "sd_sense_key_not_ready: restart already issued to"
17600 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
17601 			    ddi_get_instance(SD_DEVINFO(un)));
17602 			break;
17603 		}
17604 
17605 		/*
17606 		 * Schedule the START STOP UNIT command, then queue the command
17607 		 * for a retry.
17608 		 *
17609 		 * Note: A timeout is not scheduled for this retry because we
17610 		 * want the retry to be serial with the START_STOP_UNIT. The
17611 		 * retry will be started when the START_STOP_UNIT is completed
17612 		 * in sd_start_stop_unit_task.
17613 		 */
17614 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
17615 		    un, un->un_busy_timeout / 2);
17616 		xp->xb_nr_retry_count++;
17617 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
17618 		return;
17619 
17620 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
17621 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
17622 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17623 			    "unit does not respond to selection\n");
17624 		}
17625 		break;
17626 
17627 	case 0x3A:	/* MEDIUM NOT PRESENT */
17628 		if (sd_error_level >= SCSI_ERR_FATAL) {
17629 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17630 			    "Caddy not inserted in drive\n");
17631 		}
17632 
17633 		sr_ejected(un);
17634 		un->un_mediastate = DKIO_EJECTED;
17635 		/* The state has changed, inform the media watch routines */
17636 		cv_broadcast(&un->un_state_cv);
17637 		/* Just fail if no media is present in the drive. */
17638 		goto fail_command;
17639 
17640 	default:
17641 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
17642 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
17643 			    "Unit not Ready. Additional sense code 0x%x\n",
17644 			    asc);
17645 		}
17646 		break;
17647 	}
17648 
17649 do_retry:
17650 
17651 	/*
17652 	 * Retry the command, as some targets may report NOT READY for
17653 	 * several seconds after being reset.
17654 	 */
17655 	xp->xb_nr_retry_count++;
17656 	si.ssi_severity = SCSI_ERR_RETRYABLE;
17657 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17658 	    &si, EIO, un->un_busy_timeout, NULL);
17659 
17660 	return;
17661 
17662 fail_command:
17663 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17664 	sd_return_failed_command(un, bp, EIO);
17665 }
17666 
17667 
17668 
17669 /*
17670  *    Function: sd_sense_key_medium_or_hardware_error
17671  *
17672  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
17673  *		sense key.
17674  *
17675  *     Context: May be called from interrupt context
17676  */
17677 
17678 static void
17679 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
17680 	uint8_t *sense_datap,
17681 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17682 {
17683 	struct sd_sense_info	si;
17684 	uint8_t sense_key = scsi_sense_key(sense_datap);
17685 	uint8_t asc = scsi_sense_asc(sense_datap);
17686 
17687 	ASSERT(un != NULL);
17688 	ASSERT(mutex_owned(SD_MUTEX(un)));
17689 	ASSERT(bp != NULL);
17690 	ASSERT(xp != NULL);
17691 	ASSERT(pktp != NULL);
17692 
17693 	si.ssi_severity = SCSI_ERR_FATAL;
17694 	si.ssi_pfa_flag = FALSE;
17695 
17696 	if (sense_key == KEY_MEDIUM_ERROR) {
17697 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
17698 	}
17699 
17700 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17701 
17702 	if ((un->un_reset_retry_count != 0) &&
17703 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
17704 		mutex_exit(SD_MUTEX(un));
17705 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
17706 		if (un->un_f_allow_bus_device_reset == TRUE) {
17707 
17708 			boolean_t try_resetting_target = B_TRUE;
17709 
17710 			/*
17711 			 * We need to be able to handle specific ASC when we are
17712 			 * handling a KEY_HARDWARE_ERROR. In particular
17713 			 * taking the default action of resetting the target may
17714 			 * not be the appropriate way to attempt recovery.
17715 			 * Resetting a target because of a single LUN failure
17716 			 * victimizes all LUNs on that target.
17717 			 *
17718 			 * This is true for the LSI arrays, if an LSI
17719 			 * array controller returns an ASC of 0x84 (LUN Dead) we
17720 			 * should trust it.
17721 			 */
17722 
17723 			if (sense_key == KEY_HARDWARE_ERROR) {
17724 				switch (asc) {
17725 				case 0x84:
17726 					if (SD_IS_LSI(un)) {
17727 						try_resetting_target = B_FALSE;
17728 					}
17729 					break;
17730 				default:
17731 					break;
17732 				}
17733 			}
17734 
17735 			if (try_resetting_target == B_TRUE) {
17736 				int reset_retval = 0;
17737 				if (un->un_f_lun_reset_enabled == TRUE) {
17738 					SD_TRACE(SD_LOG_IO_CORE, un,
17739 					    "sd_sense_key_medium_or_hardware_"
17740 					    "error: issuing RESET_LUN\n");
17741 					reset_retval =
17742 					    scsi_reset(SD_ADDRESS(un),
17743 					    RESET_LUN);
17744 				}
17745 				if (reset_retval == 0) {
17746 					SD_TRACE(SD_LOG_IO_CORE, un,
17747 					    "sd_sense_key_medium_or_hardware_"
17748 					    "error: issuing RESET_TARGET\n");
17749 					(void) scsi_reset(SD_ADDRESS(un),
17750 					    RESET_TARGET);
17751 				}
17752 			}
17753 		}
17754 		mutex_enter(SD_MUTEX(un));
17755 	}
17756 
17757 	/*
17758 	 * This really ought to be a fatal error, but we will retry anyway
17759 	 * as some drives report this as a spurious error.
17760 	 */
17761 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17762 	    &si, EIO, (clock_t)0, NULL);
17763 }
17764 
17765 
17766 
17767 /*
17768  *    Function: sd_sense_key_illegal_request
17769  *
17770  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
17771  *
17772  *     Context: May be called from interrupt context
17773  */
17774 
17775 static void
17776 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
17777 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17778 {
17779 	struct sd_sense_info	si;
17780 
17781 	ASSERT(un != NULL);
17782 	ASSERT(mutex_owned(SD_MUTEX(un)));
17783 	ASSERT(bp != NULL);
17784 	ASSERT(xp != NULL);
17785 	ASSERT(pktp != NULL);
17786 
17787 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
17788 
17789 	si.ssi_severity = SCSI_ERR_INFO;
17790 	si.ssi_pfa_flag = FALSE;
17791 
17792 	/* Pointless to retry if the target thinks it's an illegal request */
17793 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17794 	sd_return_failed_command(un, bp, EIO);
17795 }
17796 
17797 
17798 
17799 
17800 /*
17801  *    Function: sd_sense_key_unit_attention
17802  *
17803  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
17804  *
17805  *     Context: May be called from interrupt context
17806  */
17807 
17808 static void
17809 sd_sense_key_unit_attention(struct sd_lun *un,
17810 	uint8_t *sense_datap,
17811 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17812 {
17813 	/*
17814 	 * For UNIT ATTENTION we allow retries for one minute. Devices
17815 	 * like Sonoma can return UNIT ATTENTION close to a minute
17816 	 * under certain conditions.
17817 	 */
17818 	int	retry_check_flag = SD_RETRIES_UA;
17819 	boolean_t	kstat_updated = B_FALSE;
17820 	struct	sd_sense_info		si;
17821 	uint8_t asc = scsi_sense_asc(sense_datap);
17822 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
17823 
17824 	ASSERT(un != NULL);
17825 	ASSERT(mutex_owned(SD_MUTEX(un)));
17826 	ASSERT(bp != NULL);
17827 	ASSERT(xp != NULL);
17828 	ASSERT(pktp != NULL);
17829 
17830 	si.ssi_severity = SCSI_ERR_INFO;
17831 	si.ssi_pfa_flag = FALSE;
17832 
17833 
17834 	switch (asc) {
17835 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
17836 		if (sd_report_pfa != 0) {
17837 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
17838 			si.ssi_pfa_flag = TRUE;
17839 			retry_check_flag = SD_RETRIES_STANDARD;
17840 			goto do_retry;
17841 		}
17842 
17843 		break;
17844 
17845 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
17846 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
17847 			un->un_resvd_status |=
17848 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
17849 		}
17850 #ifdef _LP64
17851 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
17852 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
17853 			    un, KM_NOSLEEP) == 0) {
17854 				/*
17855 				 * If we can't dispatch the task we'll just
17856 				 * live without descriptor sense.  We can
17857 				 * try again on the next "unit attention"
17858 				 */
17859 				SD_ERROR(SD_LOG_ERROR, un,
17860 				    "sd_sense_key_unit_attention: "
17861 				    "Could not dispatch "
17862 				    "sd_reenable_dsense_task\n");
17863 			}
17864 		}
17865 #endif /* _LP64 */
17866 		/* FALLTHRU */
17867 
17868 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
17869 		if (!un->un_f_has_removable_media) {
17870 			break;
17871 		}
17872 
17873 		/*
17874 		 * When we get a unit attention from a removable-media device,
17875 		 * it may be in a state that will take a long time to recover
17876 		 * (e.g., from a reset).  Since we are executing in interrupt
17877 		 * context here, we cannot wait around for the device to come
17878 		 * back. So hand this command off to sd_media_change_task()
17879 		 * for deferred processing under taskq thread context. (Note
17880 		 * that the command still may be failed if a problem is
17881 		 * encountered at a later time.)
17882 		 */
17883 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
17884 		    KM_NOSLEEP) == 0) {
17885 			/*
17886 			 * Cannot dispatch the request so fail the command.
17887 			 */
17888 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
17889 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17890 			si.ssi_severity = SCSI_ERR_FATAL;
17891 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17892 			sd_return_failed_command(un, bp, EIO);
17893 		}
17894 
17895 		/*
17896 		 * If failed to dispatch sd_media_change_task(), we already
17897 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
17898 		 * we should update kstat later if it encounters an error. So,
17899 		 * we update kstat_updated flag here.
17900 		 */
17901 		kstat_updated = B_TRUE;
17902 
17903 		/*
17904 		 * Either the command has been successfully dispatched to a
17905 		 * task Q for retrying, or the dispatch failed. In either case
17906 		 * do NOT retry again by calling sd_retry_command. This sets up
17907 		 * two retries of the same command and when one completes and
17908 		 * frees the resources the other will access freed memory,
17909 		 * a bad thing.
17910 		 */
17911 		return;
17912 
17913 	default:
17914 		break;
17915 	}
17916 
17917 	/*
17918 	 * ASC  ASCQ
17919 	 *  2A   09	Capacity data has changed
17920 	 *  2A   01	Mode parameters changed
17921 	 *  3F   0E	Reported luns data has changed
17922 	 * Arrays that support logical unit expansion should report
17923 	 * capacity changes(2Ah/09). Mode parameters changed and
17924 	 * reported luns data has changed are the approximation.
17925 	 */
17926 	if (((asc == 0x2a) && (ascq == 0x09)) ||
17927 	    ((asc == 0x2a) && (ascq == 0x01)) ||
17928 	    ((asc == 0x3f) && (ascq == 0x0e))) {
17929 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
17930 		    KM_NOSLEEP) == 0) {
17931 			SD_ERROR(SD_LOG_ERROR, un,
17932 			    "sd_sense_key_unit_attention: "
17933 			    "Could not dispatch sd_target_change_task\n");
17934 		}
17935 	}
17936 
17937 	/*
17938 	 * Update kstat if we haven't done that.
17939 	 */
17940 	if (!kstat_updated) {
17941 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17942 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17943 	}
17944 
17945 do_retry:
17946 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
17947 	    EIO, SD_UA_RETRY_DELAY, NULL);
17948 }
17949 
17950 
17951 
17952 /*
17953  *    Function: sd_sense_key_fail_command
17954  *
17955  * Description: Use to fail a command when we don't like the sense key that
17956  *		was returned.
17957  *
17958  *     Context: May be called from interrupt context
17959  */
17960 
17961 static void
17962 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
17963 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17964 {
17965 	struct sd_sense_info	si;
17966 
17967 	ASSERT(un != NULL);
17968 	ASSERT(mutex_owned(SD_MUTEX(un)));
17969 	ASSERT(bp != NULL);
17970 	ASSERT(xp != NULL);
17971 	ASSERT(pktp != NULL);
17972 
17973 	si.ssi_severity = SCSI_ERR_FATAL;
17974 	si.ssi_pfa_flag = FALSE;
17975 
17976 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17977 	sd_return_failed_command(un, bp, EIO);
17978 }
17979 
17980 
17981 
17982 /*
17983  *    Function: sd_sense_key_blank_check
17984  *
17985  * Description: Recovery actions for a SCSI "Blank Check" sense key.
17986  *		Has no monetary connotation.
17987  *
17988  *     Context: May be called from interrupt context
17989  */
17990 
17991 static void
17992 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
17993 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17994 {
17995 	struct sd_sense_info	si;
17996 
17997 	ASSERT(un != NULL);
17998 	ASSERT(mutex_owned(SD_MUTEX(un)));
17999 	ASSERT(bp != NULL);
18000 	ASSERT(xp != NULL);
18001 	ASSERT(pktp != NULL);
18002 
18003 	/*
18004 	 * Blank check is not fatal for removable devices, therefore
18005 	 * it does not require a console message.
18006 	 */
18007 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
18008 	    SCSI_ERR_FATAL;
18009 	si.ssi_pfa_flag = FALSE;
18010 
18011 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18012 	sd_return_failed_command(un, bp, EIO);
18013 }
18014 
18015 
18016 
18017 
18018 /*
18019  *    Function: sd_sense_key_aborted_command
18020  *
18021  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
18022  *
18023  *     Context: May be called from interrupt context
18024  */
18025 
18026 static void
18027 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
18028 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18029 {
18030 	struct sd_sense_info	si;
18031 
18032 	ASSERT(un != NULL);
18033 	ASSERT(mutex_owned(SD_MUTEX(un)));
18034 	ASSERT(bp != NULL);
18035 	ASSERT(xp != NULL);
18036 	ASSERT(pktp != NULL);
18037 
18038 	si.ssi_severity = SCSI_ERR_FATAL;
18039 	si.ssi_pfa_flag = FALSE;
18040 
18041 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18042 
18043 	/*
18044 	 * This really ought to be a fatal error, but we will retry anyway
18045 	 * as some drives report this as a spurious error.
18046 	 */
18047 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18048 	    &si, EIO, drv_usectohz(100000), NULL);
18049 }
18050 
18051 
18052 
18053 /*
18054  *    Function: sd_sense_key_default
18055  *
18056  * Description: Default recovery action for several SCSI sense keys (basically
18057  *		attempts a retry).
18058  *
18059  *     Context: May be called from interrupt context
18060  */
18061 
18062 static void
18063 sd_sense_key_default(struct sd_lun *un,
18064 	uint8_t *sense_datap,
18065 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18066 {
18067 	struct sd_sense_info	si;
18068 	uint8_t sense_key = scsi_sense_key(sense_datap);
18069 
18070 	ASSERT(un != NULL);
18071 	ASSERT(mutex_owned(SD_MUTEX(un)));
18072 	ASSERT(bp != NULL);
18073 	ASSERT(xp != NULL);
18074 	ASSERT(pktp != NULL);
18075 
18076 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18077 
18078 	/*
18079 	 * Undecoded sense key.	Attempt retries and hope that will fix
18080 	 * the problem.  Otherwise, we're dead.
18081 	 */
18082 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18083 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18084 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18085 	}
18086 
18087 	si.ssi_severity = SCSI_ERR_FATAL;
18088 	si.ssi_pfa_flag = FALSE;
18089 
18090 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18091 	    &si, EIO, (clock_t)0, NULL);
18092 }
18093 
18094 
18095 
18096 /*
18097  *    Function: sd_print_retry_msg
18098  *
18099  * Description: Print a message indicating the retry action being taken.
18100  *
18101  *   Arguments: un - ptr to associated softstate
18102  *		bp - ptr to buf(9S) for the command
18103  *		arg - not used.
18104  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18105  *			or SD_NO_RETRY_ISSUED
18106  *
18107  *     Context: May be called from interrupt context
18108  */
18109 /* ARGSUSED */
18110 static void
18111 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18112 {
18113 	struct sd_xbuf	*xp;
18114 	struct scsi_pkt *pktp;
18115 	char *reasonp;
18116 	char *msgp;
18117 
18118 	ASSERT(un != NULL);
18119 	ASSERT(mutex_owned(SD_MUTEX(un)));
18120 	ASSERT(bp != NULL);
18121 	pktp = SD_GET_PKTP(bp);
18122 	ASSERT(pktp != NULL);
18123 	xp = SD_GET_XBUF(bp);
18124 	ASSERT(xp != NULL);
18125 
18126 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18127 	mutex_enter(&un->un_pm_mutex);
18128 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18129 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18130 	    (pktp->pkt_flags & FLAG_SILENT)) {
18131 		mutex_exit(&un->un_pm_mutex);
18132 		goto update_pkt_reason;
18133 	}
18134 	mutex_exit(&un->un_pm_mutex);
18135 
18136 	/*
18137 	 * Suppress messages if they are all the same pkt_reason; with
18138 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18139 	 * If we are in panic, then suppress the retry messages.
18140 	 */
18141 	switch (flag) {
18142 	case SD_NO_RETRY_ISSUED:
18143 		msgp = "giving up";
18144 		break;
18145 	case SD_IMMEDIATE_RETRY_ISSUED:
18146 	case SD_DELAYED_RETRY_ISSUED:
18147 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18148 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18149 		    (sd_error_level != SCSI_ERR_ALL))) {
18150 			return;
18151 		}
18152 		msgp = "retrying command";
18153 		break;
18154 	default:
18155 		goto update_pkt_reason;
18156 	}
18157 
18158 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18159 	    scsi_rname(pktp->pkt_reason));
18160 
18161 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
18162 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18163 		    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18164 	}
18165 
18166 update_pkt_reason:
18167 	/*
18168 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18169 	 * This is to prevent multiple console messages for the same failure
18170 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18171 	 * when the command is retried successfully because there still may be
18172 	 * more commands coming back with the same value of pktp->pkt_reason.
18173 	 */
18174 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18175 		un->un_last_pkt_reason = pktp->pkt_reason;
18176 	}
18177 }
18178 
18179 
18180 /*
18181  *    Function: sd_print_cmd_incomplete_msg
18182  *
18183  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18184  *
18185  *   Arguments: un - ptr to associated softstate
18186  *		bp - ptr to buf(9S) for the command
18187  *		arg - passed to sd_print_retry_msg()
18188  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18189  *			or SD_NO_RETRY_ISSUED
18190  *
18191  *     Context: May be called from interrupt context
18192  */
18193 
18194 static void
18195 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18196 	int code)
18197 {
18198 	dev_info_t	*dip;
18199 
18200 	ASSERT(un != NULL);
18201 	ASSERT(mutex_owned(SD_MUTEX(un)));
18202 	ASSERT(bp != NULL);
18203 
18204 	switch (code) {
18205 	case SD_NO_RETRY_ISSUED:
18206 		/* Command was failed. Someone turned off this target? */
18207 		if (un->un_state != SD_STATE_OFFLINE) {
18208 			/*
18209 			 * Suppress message if we are detaching and
18210 			 * device has been disconnected
18211 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
18212 			 * private interface and not part of the DDI
18213 			 */
18214 			dip = un->un_sd->sd_dev;
18215 			if (!(DEVI_IS_DETACHING(dip) &&
18216 			    DEVI_IS_DEVICE_REMOVED(dip))) {
18217 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18218 				"disk not responding to selection\n");
18219 			}
18220 			New_state(un, SD_STATE_OFFLINE);
18221 		}
18222 		break;
18223 
18224 	case SD_DELAYED_RETRY_ISSUED:
18225 	case SD_IMMEDIATE_RETRY_ISSUED:
18226 	default:
18227 		/* Command was successfully queued for retry */
18228 		sd_print_retry_msg(un, bp, arg, code);
18229 		break;
18230 	}
18231 }
18232 
18233 
18234 /*
18235  *    Function: sd_pkt_reason_cmd_incomplete
18236  *
18237  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
18238  *
18239  *     Context: May be called from interrupt context
18240  */
18241 
18242 static void
18243 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
18244 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18245 {
18246 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
18247 
18248 	ASSERT(un != NULL);
18249 	ASSERT(mutex_owned(SD_MUTEX(un)));
18250 	ASSERT(bp != NULL);
18251 	ASSERT(xp != NULL);
18252 	ASSERT(pktp != NULL);
18253 
18254 	/* Do not do a reset if selection did not complete */
18255 	/* Note: Should this not just check the bit? */
18256 	if (pktp->pkt_state != STATE_GOT_BUS) {
18257 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18258 		sd_reset_target(un, pktp);
18259 	}
18260 
18261 	/*
18262 	 * If the target was not successfully selected, then set
18263 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
18264 	 * with the target, and further retries and/or commands are
18265 	 * likely to take a long time.
18266 	 */
18267 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
18268 		flag |= SD_RETRIES_FAILFAST;
18269 	}
18270 
18271 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18272 
18273 	sd_retry_command(un, bp, flag,
18274 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18275 }
18276 
18277 
18278 
18279 /*
18280  *    Function: sd_pkt_reason_cmd_tran_err
18281  *
18282  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
18283  *
18284  *     Context: May be called from interrupt context
18285  */
18286 
18287 static void
18288 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
18289 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18290 {
18291 	ASSERT(un != NULL);
18292 	ASSERT(mutex_owned(SD_MUTEX(un)));
18293 	ASSERT(bp != NULL);
18294 	ASSERT(xp != NULL);
18295 	ASSERT(pktp != NULL);
18296 
18297 	/*
18298 	 * Do not reset if we got a parity error, or if
18299 	 * selection did not complete.
18300 	 */
18301 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18302 	/* Note: Should this not just check the bit for pkt_state? */
18303 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
18304 	    (pktp->pkt_state != STATE_GOT_BUS)) {
18305 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18306 		sd_reset_target(un, pktp);
18307 	}
18308 
18309 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18310 
18311 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18312 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18313 }
18314 
18315 
18316 
18317 /*
18318  *    Function: sd_pkt_reason_cmd_reset
18319  *
18320  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
18321  *
18322  *     Context: May be called from interrupt context
18323  */
18324 
18325 static void
18326 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
18327 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18328 {
18329 	ASSERT(un != NULL);
18330 	ASSERT(mutex_owned(SD_MUTEX(un)));
18331 	ASSERT(bp != NULL);
18332 	ASSERT(xp != NULL);
18333 	ASSERT(pktp != NULL);
18334 
18335 	/* The target may still be running the command, so try to reset. */
18336 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18337 	sd_reset_target(un, pktp);
18338 
18339 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18340 
18341 	/*
18342 	 * If pkt_reason is CMD_RESET chances are that this pkt got
18343 	 * reset because another target on this bus caused it. The target
18344 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18345 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18346 	 */
18347 
18348 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18349 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18350 }
18351 
18352 
18353 
18354 
18355 /*
18356  *    Function: sd_pkt_reason_cmd_aborted
18357  *
18358  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
18359  *
18360  *     Context: May be called from interrupt context
18361  */
18362 
18363 static void
18364 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
18365 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18366 {
18367 	ASSERT(un != NULL);
18368 	ASSERT(mutex_owned(SD_MUTEX(un)));
18369 	ASSERT(bp != NULL);
18370 	ASSERT(xp != NULL);
18371 	ASSERT(pktp != NULL);
18372 
18373 	/* The target may still be running the command, so try to reset. */
18374 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18375 	sd_reset_target(un, pktp);
18376 
18377 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18378 
18379 	/*
18380 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
18381 	 * aborted because another target on this bus caused it. The target
18382 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18383 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18384 	 */
18385 
18386 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18387 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18388 }
18389 
18390 
18391 
18392 /*
18393  *    Function: sd_pkt_reason_cmd_timeout
18394  *
18395  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
18396  *
18397  *     Context: May be called from interrupt context
18398  */
18399 
18400 static void
18401 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
18402 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18403 {
18404 	ASSERT(un != NULL);
18405 	ASSERT(mutex_owned(SD_MUTEX(un)));
18406 	ASSERT(bp != NULL);
18407 	ASSERT(xp != NULL);
18408 	ASSERT(pktp != NULL);
18409 
18410 
18411 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18412 	sd_reset_target(un, pktp);
18413 
18414 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18415 
18416 	/*
18417 	 * A command timeout indicates that we could not establish
18418 	 * communication with the target, so set SD_RETRIES_FAILFAST
18419 	 * as further retries/commands are likely to take a long time.
18420 	 */
18421 	sd_retry_command(un, bp,
18422 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
18423 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18424 }
18425 
18426 
18427 
18428 /*
18429  *    Function: sd_pkt_reason_cmd_unx_bus_free
18430  *
18431  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
18432  *
18433  *     Context: May be called from interrupt context
18434  */
18435 
18436 static void
18437 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
18438 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18439 {
18440 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
18441 
18442 	ASSERT(un != NULL);
18443 	ASSERT(mutex_owned(SD_MUTEX(un)));
18444 	ASSERT(bp != NULL);
18445 	ASSERT(xp != NULL);
18446 	ASSERT(pktp != NULL);
18447 
18448 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18449 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18450 
18451 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
18452 	    sd_print_retry_msg : NULL;
18453 
18454 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18455 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18456 }
18457 
18458 
18459 /*
18460  *    Function: sd_pkt_reason_cmd_tag_reject
18461  *
18462  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
18463  *
18464  *     Context: May be called from interrupt context
18465  */
18466 
18467 static void
18468 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
18469 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18470 {
18471 	ASSERT(un != NULL);
18472 	ASSERT(mutex_owned(SD_MUTEX(un)));
18473 	ASSERT(bp != NULL);
18474 	ASSERT(xp != NULL);
18475 	ASSERT(pktp != NULL);
18476 
18477 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18478 	pktp->pkt_flags = 0;
18479 	un->un_tagflags = 0;
18480 	if (un->un_f_opt_queueing == TRUE) {
18481 		un->un_throttle = min(un->un_throttle, 3);
18482 	} else {
18483 		un->un_throttle = 1;
18484 	}
18485 	mutex_exit(SD_MUTEX(un));
18486 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
18487 	mutex_enter(SD_MUTEX(un));
18488 
18489 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18490 
18491 	/* Legacy behavior not to check retry counts here. */
18492 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
18493 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18494 }
18495 
18496 
18497 /*
18498  *    Function: sd_pkt_reason_default
18499  *
18500  * Description: Default recovery actions for SCSA pkt_reason values that
18501  *		do not have more explicit recovery actions.
18502  *
18503  *     Context: May be called from interrupt context
18504  */
18505 
18506 static void
18507 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
18508 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18509 {
18510 	ASSERT(un != NULL);
18511 	ASSERT(mutex_owned(SD_MUTEX(un)));
18512 	ASSERT(bp != NULL);
18513 	ASSERT(xp != NULL);
18514 	ASSERT(pktp != NULL);
18515 
18516 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18517 	sd_reset_target(un, pktp);
18518 
18519 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18520 
18521 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18522 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18523 }
18524 
18525 
18526 
18527 /*
18528  *    Function: sd_pkt_status_check_condition
18529  *
18530  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
18531  *
18532  *     Context: May be called from interrupt context
18533  */
18534 
18535 static void
18536 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
18537 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18538 {
18539 	ASSERT(un != NULL);
18540 	ASSERT(mutex_owned(SD_MUTEX(un)));
18541 	ASSERT(bp != NULL);
18542 	ASSERT(xp != NULL);
18543 	ASSERT(pktp != NULL);
18544 
18545 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
18546 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
18547 
18548 	/*
18549 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
18550 	 * command will be retried after the request sense). Otherwise, retry
18551 	 * the command. Note: we are issuing the request sense even though the
18552 	 * retry limit may have been reached for the failed command.
18553 	 */
18554 	if (un->un_f_arq_enabled == FALSE) {
18555 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
18556 		    "no ARQ, sending request sense command\n");
18557 		sd_send_request_sense_command(un, bp, pktp);
18558 	} else {
18559 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
18560 		    "ARQ,retrying request sense command\n");
18561 #if defined(__i386) || defined(__amd64)
18562 		/*
18563 		 * The SD_RETRY_DELAY value need to be adjusted here
18564 		 * when SD_RETRY_DELAY change in sddef.h
18565 		 */
18566 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
18567 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
18568 		    NULL);
18569 #else
18570 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
18571 		    EIO, SD_RETRY_DELAY, NULL);
18572 #endif
18573 	}
18574 
18575 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
18576 }
18577 
18578 
18579 /*
18580  *    Function: sd_pkt_status_busy
18581  *
18582  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
18583  *
18584  *     Context: May be called from interrupt context
18585  */
18586 
18587 static void
18588 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18589 	struct scsi_pkt *pktp)
18590 {
18591 	ASSERT(un != NULL);
18592 	ASSERT(mutex_owned(SD_MUTEX(un)));
18593 	ASSERT(bp != NULL);
18594 	ASSERT(xp != NULL);
18595 	ASSERT(pktp != NULL);
18596 
18597 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18598 	    "sd_pkt_status_busy: entry\n");
18599 
18600 	/* If retries are exhausted, just fail the command. */
18601 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
18602 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18603 		    "device busy too long\n");
18604 		sd_return_failed_command(un, bp, EIO);
18605 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18606 		    "sd_pkt_status_busy: exit\n");
18607 		return;
18608 	}
18609 	xp->xb_retry_count++;
18610 
18611 	/*
18612 	 * Try to reset the target. However, we do not want to perform
18613 	 * more than one reset if the device continues to fail. The reset
18614 	 * will be performed when the retry count reaches the reset
18615 	 * threshold.  This threshold should be set such that at least
18616 	 * one retry is issued before the reset is performed.
18617 	 */
18618 	if (xp->xb_retry_count ==
18619 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
18620 		int rval = 0;
18621 		mutex_exit(SD_MUTEX(un));
18622 		if (un->un_f_allow_bus_device_reset == TRUE) {
18623 			/*
18624 			 * First try to reset the LUN; if we cannot then
18625 			 * try to reset the target.
18626 			 */
18627 			if (un->un_f_lun_reset_enabled == TRUE) {
18628 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18629 				    "sd_pkt_status_busy: RESET_LUN\n");
18630 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
18631 			}
18632 			if (rval == 0) {
18633 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18634 				    "sd_pkt_status_busy: RESET_TARGET\n");
18635 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
18636 			}
18637 		}
18638 		if (rval == 0) {
18639 			/*
18640 			 * If the RESET_LUN and/or RESET_TARGET failed,
18641 			 * try RESET_ALL
18642 			 */
18643 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18644 			    "sd_pkt_status_busy: RESET_ALL\n");
18645 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
18646 		}
18647 		mutex_enter(SD_MUTEX(un));
18648 		if (rval == 0) {
18649 			/*
18650 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
18651 			 * At this point we give up & fail the command.
18652 			 */
18653 			sd_return_failed_command(un, bp, EIO);
18654 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18655 			    "sd_pkt_status_busy: exit (failed cmd)\n");
18656 			return;
18657 		}
18658 	}
18659 
18660 	/*
18661 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
18662 	 * we have already checked the retry counts above.
18663 	 */
18664 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
18665 	    EIO, un->un_busy_timeout, NULL);
18666 
18667 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18668 	    "sd_pkt_status_busy: exit\n");
18669 }
18670 
18671 
18672 /*
18673  *    Function: sd_pkt_status_reservation_conflict
18674  *
18675  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
18676  *		command status.
18677  *
18678  *     Context: May be called from interrupt context
18679  */
18680 
18681 static void
18682 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
18683 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18684 {
18685 	ASSERT(un != NULL);
18686 	ASSERT(mutex_owned(SD_MUTEX(un)));
18687 	ASSERT(bp != NULL);
18688 	ASSERT(xp != NULL);
18689 	ASSERT(pktp != NULL);
18690 
18691 	/*
18692 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
18693 	 * conflict could be due to various reasons like incorrect keys, not
18694 	 * registered or not reserved etc. So, we return EACCES to the caller.
18695 	 */
18696 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
18697 		int cmd = SD_GET_PKT_OPCODE(pktp);
18698 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
18699 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
18700 			sd_return_failed_command(un, bp, EACCES);
18701 			return;
18702 		}
18703 	}
18704 
18705 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
18706 
18707 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
18708 		if (sd_failfast_enable != 0) {
18709 			/* By definition, we must panic here.... */
18710 			sd_panic_for_res_conflict(un);
18711 			/*NOTREACHED*/
18712 		}
18713 		SD_ERROR(SD_LOG_IO, un,
18714 		    "sd_handle_resv_conflict: Disk Reserved\n");
18715 		sd_return_failed_command(un, bp, EACCES);
18716 		return;
18717 	}
18718 
18719 	/*
18720 	 * 1147670: retry only if sd_retry_on_reservation_conflict
18721 	 * property is set (default is 1). Retries will not succeed
18722 	 * on a disk reserved by another initiator. HA systems
18723 	 * may reset this via sd.conf to avoid these retries.
18724 	 *
18725 	 * Note: The legacy return code for this failure is EIO, however EACCES
18726 	 * seems more appropriate for a reservation conflict.
18727 	 */
18728 	if (sd_retry_on_reservation_conflict == 0) {
18729 		SD_ERROR(SD_LOG_IO, un,
18730 		    "sd_handle_resv_conflict: Device Reserved\n");
18731 		sd_return_failed_command(un, bp, EIO);
18732 		return;
18733 	}
18734 
18735 	/*
18736 	 * Retry the command if we can.
18737 	 *
18738 	 * Note: The legacy return code for this failure is EIO, however EACCES
18739 	 * seems more appropriate for a reservation conflict.
18740 	 */
18741 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
18742 	    (clock_t)2, NULL);
18743 }
18744 
18745 
18746 
18747 /*
18748  *    Function: sd_pkt_status_qfull
18749  *
18750  * Description: Handle a QUEUE FULL condition from the target.  This can
18751  *		occur if the HBA does not handle the queue full condition.
18752  *		(Basically this means third-party HBAs as Sun HBAs will
18753  *		handle the queue full condition.)  Note that if there are
18754  *		some commands already in the transport, then the queue full
18755  *		has occurred because the queue for this nexus is actually
18756  *		full. If there are no commands in the transport, then the
18757  *		queue full is resulting from some other initiator or lun
18758  *		consuming all the resources at the target.
18759  *
18760  *     Context: May be called from interrupt context
18761  */
18762 
18763 static void
18764 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
18765 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18766 {
18767 	ASSERT(un != NULL);
18768 	ASSERT(mutex_owned(SD_MUTEX(un)));
18769 	ASSERT(bp != NULL);
18770 	ASSERT(xp != NULL);
18771 	ASSERT(pktp != NULL);
18772 
18773 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18774 	    "sd_pkt_status_qfull: entry\n");
18775 
18776 	/*
18777 	 * Just lower the QFULL throttle and retry the command.  Note that
18778 	 * we do not limit the number of retries here.
18779 	 */
18780 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
18781 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
18782 	    SD_RESTART_TIMEOUT, NULL);
18783 
18784 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18785 	    "sd_pkt_status_qfull: exit\n");
18786 }
18787 
18788 
18789 /*
18790  *    Function: sd_reset_target
18791  *
18792  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
18793  *		RESET_TARGET, or RESET_ALL.
18794  *
18795  *     Context: May be called under interrupt context.
18796  */
18797 
18798 static void
18799 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
18800 {
18801 	int rval = 0;
18802 
18803 	ASSERT(un != NULL);
18804 	ASSERT(mutex_owned(SD_MUTEX(un)));
18805 	ASSERT(pktp != NULL);
18806 
18807 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
18808 
18809 	/*
18810 	 * No need to reset if the transport layer has already done so.
18811 	 */
18812 	if ((pktp->pkt_statistics &
18813 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
18814 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18815 		    "sd_reset_target: no reset\n");
18816 		return;
18817 	}
18818 
18819 	mutex_exit(SD_MUTEX(un));
18820 
18821 	if (un->un_f_allow_bus_device_reset == TRUE) {
18822 		if (un->un_f_lun_reset_enabled == TRUE) {
18823 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18824 			    "sd_reset_target: RESET_LUN\n");
18825 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
18826 		}
18827 		if (rval == 0) {
18828 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18829 			    "sd_reset_target: RESET_TARGET\n");
18830 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
18831 		}
18832 	}
18833 
18834 	if (rval == 0) {
18835 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18836 		    "sd_reset_target: RESET_ALL\n");
18837 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
18838 	}
18839 
18840 	mutex_enter(SD_MUTEX(un));
18841 
18842 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
18843 }
18844 
18845 /*
18846  *    Function: sd_target_change_task
18847  *
18848  * Description: Handle dynamic target change
18849  *
18850  *     Context: Executes in a taskq() thread context
18851  */
18852 static void
18853 sd_target_change_task(void *arg)
18854 {
18855 	struct sd_lun		*un = arg;
18856 	uint64_t		capacity;
18857 	diskaddr_t		label_cap;
18858 	uint_t			lbasize;
18859 	sd_ssc_t		*ssc;
18860 
18861 	ASSERT(un != NULL);
18862 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18863 
18864 	if ((un->un_f_blockcount_is_valid == FALSE) ||
18865 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
18866 		return;
18867 	}
18868 
18869 	ssc = sd_ssc_init(un);
18870 
18871 	if (sd_send_scsi_READ_CAPACITY(ssc, &capacity,
18872 	    &lbasize, SD_PATH_DIRECT) != 0) {
18873 		SD_ERROR(SD_LOG_ERROR, un,
18874 		    "sd_target_change_task: fail to read capacity\n");
18875 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
18876 		goto task_exit;
18877 	}
18878 
18879 	mutex_enter(SD_MUTEX(un));
18880 	if (capacity <= un->un_blockcount) {
18881 		mutex_exit(SD_MUTEX(un));
18882 		goto task_exit;
18883 	}
18884 
18885 	sd_update_block_info(un, lbasize, capacity);
18886 	mutex_exit(SD_MUTEX(un));
18887 
18888 	/*
18889 	 * If lun is EFI labeled and lun capacity is greater than the
18890 	 * capacity contained in the label, log a sys event.
18891 	 */
18892 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
18893 	    (void*)SD_PATH_DIRECT) == 0) {
18894 		mutex_enter(SD_MUTEX(un));
18895 		if (un->un_f_blockcount_is_valid &&
18896 		    un->un_blockcount > label_cap) {
18897 			mutex_exit(SD_MUTEX(un));
18898 			sd_log_lun_expansion_event(un, KM_SLEEP);
18899 		} else {
18900 			mutex_exit(SD_MUTEX(un));
18901 		}
18902 	}
18903 
18904 task_exit:
18905 	sd_ssc_fini(ssc);
18906 }
18907 
18908 /*
18909  *    Function: sd_log_lun_expansion_event
18910  *
18911  * Description: Log lun expansion sys event
18912  *
18913  *     Context: Never called from interrupt context
18914  */
18915 static void
18916 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
18917 {
18918 	int err;
18919 	char			*path;
18920 	nvlist_t		*dle_attr_list;
18921 
18922 	/* Allocate and build sysevent attribute list */
18923 	err = nvlist_alloc(&dle_attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
18924 	if (err != 0) {
18925 		SD_ERROR(SD_LOG_ERROR, un,
18926 		    "sd_log_lun_expansion_event: fail to allocate space\n");
18927 		return;
18928 	}
18929 
18930 	path = kmem_alloc(MAXPATHLEN, km_flag);
18931 	if (path == NULL) {
18932 		nvlist_free(dle_attr_list);
18933 		SD_ERROR(SD_LOG_ERROR, un,
18934 		    "sd_log_lun_expansion_event: fail to allocate space\n");
18935 		return;
18936 	}
18937 	/*
18938 	 * Add path attribute to identify the lun.
18939 	 * We are using minor node 'a' as the sysevent attribute.
18940 	 */
18941 	(void) snprintf(path, MAXPATHLEN, "/devices");
18942 	(void) ddi_pathname(SD_DEVINFO(un), path + strlen(path));
18943 	(void) snprintf(path + strlen(path), MAXPATHLEN - strlen(path),
18944 	    ":a");
18945 
18946 	err = nvlist_add_string(dle_attr_list, DEV_PHYS_PATH, path);
18947 	if (err != 0) {
18948 		nvlist_free(dle_attr_list);
18949 		kmem_free(path, MAXPATHLEN);
18950 		SD_ERROR(SD_LOG_ERROR, un,
18951 		    "sd_log_lun_expansion_event: fail to add attribute\n");
18952 		return;
18953 	}
18954 
18955 	/* Log dynamic lun expansion sysevent */
18956 	err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR, EC_DEV_STATUS,
18957 	    ESC_DEV_DLE, dle_attr_list, NULL, km_flag);
18958 	if (err != DDI_SUCCESS) {
18959 		SD_ERROR(SD_LOG_ERROR, un,
18960 		    "sd_log_lun_expansion_event: fail to log sysevent\n");
18961 	}
18962 
18963 	nvlist_free(dle_attr_list);
18964 	kmem_free(path, MAXPATHLEN);
18965 }
18966 
18967 /*
18968  *    Function: sd_media_change_task
18969  *
18970  * Description: Recovery action for CDROM to become available.
18971  *
18972  *     Context: Executes in a taskq() thread context
18973  */
18974 
18975 static void
18976 sd_media_change_task(void *arg)
18977 {
18978 	struct	scsi_pkt	*pktp = arg;
18979 	struct	sd_lun		*un;
18980 	struct	buf		*bp;
18981 	struct	sd_xbuf		*xp;
18982 	int	err		= 0;
18983 	int	retry_count	= 0;
18984 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
18985 	struct	sd_sense_info	si;
18986 
18987 	ASSERT(pktp != NULL);
18988 	bp = (struct buf *)pktp->pkt_private;
18989 	ASSERT(bp != NULL);
18990 	xp = SD_GET_XBUF(bp);
18991 	ASSERT(xp != NULL);
18992 	un = SD_GET_UN(bp);
18993 	ASSERT(un != NULL);
18994 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18995 	ASSERT(un->un_f_monitor_media_state);
18996 
18997 	si.ssi_severity = SCSI_ERR_INFO;
18998 	si.ssi_pfa_flag = FALSE;
18999 
19000 	/*
19001 	 * When a reset is issued on a CDROM, it takes a long time to
19002 	 * recover. First few attempts to read capacity and other things
19003 	 * related to handling unit attention fail (with a ASC 0x4 and
19004 	 * ASCQ 0x1). In that case we want to do enough retries and we want
19005 	 * to limit the retries in other cases of genuine failures like
19006 	 * no media in drive.
19007 	 */
19008 	while (retry_count++ < retry_limit) {
19009 		if ((err = sd_handle_mchange(un)) == 0) {
19010 			break;
19011 		}
19012 		if (err == EAGAIN) {
19013 			retry_limit = SD_UNIT_ATTENTION_RETRY;
19014 		}
19015 		/* Sleep for 0.5 sec. & try again */
19016 		delay(drv_usectohz(500000));
19017 	}
19018 
19019 	/*
19020 	 * Dispatch (retry or fail) the original command here,
19021 	 * along with appropriate console messages....
19022 	 *
19023 	 * Must grab the mutex before calling sd_retry_command,
19024 	 * sd_print_sense_msg and sd_return_failed_command.
19025 	 */
19026 	mutex_enter(SD_MUTEX(un));
19027 	if (err != SD_CMD_SUCCESS) {
19028 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
19029 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
19030 		si.ssi_severity = SCSI_ERR_FATAL;
19031 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
19032 		sd_return_failed_command(un, bp, EIO);
19033 	} else {
19034 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
19035 		    &si, EIO, (clock_t)0, NULL);
19036 	}
19037 	mutex_exit(SD_MUTEX(un));
19038 }
19039 
19040 
19041 
19042 /*
19043  *    Function: sd_handle_mchange
19044  *
19045  * Description: Perform geometry validation & other recovery when CDROM
19046  *		has been removed from drive.
19047  *
19048  * Return Code: 0 for success
19049  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
19050  *		sd_send_scsi_READ_CAPACITY()
19051  *
19052  *     Context: Executes in a taskq() thread context
19053  */
19054 
19055 static int
19056 sd_handle_mchange(struct sd_lun *un)
19057 {
19058 	uint64_t	capacity;
19059 	uint32_t	lbasize;
19060 	int		rval;
19061 	sd_ssc_t	*ssc;
19062 
19063 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19064 	ASSERT(un->un_f_monitor_media_state);
19065 
19066 	ssc = sd_ssc_init(un);
19067 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
19068 	    SD_PATH_DIRECT_PRIORITY);
19069 
19070 	if (rval != 0)
19071 		goto failed;
19072 
19073 	mutex_enter(SD_MUTEX(un));
19074 	sd_update_block_info(un, lbasize, capacity);
19075 
19076 	if (un->un_errstats != NULL) {
19077 		struct	sd_errstats *stp =
19078 		    (struct sd_errstats *)un->un_errstats->ks_data;
19079 		stp->sd_capacity.value.ui64 = (uint64_t)
19080 		    ((uint64_t)un->un_blockcount *
19081 		    (uint64_t)un->un_tgt_blocksize);
19082 	}
19083 
19084 	/*
19085 	 * Check if the media in the device is writable or not
19086 	 */
19087 	if (ISCD(un)) {
19088 		sd_check_for_writable_cd(ssc, SD_PATH_DIRECT_PRIORITY);
19089 	}
19090 
19091 	/*
19092 	 * Note: Maybe let the strategy/partitioning chain worry about getting
19093 	 * valid geometry.
19094 	 */
19095 	mutex_exit(SD_MUTEX(un));
19096 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
19097 
19098 
19099 	if (cmlb_validate(un->un_cmlbhandle, 0,
19100 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
19101 		sd_ssc_fini(ssc);
19102 		return (EIO);
19103 	} else {
19104 		if (un->un_f_pkstats_enabled) {
19105 			sd_set_pstats(un);
19106 			SD_TRACE(SD_LOG_IO_PARTITION, un,
19107 			    "sd_handle_mchange: un:0x%p pstats created and "
19108 			    "set\n", un);
19109 		}
19110 	}
19111 
19112 	/*
19113 	 * Try to lock the door
19114 	 */
19115 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
19116 	    SD_PATH_DIRECT_PRIORITY);
19117 failed:
19118 	if (rval != 0)
19119 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19120 	sd_ssc_fini(ssc);
19121 	return (rval);
19122 }
19123 
19124 
19125 /*
19126  *    Function: sd_send_scsi_DOORLOCK
19127  *
19128  * Description: Issue the scsi DOOR LOCK command
19129  *
19130  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19131  *                      structure for this target.
19132  *		flag  - SD_REMOVAL_ALLOW
19133  *			SD_REMOVAL_PREVENT
19134  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19135  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19136  *			to use the USCSI "direct" chain and bypass the normal
19137  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19138  *			command is issued as part of an error recovery action.
19139  *
19140  * Return Code: 0   - Success
19141  *		errno return code from sd_ssc_send()
19142  *
19143  *     Context: Can sleep.
19144  */
19145 
19146 static int
19147 sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag)
19148 {
19149 	struct scsi_extended_sense	sense_buf;
19150 	union scsi_cdb		cdb;
19151 	struct uscsi_cmd	ucmd_buf;
19152 	int			status;
19153 	struct sd_lun		*un;
19154 
19155 	ASSERT(ssc != NULL);
19156 	un = ssc->ssc_un;
19157 	ASSERT(un != NULL);
19158 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19159 
19160 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
19161 
19162 	/* already determined doorlock is not supported, fake success */
19163 	if (un->un_f_doorlock_supported == FALSE) {
19164 		return (0);
19165 	}
19166 
19167 	/*
19168 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
19169 	 * ignore the command so we can complete the eject
19170 	 * operation.
19171 	 */
19172 	if (flag == SD_REMOVAL_PREVENT) {
19173 		mutex_enter(SD_MUTEX(un));
19174 		if (un->un_f_ejecting == TRUE) {
19175 			mutex_exit(SD_MUTEX(un));
19176 			return (EAGAIN);
19177 		}
19178 		mutex_exit(SD_MUTEX(un));
19179 	}
19180 
19181 	bzero(&cdb, sizeof (cdb));
19182 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19183 
19184 	cdb.scc_cmd = SCMD_DOORLOCK;
19185 	cdb.cdb_opaque[4] = (uchar_t)flag;
19186 
19187 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19188 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19189 	ucmd_buf.uscsi_bufaddr	= NULL;
19190 	ucmd_buf.uscsi_buflen	= 0;
19191 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19192 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19193 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19194 	ucmd_buf.uscsi_timeout	= 15;
19195 
19196 	SD_TRACE(SD_LOG_IO, un,
19197 	    "sd_send_scsi_DOORLOCK: returning sd_ssc_send\n");
19198 
19199 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19200 	    UIO_SYSSPACE, path_flag);
19201 
19202 	if (status == 0)
19203 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19204 
19205 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
19206 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19207 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
19208 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19209 
19210 		/* fake success and skip subsequent doorlock commands */
19211 		un->un_f_doorlock_supported = FALSE;
19212 		return (0);
19213 	}
19214 
19215 	return (status);
19216 }
19217 
19218 /*
19219  *    Function: sd_send_scsi_READ_CAPACITY
19220  *
19221  * Description: This routine uses the scsi READ CAPACITY command to determine
19222  *		the device capacity in number of blocks and the device native
19223  *		block size. If this function returns a failure, then the
19224  *		values in *capp and *lbap are undefined.  If the capacity
19225  *		returned is 0xffffffff then the lun is too large for a
19226  *		normal READ CAPACITY command and the results of a
19227  *		READ CAPACITY 16 will be used instead.
19228  *
19229  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
19230  *		capp - ptr to unsigned 64-bit variable to receive the
19231  *			capacity value from the command.
19232  *		lbap - ptr to unsigned 32-bit varaible to receive the
19233  *			block size value from the command
19234  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19235  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19236  *			to use the USCSI "direct" chain and bypass the normal
19237  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19238  *			command is issued as part of an error recovery action.
19239  *
19240  * Return Code: 0   - Success
19241  *		EIO - IO error
19242  *		EACCES - Reservation conflict detected
19243  *		EAGAIN - Device is becoming ready
19244  *		errno return code from sd_ssc_send()
19245  *
19246  *     Context: Can sleep.  Blocks until command completes.
19247  */
19248 
19249 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
19250 
19251 static int
19252 sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
19253 	int path_flag)
19254 {
19255 	struct	scsi_extended_sense	sense_buf;
19256 	struct	uscsi_cmd	ucmd_buf;
19257 	union	scsi_cdb	cdb;
19258 	uint32_t		*capacity_buf;
19259 	uint64_t		capacity;
19260 	uint32_t		lbasize;
19261 	int			status;
19262 	struct sd_lun		*un;
19263 
19264 	ASSERT(ssc != NULL);
19265 
19266 	un = ssc->ssc_un;
19267 	ASSERT(un != NULL);
19268 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19269 	ASSERT(capp != NULL);
19270 	ASSERT(lbap != NULL);
19271 
19272 	SD_TRACE(SD_LOG_IO, un,
19273 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19274 
19275 	/*
19276 	 * First send a READ_CAPACITY command to the target.
19277 	 * (This command is mandatory under SCSI-2.)
19278 	 *
19279 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
19280 	 * Medium Indicator bit is cleared.  The address field must be
19281 	 * zero if the PMI bit is zero.
19282 	 */
19283 	bzero(&cdb, sizeof (cdb));
19284 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19285 
19286 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
19287 
19288 	cdb.scc_cmd = SCMD_READ_CAPACITY;
19289 
19290 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19291 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19292 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
19293 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
19294 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19295 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19296 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19297 	ucmd_buf.uscsi_timeout	= 60;
19298 
19299 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19300 	    UIO_SYSSPACE, path_flag);
19301 
19302 	switch (status) {
19303 	case 0:
19304 		/* Return failure if we did not get valid capacity data. */
19305 		if (ucmd_buf.uscsi_resid != 0) {
19306 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19307 			    "sd_send_scsi_READ_CAPACITY received invalid "
19308 			    "capacity data");
19309 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19310 			return (EIO);
19311 		}
19312 		/*
19313 		 * Read capacity and block size from the READ CAPACITY 10 data.
19314 		 * This data may be adjusted later due to device specific
19315 		 * issues.
19316 		 *
19317 		 * According to the SCSI spec, the READ CAPACITY 10
19318 		 * command returns the following:
19319 		 *
19320 		 *  bytes 0-3: Maximum logical block address available.
19321 		 *		(MSB in byte:0 & LSB in byte:3)
19322 		 *
19323 		 *  bytes 4-7: Block length in bytes
19324 		 *		(MSB in byte:4 & LSB in byte:7)
19325 		 *
19326 		 */
19327 		capacity = BE_32(capacity_buf[0]);
19328 		lbasize = BE_32(capacity_buf[1]);
19329 
19330 		/*
19331 		 * Done with capacity_buf
19332 		 */
19333 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19334 
19335 		/*
19336 		 * if the reported capacity is set to all 0xf's, then
19337 		 * this disk is too large and requires SBC-2 commands.
19338 		 * Reissue the request using READ CAPACITY 16.
19339 		 */
19340 		if (capacity == 0xffffffff) {
19341 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19342 			status = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity,
19343 			    &lbasize, path_flag);
19344 			if (status != 0) {
19345 				return (status);
19346 			}
19347 		}
19348 		break;	/* Success! */
19349 	case EIO:
19350 		switch (ucmd_buf.uscsi_status) {
19351 		case STATUS_RESERVATION_CONFLICT:
19352 			status = EACCES;
19353 			break;
19354 		case STATUS_CHECK:
19355 			/*
19356 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
19357 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
19358 			 */
19359 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19360 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
19361 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
19362 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19363 				return (EAGAIN);
19364 			}
19365 			break;
19366 		default:
19367 			break;
19368 		}
19369 		/* FALLTHRU */
19370 	default:
19371 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19372 		return (status);
19373 	}
19374 
19375 	/*
19376 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
19377 	 * (2352 and 0 are common) so for these devices always force the value
19378 	 * to 2048 as required by the ATAPI specs.
19379 	 */
19380 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
19381 		lbasize = 2048;
19382 	}
19383 
19384 	/*
19385 	 * Get the maximum LBA value from the READ CAPACITY data.
19386 	 * Here we assume that the Partial Medium Indicator (PMI) bit
19387 	 * was cleared when issuing the command. This means that the LBA
19388 	 * returned from the device is the LBA of the last logical block
19389 	 * on the logical unit.  The actual logical block count will be
19390 	 * this value plus one.
19391 	 *
19392 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
19393 	 * so scale the capacity value to reflect this.
19394 	 */
19395 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
19396 
19397 	/*
19398 	 * Copy the values from the READ CAPACITY command into the space
19399 	 * provided by the caller.
19400 	 */
19401 	*capp = capacity;
19402 	*lbap = lbasize;
19403 
19404 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
19405 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
19406 
19407 	/*
19408 	 * Both the lbasize and capacity from the device must be nonzero,
19409 	 * otherwise we assume that the values are not valid and return
19410 	 * failure to the caller. (4203735)
19411 	 */
19412 	if ((capacity == 0) || (lbasize == 0)) {
19413 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19414 		    "sd_send_scsi_READ_CAPACITY received invalid value "
19415 		    "capacity %llu lbasize %d", capacity, lbasize);
19416 		return (EIO);
19417 	}
19418 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19419 	return (0);
19420 }
19421 
19422 /*
19423  *    Function: sd_send_scsi_READ_CAPACITY_16
19424  *
19425  * Description: This routine uses the scsi READ CAPACITY 16 command to
19426  *		determine the device capacity in number of blocks and the
19427  *		device native block size.  If this function returns a failure,
19428  *		then the values in *capp and *lbap are undefined.
19429  *		This routine should always be called by
19430  *		sd_send_scsi_READ_CAPACITY which will appy any device
19431  *		specific adjustments to capacity and lbasize.
19432  *
19433  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
19434  *		capp - ptr to unsigned 64-bit variable to receive the
19435  *			capacity value from the command.
19436  *		lbap - ptr to unsigned 32-bit varaible to receive the
19437  *			block size value from the command
19438  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19439  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19440  *			to use the USCSI "direct" chain and bypass the normal
19441  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
19442  *			this command is issued as part of an error recovery
19443  *			action.
19444  *
19445  * Return Code: 0   - Success
19446  *		EIO - IO error
19447  *		EACCES - Reservation conflict detected
19448  *		EAGAIN - Device is becoming ready
19449  *		errno return code from sd_ssc_send()
19450  *
19451  *     Context: Can sleep.  Blocks until command completes.
19452  */
19453 
19454 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
19455 
19456 static int
19457 sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
19458 	uint32_t *lbap, int path_flag)
19459 {
19460 	struct	scsi_extended_sense	sense_buf;
19461 	struct	uscsi_cmd	ucmd_buf;
19462 	union	scsi_cdb	cdb;
19463 	uint64_t		*capacity16_buf;
19464 	uint64_t		capacity;
19465 	uint32_t		lbasize;
19466 	int			status;
19467 	struct sd_lun		*un;
19468 
19469 	ASSERT(ssc != NULL);
19470 
19471 	un = ssc->ssc_un;
19472 	ASSERT(un != NULL);
19473 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19474 	ASSERT(capp != NULL);
19475 	ASSERT(lbap != NULL);
19476 
19477 	SD_TRACE(SD_LOG_IO, un,
19478 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19479 
19480 	/*
19481 	 * First send a READ_CAPACITY_16 command to the target.
19482 	 *
19483 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
19484 	 * Medium Indicator bit is cleared.  The address field must be
19485 	 * zero if the PMI bit is zero.
19486 	 */
19487 	bzero(&cdb, sizeof (cdb));
19488 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19489 
19490 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
19491 
19492 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19493 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
19494 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
19495 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
19496 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19497 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19498 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19499 	ucmd_buf.uscsi_timeout	= 60;
19500 
19501 	/*
19502 	 * Read Capacity (16) is a Service Action In command.  One
19503 	 * command byte (0x9E) is overloaded for multiple operations,
19504 	 * with the second CDB byte specifying the desired operation
19505 	 */
19506 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
19507 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
19508 
19509 	/*
19510 	 * Fill in allocation length field
19511 	 */
19512 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
19513 
19514 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19515 	    UIO_SYSSPACE, path_flag);
19516 
19517 	switch (status) {
19518 	case 0:
19519 		/* Return failure if we did not get valid capacity data. */
19520 		if (ucmd_buf.uscsi_resid > 20) {
19521 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19522 			    "sd_send_scsi_READ_CAPACITY_16 received invalid "
19523 			    "capacity data");
19524 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19525 			return (EIO);
19526 		}
19527 
19528 		/*
19529 		 * Read capacity and block size from the READ CAPACITY 10 data.
19530 		 * This data may be adjusted later due to device specific
19531 		 * issues.
19532 		 *
19533 		 * According to the SCSI spec, the READ CAPACITY 10
19534 		 * command returns the following:
19535 		 *
19536 		 *  bytes 0-7: Maximum logical block address available.
19537 		 *		(MSB in byte:0 & LSB in byte:7)
19538 		 *
19539 		 *  bytes 8-11: Block length in bytes
19540 		 *		(MSB in byte:8 & LSB in byte:11)
19541 		 *
19542 		 */
19543 		capacity = BE_64(capacity16_buf[0]);
19544 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
19545 
19546 		/*
19547 		 * Done with capacity16_buf
19548 		 */
19549 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19550 
19551 		/*
19552 		 * if the reported capacity is set to all 0xf's, then
19553 		 * this disk is too large.  This could only happen with
19554 		 * a device that supports LBAs larger than 64 bits which
19555 		 * are not defined by any current T10 standards.
19556 		 */
19557 		if (capacity == 0xffffffffffffffff) {
19558 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19559 			    "disk is too large");
19560 			return (EIO);
19561 		}
19562 		break;	/* Success! */
19563 	case EIO:
19564 		switch (ucmd_buf.uscsi_status) {
19565 		case STATUS_RESERVATION_CONFLICT:
19566 			status = EACCES;
19567 			break;
19568 		case STATUS_CHECK:
19569 			/*
19570 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
19571 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
19572 			 */
19573 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19574 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
19575 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
19576 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19577 				return (EAGAIN);
19578 			}
19579 			break;
19580 		default:
19581 			break;
19582 		}
19583 		/* FALLTHRU */
19584 	default:
19585 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
19586 		return (status);
19587 	}
19588 
19589 	*capp = capacity;
19590 	*lbap = lbasize;
19591 
19592 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
19593 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
19594 
19595 	return (0);
19596 }
19597 
19598 
19599 /*
19600  *    Function: sd_send_scsi_START_STOP_UNIT
19601  *
19602  * Description: Issue a scsi START STOP UNIT command to the target.
19603  *
19604  *   Arguments: ssc    - ssc contatins pointer to driver soft state (unit)
19605  *                       structure for this target.
19606  *		flag  - SD_TARGET_START
19607  *			SD_TARGET_STOP
19608  *			SD_TARGET_EJECT
19609  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19610  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19611  *			to use the USCSI "direct" chain and bypass the normal
19612  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19613  *			command is issued as part of an error recovery action.
19614  *
19615  * Return Code: 0   - Success
19616  *		EIO - IO error
19617  *		EACCES - Reservation conflict detected
19618  *		ENXIO  - Not Ready, medium not present
19619  *		errno return code from sd_ssc_send()
19620  *
19621  *     Context: Can sleep.
19622  */
19623 
19624 static int
19625 sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int flag, int path_flag)
19626 {
19627 	struct	scsi_extended_sense	sense_buf;
19628 	union scsi_cdb		cdb;
19629 	struct uscsi_cmd	ucmd_buf;
19630 	int			status;
19631 	struct sd_lun		*un;
19632 
19633 	ASSERT(ssc != NULL);
19634 	un = ssc->ssc_un;
19635 	ASSERT(un != NULL);
19636 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19637 
19638 	SD_TRACE(SD_LOG_IO, un,
19639 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
19640 
19641 	if (un->un_f_check_start_stop &&
19642 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
19643 	    (un->un_f_start_stop_supported != TRUE)) {
19644 		return (0);
19645 	}
19646 
19647 	/*
19648 	 * If we are performing an eject operation and
19649 	 * we receive any command other than SD_TARGET_EJECT
19650 	 * we should immediately return.
19651 	 */
19652 	if (flag != SD_TARGET_EJECT) {
19653 		mutex_enter(SD_MUTEX(un));
19654 		if (un->un_f_ejecting == TRUE) {
19655 			mutex_exit(SD_MUTEX(un));
19656 			return (EAGAIN);
19657 		}
19658 		mutex_exit(SD_MUTEX(un));
19659 	}
19660 
19661 	bzero(&cdb, sizeof (cdb));
19662 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19663 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19664 
19665 	cdb.scc_cmd = SCMD_START_STOP;
19666 	cdb.cdb_opaque[4] = (uchar_t)flag;
19667 
19668 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19669 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19670 	ucmd_buf.uscsi_bufaddr	= NULL;
19671 	ucmd_buf.uscsi_buflen	= 0;
19672 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19673 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19674 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19675 	ucmd_buf.uscsi_timeout	= 200;
19676 
19677 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19678 	    UIO_SYSSPACE, path_flag);
19679 
19680 	switch (status) {
19681 	case 0:
19682 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19683 		break;	/* Success! */
19684 	case EIO:
19685 		switch (ucmd_buf.uscsi_status) {
19686 		case STATUS_RESERVATION_CONFLICT:
19687 			status = EACCES;
19688 			break;
19689 		case STATUS_CHECK:
19690 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
19691 				switch (scsi_sense_key(
19692 				    (uint8_t *)&sense_buf)) {
19693 				case KEY_ILLEGAL_REQUEST:
19694 					status = ENOTSUP;
19695 					break;
19696 				case KEY_NOT_READY:
19697 					if (scsi_sense_asc(
19698 					    (uint8_t *)&sense_buf)
19699 					    == 0x3A) {
19700 						status = ENXIO;
19701 					}
19702 					break;
19703 				default:
19704 					break;
19705 				}
19706 			}
19707 			break;
19708 		default:
19709 			break;
19710 		}
19711 		break;
19712 	default:
19713 		break;
19714 	}
19715 
19716 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
19717 
19718 	return (status);
19719 }
19720 
19721 
19722 /*
19723  *    Function: sd_start_stop_unit_callback
19724  *
19725  * Description: timeout(9F) callback to begin recovery process for a
19726  *		device that has spun down.
19727  *
19728  *   Arguments: arg - pointer to associated softstate struct.
19729  *
19730  *     Context: Executes in a timeout(9F) thread context
19731  */
19732 
19733 static void
19734 sd_start_stop_unit_callback(void *arg)
19735 {
19736 	struct sd_lun	*un = arg;
19737 	ASSERT(un != NULL);
19738 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19739 
19740 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
19741 
19742 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
19743 }
19744 
19745 
19746 /*
19747  *    Function: sd_start_stop_unit_task
19748  *
19749  * Description: Recovery procedure when a drive is spun down.
19750  *
19751  *   Arguments: arg - pointer to associated softstate struct.
19752  *
19753  *     Context: Executes in a taskq() thread context
19754  */
19755 
19756 static void
19757 sd_start_stop_unit_task(void *arg)
19758 {
19759 	struct sd_lun	*un = arg;
19760 	sd_ssc_t	*ssc;
19761 	int		rval;
19762 
19763 	ASSERT(un != NULL);
19764 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19765 
19766 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
19767 
19768 	/*
19769 	 * Some unformatted drives report not ready error, no need to
19770 	 * restart if format has been initiated.
19771 	 */
19772 	mutex_enter(SD_MUTEX(un));
19773 	if (un->un_f_format_in_progress == TRUE) {
19774 		mutex_exit(SD_MUTEX(un));
19775 		return;
19776 	}
19777 	mutex_exit(SD_MUTEX(un));
19778 
19779 	/*
19780 	 * When a START STOP command is issued from here, it is part of a
19781 	 * failure recovery operation and must be issued before any other
19782 	 * commands, including any pending retries. Thus it must be sent
19783 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
19784 	 * succeeds or not, we will start I/O after the attempt.
19785 	 */
19786 	ssc = sd_ssc_init(un);
19787 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_START,
19788 	    SD_PATH_DIRECT_PRIORITY);
19789 	if (rval != 0)
19790 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19791 	sd_ssc_fini(ssc);
19792 	/*
19793 	 * The above call blocks until the START_STOP_UNIT command completes.
19794 	 * Now that it has completed, we must re-try the original IO that
19795 	 * received the NOT READY condition in the first place. There are
19796 	 * three possible conditions here:
19797 	 *
19798 	 *  (1) The original IO is on un_retry_bp.
19799 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
19800 	 *	is NULL.
19801 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
19802 	 *	points to some other, unrelated bp.
19803 	 *
19804 	 * For each case, we must call sd_start_cmds() with un_retry_bp
19805 	 * as the argument. If un_retry_bp is NULL, this will initiate
19806 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
19807 	 * then this will process the bp on un_retry_bp. That may or may not
19808 	 * be the original IO, but that does not matter: the important thing
19809 	 * is to keep the IO processing going at this point.
19810 	 *
19811 	 * Note: This is a very specific error recovery sequence associated
19812 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
19813 	 * serialize the I/O with completion of the spin-up.
19814 	 */
19815 	mutex_enter(SD_MUTEX(un));
19816 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19817 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
19818 	    un, un->un_retry_bp);
19819 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
19820 	sd_start_cmds(un, un->un_retry_bp);
19821 	mutex_exit(SD_MUTEX(un));
19822 
19823 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
19824 }
19825 
19826 
19827 /*
19828  *    Function: sd_send_scsi_INQUIRY
19829  *
19830  * Description: Issue the scsi INQUIRY command.
19831  *
19832  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19833  *                      structure for this target.
19834  *		bufaddr
19835  *		buflen
19836  *		evpd
19837  *		page_code
19838  *		page_length
19839  *
19840  * Return Code: 0   - Success
19841  *		errno return code from sd_ssc_send()
19842  *
19843  *     Context: Can sleep. Does not return until command is completed.
19844  */
19845 
19846 static int
19847 sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr, size_t buflen,
19848 	uchar_t evpd, uchar_t page_code, size_t *residp)
19849 {
19850 	union scsi_cdb		cdb;
19851 	struct uscsi_cmd	ucmd_buf;
19852 	int			status;
19853 	struct sd_lun		*un;
19854 
19855 	ASSERT(ssc != NULL);
19856 	un = ssc->ssc_un;
19857 	ASSERT(un != NULL);
19858 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19859 	ASSERT(bufaddr != NULL);
19860 
19861 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
19862 
19863 	bzero(&cdb, sizeof (cdb));
19864 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19865 	bzero(bufaddr, buflen);
19866 
19867 	cdb.scc_cmd = SCMD_INQUIRY;
19868 	cdb.cdb_opaque[1] = evpd;
19869 	cdb.cdb_opaque[2] = page_code;
19870 	FORMG0COUNT(&cdb, buflen);
19871 
19872 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19873 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19874 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19875 	ucmd_buf.uscsi_buflen	= buflen;
19876 	ucmd_buf.uscsi_rqbuf	= NULL;
19877 	ucmd_buf.uscsi_rqlen	= 0;
19878 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
19879 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
19880 
19881 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19882 	    UIO_SYSSPACE, SD_PATH_DIRECT);
19883 
19884 	/*
19885 	 * Only handle status == 0, the upper-level caller
19886 	 * will put different assessment based on the context.
19887 	 */
19888 	if (status == 0)
19889 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19890 
19891 	if ((status == 0) && (residp != NULL)) {
19892 		*residp = ucmd_buf.uscsi_resid;
19893 	}
19894 
19895 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
19896 
19897 	return (status);
19898 }
19899 
19900 
19901 /*
19902  *    Function: sd_send_scsi_TEST_UNIT_READY
19903  *
19904  * Description: Issue the scsi TEST UNIT READY command.
19905  *		This routine can be told to set the flag USCSI_DIAGNOSE to
19906  *		prevent retrying failed commands. Use this when the intent
19907  *		is either to check for device readiness, to clear a Unit
19908  *		Attention, or to clear any outstanding sense data.
19909  *		However under specific conditions the expected behavior
19910  *		is for retries to bring a device ready, so use the flag
19911  *		with caution.
19912  *
19913  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19914  *                      structure for this target.
19915  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
19916  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
19917  *			0: dont check for media present, do retries on cmd.
19918  *
19919  * Return Code: 0   - Success
19920  *		EIO - IO error
19921  *		EACCES - Reservation conflict detected
19922  *		ENXIO  - Not Ready, medium not present
19923  *		errno return code from sd_ssc_send()
19924  *
19925  *     Context: Can sleep. Does not return until command is completed.
19926  */
19927 
19928 static int
19929 sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag)
19930 {
19931 	struct	scsi_extended_sense	sense_buf;
19932 	union scsi_cdb		cdb;
19933 	struct uscsi_cmd	ucmd_buf;
19934 	int			status;
19935 	struct sd_lun		*un;
19936 
19937 	ASSERT(ssc != NULL);
19938 	un = ssc->ssc_un;
19939 	ASSERT(un != NULL);
19940 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19941 
19942 	SD_TRACE(SD_LOG_IO, un,
19943 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
19944 
19945 	/*
19946 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
19947 	 * timeouts when they receive a TUR and the queue is not empty. Check
19948 	 * the configuration flag set during attach (indicating the drive has
19949 	 * this firmware bug) and un_ncmds_in_transport before issuing the
19950 	 * TUR. If there are
19951 	 * pending commands return success, this is a bit arbitrary but is ok
19952 	 * for non-removables (i.e. the eliteI disks) and non-clustering
19953 	 * configurations.
19954 	 */
19955 	if (un->un_f_cfg_tur_check == TRUE) {
19956 		mutex_enter(SD_MUTEX(un));
19957 		if (un->un_ncmds_in_transport != 0) {
19958 			mutex_exit(SD_MUTEX(un));
19959 			return (0);
19960 		}
19961 		mutex_exit(SD_MUTEX(un));
19962 	}
19963 
19964 	bzero(&cdb, sizeof (cdb));
19965 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19966 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19967 
19968 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
19969 
19970 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19971 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19972 	ucmd_buf.uscsi_bufaddr	= NULL;
19973 	ucmd_buf.uscsi_buflen	= 0;
19974 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19975 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19976 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19977 
19978 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
19979 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
19980 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
19981 	}
19982 	ucmd_buf.uscsi_timeout	= 60;
19983 
19984 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19985 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
19986 	    SD_PATH_STANDARD));
19987 
19988 	switch (status) {
19989 	case 0:
19990 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19991 		break;	/* Success! */
19992 	case EIO:
19993 		switch (ucmd_buf.uscsi_status) {
19994 		case STATUS_RESERVATION_CONFLICT:
19995 			status = EACCES;
19996 			break;
19997 		case STATUS_CHECK:
19998 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
19999 				break;
20000 			}
20001 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20002 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20003 			    KEY_NOT_READY) &&
20004 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
20005 				status = ENXIO;
20006 			}
20007 			break;
20008 		default:
20009 			break;
20010 		}
20011 		break;
20012 	default:
20013 		break;
20014 	}
20015 
20016 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
20017 
20018 	return (status);
20019 }
20020 
20021 /*
20022  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
20023  *
20024  * Description: Issue the scsi PERSISTENT RESERVE IN command.
20025  *
20026  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20027  *                      structure for this target.
20028  *
20029  * Return Code: 0   - Success
20030  *		EACCES
20031  *		ENOTSUP
20032  *		errno return code from sd_ssc_send()
20033  *
20034  *     Context: Can sleep. Does not return until command is completed.
20035  */
20036 
20037 static int
20038 sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc, uchar_t  usr_cmd,
20039 	uint16_t data_len, uchar_t *data_bufp)
20040 {
20041 	struct scsi_extended_sense	sense_buf;
20042 	union scsi_cdb		cdb;
20043 	struct uscsi_cmd	ucmd_buf;
20044 	int			status;
20045 	int			no_caller_buf = FALSE;
20046 	struct sd_lun		*un;
20047 
20048 	ASSERT(ssc != NULL);
20049 	un = ssc->ssc_un;
20050 	ASSERT(un != NULL);
20051 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20052 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
20053 
20054 	SD_TRACE(SD_LOG_IO, un,
20055 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
20056 
20057 	bzero(&cdb, sizeof (cdb));
20058 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20059 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20060 	if (data_bufp == NULL) {
20061 		/* Allocate a default buf if the caller did not give one */
20062 		ASSERT(data_len == 0);
20063 		data_len  = MHIOC_RESV_KEY_SIZE;
20064 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
20065 		no_caller_buf = TRUE;
20066 	}
20067 
20068 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
20069 	cdb.cdb_opaque[1] = usr_cmd;
20070 	FORMG1COUNT(&cdb, data_len);
20071 
20072 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20073 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20074 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
20075 	ucmd_buf.uscsi_buflen	= data_len;
20076 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20077 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20078 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20079 	ucmd_buf.uscsi_timeout	= 60;
20080 
20081 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20082 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20083 
20084 	switch (status) {
20085 	case 0:
20086 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20087 
20088 		break;	/* Success! */
20089 	case EIO:
20090 		switch (ucmd_buf.uscsi_status) {
20091 		case STATUS_RESERVATION_CONFLICT:
20092 			status = EACCES;
20093 			break;
20094 		case STATUS_CHECK:
20095 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20096 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20097 			    KEY_ILLEGAL_REQUEST)) {
20098 				status = ENOTSUP;
20099 			}
20100 			break;
20101 		default:
20102 			break;
20103 		}
20104 		break;
20105 	default:
20106 		break;
20107 	}
20108 
20109 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
20110 
20111 	if (no_caller_buf == TRUE) {
20112 		kmem_free(data_bufp, data_len);
20113 	}
20114 
20115 	return (status);
20116 }
20117 
20118 
20119 /*
20120  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
20121  *
20122  * Description: This routine is the driver entry point for handling CD-ROM
20123  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
20124  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
20125  *		device.
20126  *
20127  *   Arguments: ssc  -  ssc contains un - pointer to soft state struct
20128  *                      for the target.
20129  *		usr_cmd SCSI-3 reservation facility command (one of
20130  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
20131  *			SD_SCSI3_PREEMPTANDABORT)
20132  *		usr_bufp - user provided pointer register, reserve descriptor or
20133  *			preempt and abort structure (mhioc_register_t,
20134  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
20135  *
20136  * Return Code: 0   - Success
20137  *		EACCES
20138  *		ENOTSUP
20139  *		errno return code from sd_ssc_send()
20140  *
20141  *     Context: Can sleep. Does not return until command is completed.
20142  */
20143 
20144 static int
20145 sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc, uchar_t usr_cmd,
20146 	uchar_t	*usr_bufp)
20147 {
20148 	struct scsi_extended_sense	sense_buf;
20149 	union scsi_cdb		cdb;
20150 	struct uscsi_cmd	ucmd_buf;
20151 	int			status;
20152 	uchar_t			data_len = sizeof (sd_prout_t);
20153 	sd_prout_t		*prp;
20154 	struct sd_lun		*un;
20155 
20156 	ASSERT(ssc != NULL);
20157 	un = ssc->ssc_un;
20158 	ASSERT(un != NULL);
20159 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20160 	ASSERT(data_len == 24);	/* required by scsi spec */
20161 
20162 	SD_TRACE(SD_LOG_IO, un,
20163 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
20164 
20165 	if (usr_bufp == NULL) {
20166 		return (EINVAL);
20167 	}
20168 
20169 	bzero(&cdb, sizeof (cdb));
20170 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20171 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20172 	prp = kmem_zalloc(data_len, KM_SLEEP);
20173 
20174 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
20175 	cdb.cdb_opaque[1] = usr_cmd;
20176 	FORMG1COUNT(&cdb, data_len);
20177 
20178 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20179 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20180 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
20181 	ucmd_buf.uscsi_buflen	= data_len;
20182 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20183 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20184 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
20185 	ucmd_buf.uscsi_timeout	= 60;
20186 
20187 	switch (usr_cmd) {
20188 	case SD_SCSI3_REGISTER: {
20189 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
20190 
20191 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20192 		bcopy(ptr->newkey.key, prp->service_key,
20193 		    MHIOC_RESV_KEY_SIZE);
20194 		prp->aptpl = ptr->aptpl;
20195 		break;
20196 	}
20197 	case SD_SCSI3_RESERVE:
20198 	case SD_SCSI3_RELEASE: {
20199 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
20200 
20201 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20202 		prp->scope_address = BE_32(ptr->scope_specific_addr);
20203 		cdb.cdb_opaque[2] = ptr->type;
20204 		break;
20205 	}
20206 	case SD_SCSI3_PREEMPTANDABORT: {
20207 		mhioc_preemptandabort_t *ptr =
20208 		    (mhioc_preemptandabort_t *)usr_bufp;
20209 
20210 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20211 		bcopy(ptr->victim_key.key, prp->service_key,
20212 		    MHIOC_RESV_KEY_SIZE);
20213 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
20214 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
20215 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
20216 		break;
20217 	}
20218 	case SD_SCSI3_REGISTERANDIGNOREKEY:
20219 	{
20220 		mhioc_registerandignorekey_t *ptr;
20221 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
20222 		bcopy(ptr->newkey.key,
20223 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
20224 		prp->aptpl = ptr->aptpl;
20225 		break;
20226 	}
20227 	default:
20228 		ASSERT(FALSE);
20229 		break;
20230 	}
20231 
20232 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20233 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20234 
20235 	switch (status) {
20236 	case 0:
20237 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20238 		break;	/* Success! */
20239 	case EIO:
20240 		switch (ucmd_buf.uscsi_status) {
20241 		case STATUS_RESERVATION_CONFLICT:
20242 			status = EACCES;
20243 			break;
20244 		case STATUS_CHECK:
20245 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20246 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20247 			    KEY_ILLEGAL_REQUEST)) {
20248 				status = ENOTSUP;
20249 			}
20250 			break;
20251 		default:
20252 			break;
20253 		}
20254 		break;
20255 	default:
20256 		break;
20257 	}
20258 
20259 	kmem_free(prp, data_len);
20260 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
20261 	return (status);
20262 }
20263 
20264 
20265 /*
20266  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
20267  *
20268  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
20269  *
20270  *   Arguments: un - pointer to the target's soft state struct
20271  *              dkc - pointer to the callback structure
20272  *
20273  * Return Code: 0 - success
20274  *		errno-type error code
20275  *
20276  *     Context: kernel thread context only.
20277  *
20278  *  _______________________________________________________________
20279  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
20280  * |FLUSH_VOLATILE|              | operation                       |
20281  * |______________|______________|_________________________________|
20282  * | 0            | NULL         | Synchronous flush on both       |
20283  * |              |              | volatile and non-volatile cache |
20284  * |______________|______________|_________________________________|
20285  * | 1            | NULL         | Synchronous flush on volatile   |
20286  * |              |              | cache; disk drivers may suppress|
20287  * |              |              | flush if disk table indicates   |
20288  * |              |              | non-volatile cache              |
20289  * |______________|______________|_________________________________|
20290  * | 0            | !NULL        | Asynchronous flush on both      |
20291  * |              |              | volatile and non-volatile cache;|
20292  * |______________|______________|_________________________________|
20293  * | 1            | !NULL        | Asynchronous flush on volatile  |
20294  * |              |              | cache; disk drivers may suppress|
20295  * |              |              | flush if disk table indicates   |
20296  * |              |              | non-volatile cache              |
20297  * |______________|______________|_________________________________|
20298  *
20299  */
20300 
20301 static int
20302 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
20303 {
20304 	struct sd_uscsi_info	*uip;
20305 	struct uscsi_cmd	*uscmd;
20306 	union scsi_cdb		*cdb;
20307 	struct buf		*bp;
20308 	int			rval = 0;
20309 	int			is_async;
20310 
20311 	SD_TRACE(SD_LOG_IO, un,
20312 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
20313 
20314 	ASSERT(un != NULL);
20315 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20316 
20317 	if (dkc == NULL || dkc->dkc_callback == NULL) {
20318 		is_async = FALSE;
20319 	} else {
20320 		is_async = TRUE;
20321 	}
20322 
20323 	mutex_enter(SD_MUTEX(un));
20324 	/* check whether cache flush should be suppressed */
20325 	if (un->un_f_suppress_cache_flush == TRUE) {
20326 		mutex_exit(SD_MUTEX(un));
20327 		/*
20328 		 * suppress the cache flush if the device is told to do
20329 		 * so by sd.conf or disk table
20330 		 */
20331 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
20332 		    skip the cache flush since suppress_cache_flush is %d!\n",
20333 		    un->un_f_suppress_cache_flush);
20334 
20335 		if (is_async == TRUE) {
20336 			/* invoke callback for asynchronous flush */
20337 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
20338 		}
20339 		return (rval);
20340 	}
20341 	mutex_exit(SD_MUTEX(un));
20342 
20343 	/*
20344 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
20345 	 * set properly
20346 	 */
20347 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
20348 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
20349 
20350 	mutex_enter(SD_MUTEX(un));
20351 	if (dkc != NULL && un->un_f_sync_nv_supported &&
20352 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
20353 		/*
20354 		 * if the device supports SYNC_NV bit, turn on
20355 		 * the SYNC_NV bit to only flush volatile cache
20356 		 */
20357 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
20358 	}
20359 	mutex_exit(SD_MUTEX(un));
20360 
20361 	/*
20362 	 * First get some memory for the uscsi_cmd struct and cdb
20363 	 * and initialize for SYNCHRONIZE_CACHE cmd.
20364 	 */
20365 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
20366 	uscmd->uscsi_cdblen = CDB_GROUP1;
20367 	uscmd->uscsi_cdb = (caddr_t)cdb;
20368 	uscmd->uscsi_bufaddr = NULL;
20369 	uscmd->uscsi_buflen = 0;
20370 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20371 	uscmd->uscsi_rqlen = SENSE_LENGTH;
20372 	uscmd->uscsi_rqresid = SENSE_LENGTH;
20373 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
20374 	uscmd->uscsi_timeout = sd_io_time;
20375 
20376 	/*
20377 	 * Allocate an sd_uscsi_info struct and fill it with the info
20378 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
20379 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
20380 	 * since we allocate the buf here in this function, we do not
20381 	 * need to preserve the prior contents of b_private.
20382 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
20383 	 */
20384 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
20385 	uip->ui_flags = SD_PATH_DIRECT;
20386 	uip->ui_cmdp  = uscmd;
20387 
20388 	bp = getrbuf(KM_SLEEP);
20389 	bp->b_private = uip;
20390 
20391 	/*
20392 	 * Setup buffer to carry uscsi request.
20393 	 */
20394 	bp->b_flags  = B_BUSY;
20395 	bp->b_bcount = 0;
20396 	bp->b_blkno  = 0;
20397 
20398 	if (is_async == TRUE) {
20399 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
20400 		uip->ui_dkc = *dkc;
20401 	}
20402 
20403 	bp->b_edev = SD_GET_DEV(un);
20404 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
20405 
20406 	/*
20407 	 * Unset un_f_sync_cache_required flag
20408 	 */
20409 	mutex_enter(SD_MUTEX(un));
20410 	un->un_f_sync_cache_required = FALSE;
20411 	mutex_exit(SD_MUTEX(un));
20412 
20413 	(void) sd_uscsi_strategy(bp);
20414 
20415 	/*
20416 	 * If synchronous request, wait for completion
20417 	 * If async just return and let b_iodone callback
20418 	 * cleanup.
20419 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
20420 	 * but it was also incremented in sd_uscsi_strategy(), so
20421 	 * we should be ok.
20422 	 */
20423 	if (is_async == FALSE) {
20424 		(void) biowait(bp);
20425 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
20426 	}
20427 
20428 	return (rval);
20429 }
20430 
20431 
20432 static int
20433 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
20434 {
20435 	struct sd_uscsi_info *uip;
20436 	struct uscsi_cmd *uscmd;
20437 	uint8_t *sense_buf;
20438 	struct sd_lun *un;
20439 	int status;
20440 	union scsi_cdb *cdb;
20441 
20442 	uip = (struct sd_uscsi_info *)(bp->b_private);
20443 	ASSERT(uip != NULL);
20444 
20445 	uscmd = uip->ui_cmdp;
20446 	ASSERT(uscmd != NULL);
20447 
20448 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
20449 	ASSERT(sense_buf != NULL);
20450 
20451 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
20452 	ASSERT(un != NULL);
20453 
20454 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
20455 
20456 	status = geterror(bp);
20457 	switch (status) {
20458 	case 0:
20459 		break;	/* Success! */
20460 	case EIO:
20461 		switch (uscmd->uscsi_status) {
20462 		case STATUS_RESERVATION_CONFLICT:
20463 			/* Ignore reservation conflict */
20464 			status = 0;
20465 			goto done;
20466 
20467 		case STATUS_CHECK:
20468 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
20469 			    (scsi_sense_key(sense_buf) ==
20470 			    KEY_ILLEGAL_REQUEST)) {
20471 				/* Ignore Illegal Request error */
20472 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
20473 					mutex_enter(SD_MUTEX(un));
20474 					un->un_f_sync_nv_supported = FALSE;
20475 					mutex_exit(SD_MUTEX(un));
20476 					status = 0;
20477 					SD_TRACE(SD_LOG_IO, un,
20478 					    "un_f_sync_nv_supported \
20479 					    is set to false.\n");
20480 					goto done;
20481 				}
20482 
20483 				mutex_enter(SD_MUTEX(un));
20484 				un->un_f_sync_cache_supported = FALSE;
20485 				mutex_exit(SD_MUTEX(un));
20486 				SD_TRACE(SD_LOG_IO, un,
20487 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
20488 				    un_f_sync_cache_supported set to false \
20489 				    with asc = %x, ascq = %x\n",
20490 				    scsi_sense_asc(sense_buf),
20491 				    scsi_sense_ascq(sense_buf));
20492 				status = ENOTSUP;
20493 				goto done;
20494 			}
20495 			break;
20496 		default:
20497 			break;
20498 		}
20499 		/* FALLTHRU */
20500 	default:
20501 		/*
20502 		 * Turn on the un_f_sync_cache_required flag
20503 		 * since the SYNC CACHE command failed
20504 		 */
20505 		mutex_enter(SD_MUTEX(un));
20506 		un->un_f_sync_cache_required = TRUE;
20507 		mutex_exit(SD_MUTEX(un));
20508 
20509 		/*
20510 		 * Don't log an error message if this device
20511 		 * has removable media.
20512 		 */
20513 		if (!un->un_f_has_removable_media) {
20514 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
20515 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
20516 		}
20517 		break;
20518 	}
20519 
20520 done:
20521 	if (uip->ui_dkc.dkc_callback != NULL) {
20522 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
20523 	}
20524 
20525 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
20526 	freerbuf(bp);
20527 	kmem_free(uip, sizeof (struct sd_uscsi_info));
20528 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
20529 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
20530 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
20531 
20532 	return (status);
20533 }
20534 
20535 
20536 /*
20537  *    Function: sd_send_scsi_GET_CONFIGURATION
20538  *
20539  * Description: Issues the get configuration command to the device.
20540  *		Called from sd_check_for_writable_cd & sd_get_media_info
20541  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
20542  *   Arguments: ssc
20543  *		ucmdbuf
20544  *		rqbuf
20545  *		rqbuflen
20546  *		bufaddr
20547  *		buflen
20548  *		path_flag
20549  *
20550  * Return Code: 0   - Success
20551  *		errno return code from sd_ssc_send()
20552  *
20553  *     Context: Can sleep. Does not return until command is completed.
20554  *
20555  */
20556 
20557 static int
20558 sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
20559 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
20560 	int path_flag)
20561 {
20562 	char	cdb[CDB_GROUP1];
20563 	int	status;
20564 	struct sd_lun	*un;
20565 
20566 	ASSERT(ssc != NULL);
20567 	un = ssc->ssc_un;
20568 	ASSERT(un != NULL);
20569 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20570 	ASSERT(bufaddr != NULL);
20571 	ASSERT(ucmdbuf != NULL);
20572 	ASSERT(rqbuf != NULL);
20573 
20574 	SD_TRACE(SD_LOG_IO, un,
20575 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
20576 
20577 	bzero(cdb, sizeof (cdb));
20578 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
20579 	bzero(rqbuf, rqbuflen);
20580 	bzero(bufaddr, buflen);
20581 
20582 	/*
20583 	 * Set up cdb field for the get configuration command.
20584 	 */
20585 	cdb[0] = SCMD_GET_CONFIGURATION;
20586 	cdb[1] = 0x02;  /* Requested Type */
20587 	cdb[8] = SD_PROFILE_HEADER_LEN;
20588 	ucmdbuf->uscsi_cdb = cdb;
20589 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
20590 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
20591 	ucmdbuf->uscsi_buflen = buflen;
20592 	ucmdbuf->uscsi_timeout = sd_io_time;
20593 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
20594 	ucmdbuf->uscsi_rqlen = rqbuflen;
20595 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
20596 
20597 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
20598 	    UIO_SYSSPACE, path_flag);
20599 
20600 	switch (status) {
20601 	case 0:
20602 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20603 		break;  /* Success! */
20604 	case EIO:
20605 		switch (ucmdbuf->uscsi_status) {
20606 		case STATUS_RESERVATION_CONFLICT:
20607 			status = EACCES;
20608 			break;
20609 		default:
20610 			break;
20611 		}
20612 		break;
20613 	default:
20614 		break;
20615 	}
20616 
20617 	if (status == 0) {
20618 		SD_DUMP_MEMORY(un, SD_LOG_IO,
20619 		    "sd_send_scsi_GET_CONFIGURATION: data",
20620 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
20621 	}
20622 
20623 	SD_TRACE(SD_LOG_IO, un,
20624 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
20625 
20626 	return (status);
20627 }
20628 
20629 /*
20630  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
20631  *
20632  * Description: Issues the get configuration command to the device to
20633  *              retrieve a specific feature. Called from
20634  *		sd_check_for_writable_cd & sd_set_mmc_caps.
20635  *   Arguments: ssc
20636  *              ucmdbuf
20637  *              rqbuf
20638  *              rqbuflen
20639  *              bufaddr
20640  *              buflen
20641  *		feature
20642  *
20643  * Return Code: 0   - Success
20644  *              errno return code from sd_ssc_send()
20645  *
20646  *     Context: Can sleep. Does not return until command is completed.
20647  *
20648  */
20649 static int
20650 sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
20651 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
20652 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
20653 {
20654 	char    cdb[CDB_GROUP1];
20655 	int	status;
20656 	struct sd_lun	*un;
20657 
20658 	ASSERT(ssc != NULL);
20659 	un = ssc->ssc_un;
20660 	ASSERT(un != NULL);
20661 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20662 	ASSERT(bufaddr != NULL);
20663 	ASSERT(ucmdbuf != NULL);
20664 	ASSERT(rqbuf != NULL);
20665 
20666 	SD_TRACE(SD_LOG_IO, un,
20667 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
20668 
20669 	bzero(cdb, sizeof (cdb));
20670 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
20671 	bzero(rqbuf, rqbuflen);
20672 	bzero(bufaddr, buflen);
20673 
20674 	/*
20675 	 * Set up cdb field for the get configuration command.
20676 	 */
20677 	cdb[0] = SCMD_GET_CONFIGURATION;
20678 	cdb[1] = 0x02;  /* Requested Type */
20679 	cdb[3] = feature;
20680 	cdb[8] = buflen;
20681 	ucmdbuf->uscsi_cdb = cdb;
20682 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
20683 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
20684 	ucmdbuf->uscsi_buflen = buflen;
20685 	ucmdbuf->uscsi_timeout = sd_io_time;
20686 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
20687 	ucmdbuf->uscsi_rqlen = rqbuflen;
20688 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
20689 
20690 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
20691 	    UIO_SYSSPACE, path_flag);
20692 
20693 	switch (status) {
20694 	case 0:
20695 
20696 		break;  /* Success! */
20697 	case EIO:
20698 		switch (ucmdbuf->uscsi_status) {
20699 		case STATUS_RESERVATION_CONFLICT:
20700 			status = EACCES;
20701 			break;
20702 		default:
20703 			break;
20704 		}
20705 		break;
20706 	default:
20707 		break;
20708 	}
20709 
20710 	if (status == 0) {
20711 		SD_DUMP_MEMORY(un, SD_LOG_IO,
20712 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
20713 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
20714 	}
20715 
20716 	SD_TRACE(SD_LOG_IO, un,
20717 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
20718 
20719 	return (status);
20720 }
20721 
20722 
20723 /*
20724  *    Function: sd_send_scsi_MODE_SENSE
20725  *
20726  * Description: Utility function for issuing a scsi MODE SENSE command.
20727  *		Note: This routine uses a consistent implementation for Group0,
20728  *		Group1, and Group2 commands across all platforms. ATAPI devices
20729  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
20730  *
20731  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20732  *                      structure for this target.
20733  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
20734  *			  CDB_GROUP[1|2] (10 byte).
20735  *		bufaddr - buffer for page data retrieved from the target.
20736  *		buflen - size of page to be retrieved.
20737  *		page_code - page code of data to be retrieved from the target.
20738  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20739  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20740  *			to use the USCSI "direct" chain and bypass the normal
20741  *			command waitq.
20742  *
20743  * Return Code: 0   - Success
20744  *		errno return code from sd_ssc_send()
20745  *
20746  *     Context: Can sleep. Does not return until command is completed.
20747  */
20748 
20749 static int
20750 sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
20751 	size_t buflen,  uchar_t page_code, int path_flag)
20752 {
20753 	struct	scsi_extended_sense	sense_buf;
20754 	union scsi_cdb		cdb;
20755 	struct uscsi_cmd	ucmd_buf;
20756 	int			status;
20757 	int			headlen;
20758 	struct sd_lun		*un;
20759 
20760 	ASSERT(ssc != NULL);
20761 	un = ssc->ssc_un;
20762 	ASSERT(un != NULL);
20763 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20764 	ASSERT(bufaddr != NULL);
20765 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
20766 	    (cdbsize == CDB_GROUP2));
20767 
20768 	SD_TRACE(SD_LOG_IO, un,
20769 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
20770 
20771 	bzero(&cdb, sizeof (cdb));
20772 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20773 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20774 	bzero(bufaddr, buflen);
20775 
20776 	if (cdbsize == CDB_GROUP0) {
20777 		cdb.scc_cmd = SCMD_MODE_SENSE;
20778 		cdb.cdb_opaque[2] = page_code;
20779 		FORMG0COUNT(&cdb, buflen);
20780 		headlen = MODE_HEADER_LENGTH;
20781 	} else {
20782 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
20783 		cdb.cdb_opaque[2] = page_code;
20784 		FORMG1COUNT(&cdb, buflen);
20785 		headlen = MODE_HEADER_LENGTH_GRP2;
20786 	}
20787 
20788 	ASSERT(headlen <= buflen);
20789 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
20790 
20791 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20792 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
20793 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20794 	ucmd_buf.uscsi_buflen	= buflen;
20795 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20796 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20797 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20798 	ucmd_buf.uscsi_timeout	= 60;
20799 
20800 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20801 	    UIO_SYSSPACE, path_flag);
20802 
20803 	switch (status) {
20804 	case 0:
20805 		/*
20806 		 * sr_check_wp() uses 0x3f page code and check the header of
20807 		 * mode page to determine if target device is write-protected.
20808 		 * But some USB devices return 0 bytes for 0x3f page code. For
20809 		 * this case, make sure that mode page header is returned at
20810 		 * least.
20811 		 */
20812 		if (buflen - ucmd_buf.uscsi_resid <  headlen) {
20813 			status = EIO;
20814 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20815 			    "mode page header is not returned");
20816 		}
20817 		break;	/* Success! */
20818 	case EIO:
20819 		switch (ucmd_buf.uscsi_status) {
20820 		case STATUS_RESERVATION_CONFLICT:
20821 			status = EACCES;
20822 			break;
20823 		default:
20824 			break;
20825 		}
20826 		break;
20827 	default:
20828 		break;
20829 	}
20830 
20831 	if (status == 0) {
20832 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
20833 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
20834 	}
20835 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
20836 
20837 	return (status);
20838 }
20839 
20840 
20841 /*
20842  *    Function: sd_send_scsi_MODE_SELECT
20843  *
20844  * Description: Utility function for issuing a scsi MODE SELECT command.
20845  *		Note: This routine uses a consistent implementation for Group0,
20846  *		Group1, and Group2 commands across all platforms. ATAPI devices
20847  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
20848  *
20849  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20850  *                      structure for this target.
20851  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
20852  *			  CDB_GROUP[1|2] (10 byte).
20853  *		bufaddr - buffer for page data retrieved from the target.
20854  *		buflen - size of page to be retrieved.
20855  *		save_page - boolean to determin if SP bit should be set.
20856  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20857  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20858  *			to use the USCSI "direct" chain and bypass the normal
20859  *			command waitq.
20860  *
20861  * Return Code: 0   - Success
20862  *		errno return code from sd_ssc_send()
20863  *
20864  *     Context: Can sleep. Does not return until command is completed.
20865  */
20866 
20867 static int
20868 sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
20869 	size_t buflen,  uchar_t save_page, int path_flag)
20870 {
20871 	struct	scsi_extended_sense	sense_buf;
20872 	union scsi_cdb		cdb;
20873 	struct uscsi_cmd	ucmd_buf;
20874 	int			status;
20875 	struct sd_lun		*un;
20876 
20877 	ASSERT(ssc != NULL);
20878 	un = ssc->ssc_un;
20879 	ASSERT(un != NULL);
20880 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20881 	ASSERT(bufaddr != NULL);
20882 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
20883 	    (cdbsize == CDB_GROUP2));
20884 
20885 	SD_TRACE(SD_LOG_IO, un,
20886 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
20887 
20888 	bzero(&cdb, sizeof (cdb));
20889 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20890 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20891 
20892 	/* Set the PF bit for many third party drives */
20893 	cdb.cdb_opaque[1] = 0x10;
20894 
20895 	/* Set the savepage(SP) bit if given */
20896 	if (save_page == SD_SAVE_PAGE) {
20897 		cdb.cdb_opaque[1] |= 0x01;
20898 	}
20899 
20900 	if (cdbsize == CDB_GROUP0) {
20901 		cdb.scc_cmd = SCMD_MODE_SELECT;
20902 		FORMG0COUNT(&cdb, buflen);
20903 	} else {
20904 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
20905 		FORMG1COUNT(&cdb, buflen);
20906 	}
20907 
20908 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
20909 
20910 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20911 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
20912 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20913 	ucmd_buf.uscsi_buflen	= buflen;
20914 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20915 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20916 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
20917 	ucmd_buf.uscsi_timeout	= 60;
20918 
20919 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20920 	    UIO_SYSSPACE, path_flag);
20921 
20922 	switch (status) {
20923 	case 0:
20924 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20925 		break;	/* Success! */
20926 	case EIO:
20927 		switch (ucmd_buf.uscsi_status) {
20928 		case STATUS_RESERVATION_CONFLICT:
20929 			status = EACCES;
20930 			break;
20931 		default:
20932 			break;
20933 		}
20934 		break;
20935 	default:
20936 		break;
20937 	}
20938 
20939 	if (status == 0) {
20940 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
20941 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
20942 	}
20943 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
20944 
20945 	return (status);
20946 }
20947 
20948 
20949 /*
20950  *    Function: sd_send_scsi_RDWR
20951  *
20952  * Description: Issue a scsi READ or WRITE command with the given parameters.
20953  *
20954  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20955  *                      structure for this target.
20956  *		cmd:	 SCMD_READ or SCMD_WRITE
20957  *		bufaddr: Address of caller's buffer to receive the RDWR data
20958  *		buflen:  Length of caller's buffer receive the RDWR data.
20959  *		start_block: Block number for the start of the RDWR operation.
20960  *			 (Assumes target-native block size.)
20961  *		residp:  Pointer to variable to receive the redisual of the
20962  *			 RDWR operation (may be NULL of no residual requested).
20963  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20964  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20965  *			to use the USCSI "direct" chain and bypass the normal
20966  *			command waitq.
20967  *
20968  * Return Code: 0   - Success
20969  *		errno return code from sd_ssc_send()
20970  *
20971  *     Context: Can sleep. Does not return until command is completed.
20972  */
20973 
20974 static int
20975 sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
20976 	size_t buflen, daddr_t start_block, int path_flag)
20977 {
20978 	struct	scsi_extended_sense	sense_buf;
20979 	union scsi_cdb		cdb;
20980 	struct uscsi_cmd	ucmd_buf;
20981 	uint32_t		block_count;
20982 	int			status;
20983 	int			cdbsize;
20984 	uchar_t			flag;
20985 	struct sd_lun		*un;
20986 
20987 	ASSERT(ssc != NULL);
20988 	un = ssc->ssc_un;
20989 	ASSERT(un != NULL);
20990 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20991 	ASSERT(bufaddr != NULL);
20992 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
20993 
20994 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
20995 
20996 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
20997 		return (EINVAL);
20998 	}
20999 
21000 	mutex_enter(SD_MUTEX(un));
21001 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
21002 	mutex_exit(SD_MUTEX(un));
21003 
21004 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
21005 
21006 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
21007 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
21008 	    bufaddr, buflen, start_block, block_count);
21009 
21010 	bzero(&cdb, sizeof (cdb));
21011 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21012 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21013 
21014 	/* Compute CDB size to use */
21015 	if (start_block > 0xffffffff)
21016 		cdbsize = CDB_GROUP4;
21017 	else if ((start_block & 0xFFE00000) ||
21018 	    (un->un_f_cfg_is_atapi == TRUE))
21019 		cdbsize = CDB_GROUP1;
21020 	else
21021 		cdbsize = CDB_GROUP0;
21022 
21023 	switch (cdbsize) {
21024 	case CDB_GROUP0:	/* 6-byte CDBs */
21025 		cdb.scc_cmd = cmd;
21026 		FORMG0ADDR(&cdb, start_block);
21027 		FORMG0COUNT(&cdb, block_count);
21028 		break;
21029 	case CDB_GROUP1:	/* 10-byte CDBs */
21030 		cdb.scc_cmd = cmd | SCMD_GROUP1;
21031 		FORMG1ADDR(&cdb, start_block);
21032 		FORMG1COUNT(&cdb, block_count);
21033 		break;
21034 	case CDB_GROUP4:	/* 16-byte CDBs */
21035 		cdb.scc_cmd = cmd | SCMD_GROUP4;
21036 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
21037 		FORMG4COUNT(&cdb, block_count);
21038 		break;
21039 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
21040 	default:
21041 		/* All others reserved */
21042 		return (EINVAL);
21043 	}
21044 
21045 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
21046 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21047 
21048 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21049 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21050 	ucmd_buf.uscsi_bufaddr	= bufaddr;
21051 	ucmd_buf.uscsi_buflen	= buflen;
21052 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21053 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21054 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
21055 	ucmd_buf.uscsi_timeout	= 60;
21056 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21057 	    UIO_SYSSPACE, path_flag);
21058 
21059 	switch (status) {
21060 	case 0:
21061 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21062 		break;	/* Success! */
21063 	case EIO:
21064 		switch (ucmd_buf.uscsi_status) {
21065 		case STATUS_RESERVATION_CONFLICT:
21066 			status = EACCES;
21067 			break;
21068 		default:
21069 			break;
21070 		}
21071 		break;
21072 	default:
21073 		break;
21074 	}
21075 
21076 	if (status == 0) {
21077 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
21078 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21079 	}
21080 
21081 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
21082 
21083 	return (status);
21084 }
21085 
21086 
21087 /*
21088  *    Function: sd_send_scsi_LOG_SENSE
21089  *
21090  * Description: Issue a scsi LOG_SENSE command with the given parameters.
21091  *
21092  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21093  *                      structure for this target.
21094  *
21095  * Return Code: 0   - Success
21096  *		errno return code from sd_ssc_send()
21097  *
21098  *     Context: Can sleep. Does not return until command is completed.
21099  */
21100 
21101 static int
21102 sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr, uint16_t buflen,
21103 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
21104 	int path_flag)
21105 
21106 {
21107 	struct scsi_extended_sense	sense_buf;
21108 	union scsi_cdb		cdb;
21109 	struct uscsi_cmd	ucmd_buf;
21110 	int			status;
21111 	struct sd_lun		*un;
21112 
21113 	ASSERT(ssc != NULL);
21114 	un = ssc->ssc_un;
21115 	ASSERT(un != NULL);
21116 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21117 
21118 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
21119 
21120 	bzero(&cdb, sizeof (cdb));
21121 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21122 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21123 
21124 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
21125 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
21126 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
21127 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
21128 	FORMG1COUNT(&cdb, buflen);
21129 
21130 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21131 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
21132 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21133 	ucmd_buf.uscsi_buflen	= buflen;
21134 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21135 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21136 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21137 	ucmd_buf.uscsi_timeout	= 60;
21138 
21139 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21140 	    UIO_SYSSPACE, path_flag);
21141 
21142 	switch (status) {
21143 	case 0:
21144 		break;
21145 	case EIO:
21146 		switch (ucmd_buf.uscsi_status) {
21147 		case STATUS_RESERVATION_CONFLICT:
21148 			status = EACCES;
21149 			break;
21150 		case STATUS_CHECK:
21151 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21152 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21153 				KEY_ILLEGAL_REQUEST) &&
21154 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
21155 				/*
21156 				 * ASC 0x24: INVALID FIELD IN CDB
21157 				 */
21158 				switch (page_code) {
21159 				case START_STOP_CYCLE_PAGE:
21160 					/*
21161 					 * The start stop cycle counter is
21162 					 * implemented as page 0x31 in earlier
21163 					 * generation disks. In new generation
21164 					 * disks the start stop cycle counter is
21165 					 * implemented as page 0xE. To properly
21166 					 * handle this case if an attempt for
21167 					 * log page 0xE is made and fails we
21168 					 * will try again using page 0x31.
21169 					 *
21170 					 * Network storage BU committed to
21171 					 * maintain the page 0x31 for this
21172 					 * purpose and will not have any other
21173 					 * page implemented with page code 0x31
21174 					 * until all disks transition to the
21175 					 * standard page.
21176 					 */
21177 					mutex_enter(SD_MUTEX(un));
21178 					un->un_start_stop_cycle_page =
21179 					    START_STOP_CYCLE_VU_PAGE;
21180 					cdb.cdb_opaque[2] =
21181 					    (char)(page_control << 6) |
21182 					    un->un_start_stop_cycle_page;
21183 					mutex_exit(SD_MUTEX(un));
21184 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
21185 					status = sd_ssc_send(
21186 					    ssc, &ucmd_buf, FKIOCTL,
21187 					    UIO_SYSSPACE, path_flag);
21188 
21189 					break;
21190 				case TEMPERATURE_PAGE:
21191 					status = ENOTTY;
21192 					break;
21193 				default:
21194 					break;
21195 				}
21196 			}
21197 			break;
21198 		default:
21199 			break;
21200 		}
21201 		break;
21202 	default:
21203 		break;
21204 	}
21205 
21206 	if (status == 0) {
21207 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21208 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
21209 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21210 	}
21211 
21212 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
21213 
21214 	return (status);
21215 }
21216 
21217 
21218 /*
21219  *    Function: sdioctl
21220  *
21221  * Description: Driver's ioctl(9e) entry point function.
21222  *
21223  *   Arguments: dev     - device number
21224  *		cmd     - ioctl operation to be performed
21225  *		arg     - user argument, contains data to be set or reference
21226  *			  parameter for get
21227  *		flag    - bit flag, indicating open settings, 32/64 bit type
21228  *		cred_p  - user credential pointer
21229  *		rval_p  - calling process return value (OPT)
21230  *
21231  * Return Code: EINVAL
21232  *		ENOTTY
21233  *		ENXIO
21234  *		EIO
21235  *		EFAULT
21236  *		ENOTSUP
21237  *		EPERM
21238  *
21239  *     Context: Called from the device switch at normal priority.
21240  */
21241 
21242 static int
21243 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
21244 {
21245 	struct sd_lun	*un = NULL;
21246 	int		err = 0;
21247 	int		i = 0;
21248 	cred_t		*cr;
21249 	int		tmprval = EINVAL;
21250 	int 		is_valid;
21251 	sd_ssc_t	*ssc;
21252 
21253 	/*
21254 	 * All device accesses go thru sdstrategy where we check on suspend
21255 	 * status
21256 	 */
21257 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21258 		return (ENXIO);
21259 	}
21260 
21261 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21262 
21263 	/* Initialize sd_ssc_t for internal uscsi commands */
21264 	ssc = sd_ssc_init(un);
21265 
21266 	is_valid = SD_IS_VALID_LABEL(un);
21267 
21268 	/*
21269 	 * Moved this wait from sd_uscsi_strategy to here for
21270 	 * reasons of deadlock prevention. Internal driver commands,
21271 	 * specifically those to change a devices power level, result
21272 	 * in a call to sd_uscsi_strategy.
21273 	 */
21274 	mutex_enter(SD_MUTEX(un));
21275 	while ((un->un_state == SD_STATE_SUSPENDED) ||
21276 	    (un->un_state == SD_STATE_PM_CHANGING)) {
21277 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
21278 	}
21279 	/*
21280 	 * Twiddling the counter here protects commands from now
21281 	 * through to the top of sd_uscsi_strategy. Without the
21282 	 * counter inc. a power down, for example, could get in
21283 	 * after the above check for state is made and before
21284 	 * execution gets to the top of sd_uscsi_strategy.
21285 	 * That would cause problems.
21286 	 */
21287 	un->un_ncmds_in_driver++;
21288 
21289 	if (!is_valid &&
21290 	    (flag & (FNDELAY | FNONBLOCK))) {
21291 		switch (cmd) {
21292 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
21293 		case DKIOCGVTOC:
21294 		case DKIOCGEXTVTOC:
21295 		case DKIOCGAPART:
21296 		case DKIOCPARTINFO:
21297 		case DKIOCEXTPARTINFO:
21298 		case DKIOCSGEOM:
21299 		case DKIOCSAPART:
21300 		case DKIOCGETEFI:
21301 		case DKIOCPARTITION:
21302 		case DKIOCSVTOC:
21303 		case DKIOCSEXTVTOC:
21304 		case DKIOCSETEFI:
21305 		case DKIOCGMBOOT:
21306 		case DKIOCSMBOOT:
21307 		case DKIOCG_PHYGEOM:
21308 		case DKIOCG_VIRTGEOM:
21309 #if defined(__i386) || defined(__amd64)
21310 		case DKIOCSETEXTPART:
21311 #endif
21312 			/* let cmlb handle it */
21313 			goto skip_ready_valid;
21314 
21315 		case CDROMPAUSE:
21316 		case CDROMRESUME:
21317 		case CDROMPLAYMSF:
21318 		case CDROMPLAYTRKIND:
21319 		case CDROMREADTOCHDR:
21320 		case CDROMREADTOCENTRY:
21321 		case CDROMSTOP:
21322 		case CDROMSTART:
21323 		case CDROMVOLCTRL:
21324 		case CDROMSUBCHNL:
21325 		case CDROMREADMODE2:
21326 		case CDROMREADMODE1:
21327 		case CDROMREADOFFSET:
21328 		case CDROMSBLKMODE:
21329 		case CDROMGBLKMODE:
21330 		case CDROMGDRVSPEED:
21331 		case CDROMSDRVSPEED:
21332 		case CDROMCDDA:
21333 		case CDROMCDXA:
21334 		case CDROMSUBCODE:
21335 			if (!ISCD(un)) {
21336 				un->un_ncmds_in_driver--;
21337 				ASSERT(un->un_ncmds_in_driver >= 0);
21338 				mutex_exit(SD_MUTEX(un));
21339 				err = ENOTTY;
21340 				goto done_without_assess;
21341 			}
21342 			break;
21343 		case FDEJECT:
21344 		case DKIOCEJECT:
21345 		case CDROMEJECT:
21346 			if (!un->un_f_eject_media_supported) {
21347 				un->un_ncmds_in_driver--;
21348 				ASSERT(un->un_ncmds_in_driver >= 0);
21349 				mutex_exit(SD_MUTEX(un));
21350 				err = ENOTTY;
21351 				goto done_without_assess;
21352 			}
21353 			break;
21354 		case DKIOCFLUSHWRITECACHE:
21355 			mutex_exit(SD_MUTEX(un));
21356 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
21357 			if (err != 0) {
21358 				mutex_enter(SD_MUTEX(un));
21359 				un->un_ncmds_in_driver--;
21360 				ASSERT(un->un_ncmds_in_driver >= 0);
21361 				mutex_exit(SD_MUTEX(un));
21362 				err = EIO;
21363 				goto done_quick_assess;
21364 			}
21365 			mutex_enter(SD_MUTEX(un));
21366 			/* FALLTHROUGH */
21367 		case DKIOCREMOVABLE:
21368 		case DKIOCHOTPLUGGABLE:
21369 		case DKIOCINFO:
21370 		case DKIOCGMEDIAINFO:
21371 		case MHIOCENFAILFAST:
21372 		case MHIOCSTATUS:
21373 		case MHIOCTKOWN:
21374 		case MHIOCRELEASE:
21375 		case MHIOCGRP_INKEYS:
21376 		case MHIOCGRP_INRESV:
21377 		case MHIOCGRP_REGISTER:
21378 		case MHIOCGRP_RESERVE:
21379 		case MHIOCGRP_PREEMPTANDABORT:
21380 		case MHIOCGRP_REGISTERANDIGNOREKEY:
21381 		case CDROMCLOSETRAY:
21382 		case USCSICMD:
21383 			goto skip_ready_valid;
21384 		default:
21385 			break;
21386 		}
21387 
21388 		mutex_exit(SD_MUTEX(un));
21389 		err = sd_ready_and_valid(ssc, SDPART(dev));
21390 		mutex_enter(SD_MUTEX(un));
21391 
21392 		if (err != SD_READY_VALID) {
21393 			switch (cmd) {
21394 			case DKIOCSTATE:
21395 			case CDROMGDRVSPEED:
21396 			case CDROMSDRVSPEED:
21397 			case FDEJECT:	/* for eject command */
21398 			case DKIOCEJECT:
21399 			case CDROMEJECT:
21400 			case DKIOCREMOVABLE:
21401 			case DKIOCHOTPLUGGABLE:
21402 				break;
21403 			default:
21404 				if (un->un_f_has_removable_media) {
21405 					err = ENXIO;
21406 				} else {
21407 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
21408 					if (err == SD_RESERVED_BY_OTHERS) {
21409 						err = EACCES;
21410 					} else {
21411 						err = EIO;
21412 					}
21413 				}
21414 				un->un_ncmds_in_driver--;
21415 				ASSERT(un->un_ncmds_in_driver >= 0);
21416 				mutex_exit(SD_MUTEX(un));
21417 
21418 				goto done_without_assess;
21419 			}
21420 		}
21421 	}
21422 
21423 skip_ready_valid:
21424 	mutex_exit(SD_MUTEX(un));
21425 
21426 	switch (cmd) {
21427 	case DKIOCINFO:
21428 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
21429 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
21430 		break;
21431 
21432 	case DKIOCGMEDIAINFO:
21433 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
21434 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
21435 		break;
21436 
21437 	case DKIOCGGEOM:
21438 	case DKIOCGVTOC:
21439 	case DKIOCGEXTVTOC:
21440 	case DKIOCGAPART:
21441 	case DKIOCPARTINFO:
21442 	case DKIOCEXTPARTINFO:
21443 	case DKIOCSGEOM:
21444 	case DKIOCSAPART:
21445 	case DKIOCGETEFI:
21446 	case DKIOCPARTITION:
21447 	case DKIOCSVTOC:
21448 	case DKIOCSEXTVTOC:
21449 	case DKIOCSETEFI:
21450 	case DKIOCGMBOOT:
21451 	case DKIOCSMBOOT:
21452 	case DKIOCG_PHYGEOM:
21453 	case DKIOCG_VIRTGEOM:
21454 #if defined(__i386) || defined(__amd64)
21455 	case DKIOCSETEXTPART:
21456 #endif
21457 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
21458 
21459 		/* TUR should spin up */
21460 
21461 		if (un->un_f_has_removable_media)
21462 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
21463 			    SD_CHECK_FOR_MEDIA);
21464 
21465 		else
21466 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
21467 
21468 		if (err != 0)
21469 			goto done_with_assess;
21470 
21471 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
21472 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
21473 
21474 		if ((err == 0) &&
21475 		    ((cmd == DKIOCSETEFI) ||
21476 		    (un->un_f_pkstats_enabled) &&
21477 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
21478 		    cmd == DKIOCSEXTVTOC))) {
21479 
21480 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
21481 			    (void *)SD_PATH_DIRECT);
21482 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
21483 				sd_set_pstats(un);
21484 				SD_TRACE(SD_LOG_IO_PARTITION, un,
21485 				    "sd_ioctl: un:0x%p pstats created and "
21486 				    "set\n", un);
21487 			}
21488 		}
21489 
21490 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
21491 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
21492 
21493 			mutex_enter(SD_MUTEX(un));
21494 			if (un->un_f_devid_supported &&
21495 			    (un->un_f_opt_fab_devid == TRUE)) {
21496 				if (un->un_devid == NULL) {
21497 					sd_register_devid(ssc, SD_DEVINFO(un),
21498 					    SD_TARGET_IS_UNRESERVED);
21499 				} else {
21500 					/*
21501 					 * The device id for this disk
21502 					 * has been fabricated. The
21503 					 * device id must be preserved
21504 					 * by writing it back out to
21505 					 * disk.
21506 					 */
21507 					if (sd_write_deviceid(ssc) != 0) {
21508 						ddi_devid_free(un->un_devid);
21509 						un->un_devid = NULL;
21510 					}
21511 				}
21512 			}
21513 			mutex_exit(SD_MUTEX(un));
21514 		}
21515 
21516 		break;
21517 
21518 	case DKIOCLOCK:
21519 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
21520 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
21521 		    SD_PATH_STANDARD);
21522 		goto done_with_assess;
21523 
21524 	case DKIOCUNLOCK:
21525 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
21526 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
21527 		    SD_PATH_STANDARD);
21528 		goto done_with_assess;
21529 
21530 	case DKIOCSTATE: {
21531 		enum dkio_state		state;
21532 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
21533 
21534 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
21535 			err = EFAULT;
21536 		} else {
21537 			err = sd_check_media(dev, state);
21538 			if (err == 0) {
21539 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
21540 				    sizeof (int), flag) != 0)
21541 					err = EFAULT;
21542 			}
21543 		}
21544 		break;
21545 	}
21546 
21547 	case DKIOCREMOVABLE:
21548 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
21549 		i = un->un_f_has_removable_media ? 1 : 0;
21550 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
21551 			err = EFAULT;
21552 		} else {
21553 			err = 0;
21554 		}
21555 		break;
21556 
21557 	case DKIOCHOTPLUGGABLE:
21558 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
21559 		i = un->un_f_is_hotpluggable ? 1 : 0;
21560 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
21561 			err = EFAULT;
21562 		} else {
21563 			err = 0;
21564 		}
21565 		break;
21566 
21567 	case DKIOCGTEMPERATURE:
21568 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
21569 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
21570 		break;
21571 
21572 	case MHIOCENFAILFAST:
21573 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
21574 		if ((err = drv_priv(cred_p)) == 0) {
21575 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
21576 		}
21577 		break;
21578 
21579 	case MHIOCTKOWN:
21580 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
21581 		if ((err = drv_priv(cred_p)) == 0) {
21582 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
21583 		}
21584 		break;
21585 
21586 	case MHIOCRELEASE:
21587 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
21588 		if ((err = drv_priv(cred_p)) == 0) {
21589 			err = sd_mhdioc_release(dev);
21590 		}
21591 		break;
21592 
21593 	case MHIOCSTATUS:
21594 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
21595 		if ((err = drv_priv(cred_p)) == 0) {
21596 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
21597 			case 0:
21598 				err = 0;
21599 				break;
21600 			case EACCES:
21601 				*rval_p = 1;
21602 				err = 0;
21603 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
21604 				break;
21605 			default:
21606 				err = EIO;
21607 				goto done_with_assess;
21608 			}
21609 		}
21610 		break;
21611 
21612 	case MHIOCQRESERVE:
21613 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
21614 		if ((err = drv_priv(cred_p)) == 0) {
21615 			err = sd_reserve_release(dev, SD_RESERVE);
21616 		}
21617 		break;
21618 
21619 	case MHIOCREREGISTERDEVID:
21620 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
21621 		if (drv_priv(cred_p) == EPERM) {
21622 			err = EPERM;
21623 		} else if (!un->un_f_devid_supported) {
21624 			err = ENOTTY;
21625 		} else {
21626 			err = sd_mhdioc_register_devid(dev);
21627 		}
21628 		break;
21629 
21630 	case MHIOCGRP_INKEYS:
21631 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
21632 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
21633 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21634 				err = ENOTSUP;
21635 			} else {
21636 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
21637 				    flag);
21638 			}
21639 		}
21640 		break;
21641 
21642 	case MHIOCGRP_INRESV:
21643 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
21644 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
21645 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21646 				err = ENOTSUP;
21647 			} else {
21648 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
21649 			}
21650 		}
21651 		break;
21652 
21653 	case MHIOCGRP_REGISTER:
21654 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
21655 		if ((err = drv_priv(cred_p)) != EPERM) {
21656 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21657 				err = ENOTSUP;
21658 			} else if (arg != NULL) {
21659 				mhioc_register_t reg;
21660 				if (ddi_copyin((void *)arg, &reg,
21661 				    sizeof (mhioc_register_t), flag) != 0) {
21662 					err = EFAULT;
21663 				} else {
21664 					err =
21665 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21666 					    ssc, SD_SCSI3_REGISTER,
21667 					    (uchar_t *)&reg);
21668 					if (err != 0)
21669 						goto done_with_assess;
21670 				}
21671 			}
21672 		}
21673 		break;
21674 
21675 	case MHIOCGRP_RESERVE:
21676 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
21677 		if ((err = drv_priv(cred_p)) != EPERM) {
21678 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21679 				err = ENOTSUP;
21680 			} else if (arg != NULL) {
21681 				mhioc_resv_desc_t resv_desc;
21682 				if (ddi_copyin((void *)arg, &resv_desc,
21683 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
21684 					err = EFAULT;
21685 				} else {
21686 					err =
21687 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21688 					    ssc, SD_SCSI3_RESERVE,
21689 					    (uchar_t *)&resv_desc);
21690 					if (err != 0)
21691 						goto done_with_assess;
21692 				}
21693 			}
21694 		}
21695 		break;
21696 
21697 	case MHIOCGRP_PREEMPTANDABORT:
21698 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
21699 		if ((err = drv_priv(cred_p)) != EPERM) {
21700 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21701 				err = ENOTSUP;
21702 			} else if (arg != NULL) {
21703 				mhioc_preemptandabort_t preempt_abort;
21704 				if (ddi_copyin((void *)arg, &preempt_abort,
21705 				    sizeof (mhioc_preemptandabort_t),
21706 				    flag) != 0) {
21707 					err = EFAULT;
21708 				} else {
21709 					err =
21710 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21711 					    ssc, SD_SCSI3_PREEMPTANDABORT,
21712 					    (uchar_t *)&preempt_abort);
21713 					if (err != 0)
21714 						goto done_with_assess;
21715 				}
21716 			}
21717 		}
21718 		break;
21719 
21720 	case MHIOCGRP_REGISTERANDIGNOREKEY:
21721 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
21722 		if ((err = drv_priv(cred_p)) != EPERM) {
21723 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21724 				err = ENOTSUP;
21725 			} else if (arg != NULL) {
21726 				mhioc_registerandignorekey_t r_and_i;
21727 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
21728 				    sizeof (mhioc_registerandignorekey_t),
21729 				    flag) != 0) {
21730 					err = EFAULT;
21731 				} else {
21732 					err =
21733 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21734 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
21735 					    (uchar_t *)&r_and_i);
21736 					if (err != 0)
21737 						goto done_with_assess;
21738 				}
21739 			}
21740 		}
21741 		break;
21742 
21743 	case USCSICMD:
21744 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
21745 		cr = ddi_get_cred();
21746 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
21747 			err = EPERM;
21748 		} else {
21749 			enum uio_seg	uioseg;
21750 
21751 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
21752 			    UIO_USERSPACE;
21753 			if (un->un_f_format_in_progress == TRUE) {
21754 				err = EAGAIN;
21755 				break;
21756 			}
21757 
21758 			err = sd_ssc_send(ssc,
21759 			    (struct uscsi_cmd *)arg,
21760 			    flag, uioseg, SD_PATH_STANDARD);
21761 			if (err != 0)
21762 				goto done_with_assess;
21763 			else
21764 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21765 		}
21766 		break;
21767 
21768 	case CDROMPAUSE:
21769 	case CDROMRESUME:
21770 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
21771 		if (!ISCD(un)) {
21772 			err = ENOTTY;
21773 		} else {
21774 			err = sr_pause_resume(dev, cmd);
21775 		}
21776 		break;
21777 
21778 	case CDROMPLAYMSF:
21779 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
21780 		if (!ISCD(un)) {
21781 			err = ENOTTY;
21782 		} else {
21783 			err = sr_play_msf(dev, (caddr_t)arg, flag);
21784 		}
21785 		break;
21786 
21787 	case CDROMPLAYTRKIND:
21788 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
21789 #if defined(__i386) || defined(__amd64)
21790 		/*
21791 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
21792 		 */
21793 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
21794 #else
21795 		if (!ISCD(un)) {
21796 #endif
21797 			err = ENOTTY;
21798 		} else {
21799 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
21800 		}
21801 		break;
21802 
21803 	case CDROMREADTOCHDR:
21804 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
21805 		if (!ISCD(un)) {
21806 			err = ENOTTY;
21807 		} else {
21808 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
21809 		}
21810 		break;
21811 
21812 	case CDROMREADTOCENTRY:
21813 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
21814 		if (!ISCD(un)) {
21815 			err = ENOTTY;
21816 		} else {
21817 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
21818 		}
21819 		break;
21820 
21821 	case CDROMSTOP:
21822 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
21823 		if (!ISCD(un)) {
21824 			err = ENOTTY;
21825 		} else {
21826 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_STOP,
21827 			    SD_PATH_STANDARD);
21828 			goto done_with_assess;
21829 		}
21830 		break;
21831 
21832 	case CDROMSTART:
21833 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
21834 		if (!ISCD(un)) {
21835 			err = ENOTTY;
21836 		} else {
21837 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_START,
21838 			    SD_PATH_STANDARD);
21839 			goto done_with_assess;
21840 		}
21841 		break;
21842 
21843 	case CDROMCLOSETRAY:
21844 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
21845 		if (!ISCD(un)) {
21846 			err = ENOTTY;
21847 		} else {
21848 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_CLOSE,
21849 			    SD_PATH_STANDARD);
21850 			goto done_with_assess;
21851 		}
21852 		break;
21853 
21854 	case FDEJECT:	/* for eject command */
21855 	case DKIOCEJECT:
21856 	case CDROMEJECT:
21857 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
21858 		if (!un->un_f_eject_media_supported) {
21859 			err = ENOTTY;
21860 		} else {
21861 			err = sr_eject(dev);
21862 		}
21863 		break;
21864 
21865 	case CDROMVOLCTRL:
21866 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
21867 		if (!ISCD(un)) {
21868 			err = ENOTTY;
21869 		} else {
21870 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
21871 		}
21872 		break;
21873 
21874 	case CDROMSUBCHNL:
21875 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
21876 		if (!ISCD(un)) {
21877 			err = ENOTTY;
21878 		} else {
21879 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
21880 		}
21881 		break;
21882 
21883 	case CDROMREADMODE2:
21884 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
21885 		if (!ISCD(un)) {
21886 			err = ENOTTY;
21887 		} else if (un->un_f_cfg_is_atapi == TRUE) {
21888 			/*
21889 			 * If the drive supports READ CD, use that instead of
21890 			 * switching the LBA size via a MODE SELECT
21891 			 * Block Descriptor
21892 			 */
21893 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
21894 		} else {
21895 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
21896 		}
21897 		break;
21898 
21899 	case CDROMREADMODE1:
21900 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
21901 		if (!ISCD(un)) {
21902 			err = ENOTTY;
21903 		} else {
21904 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
21905 		}
21906 		break;
21907 
21908 	case CDROMREADOFFSET:
21909 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
21910 		if (!ISCD(un)) {
21911 			err = ENOTTY;
21912 		} else {
21913 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
21914 			    flag);
21915 		}
21916 		break;
21917 
21918 	case CDROMSBLKMODE:
21919 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
21920 		/*
21921 		 * There is no means of changing block size in case of atapi
21922 		 * drives, thus return ENOTTY if drive type is atapi
21923 		 */
21924 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
21925 			err = ENOTTY;
21926 		} else if (un->un_f_mmc_cap == TRUE) {
21927 
21928 			/*
21929 			 * MMC Devices do not support changing the
21930 			 * logical block size
21931 			 *
21932 			 * Note: EINVAL is being returned instead of ENOTTY to
21933 			 * maintain consistancy with the original mmc
21934 			 * driver update.
21935 			 */
21936 			err = EINVAL;
21937 		} else {
21938 			mutex_enter(SD_MUTEX(un));
21939 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
21940 			    (un->un_ncmds_in_transport > 0)) {
21941 				mutex_exit(SD_MUTEX(un));
21942 				err = EINVAL;
21943 			} else {
21944 				mutex_exit(SD_MUTEX(un));
21945 				err = sr_change_blkmode(dev, cmd, arg, flag);
21946 			}
21947 		}
21948 		break;
21949 
21950 	case CDROMGBLKMODE:
21951 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
21952 		if (!ISCD(un)) {
21953 			err = ENOTTY;
21954 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
21955 		    (un->un_f_blockcount_is_valid != FALSE)) {
21956 			/*
21957 			 * Drive is an ATAPI drive so return target block
21958 			 * size for ATAPI drives since we cannot change the
21959 			 * blocksize on ATAPI drives. Used primarily to detect
21960 			 * if an ATAPI cdrom is present.
21961 			 */
21962 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
21963 			    sizeof (int), flag) != 0) {
21964 				err = EFAULT;
21965 			} else {
21966 				err = 0;
21967 			}
21968 
21969 		} else {
21970 			/*
21971 			 * Drive supports changing block sizes via a Mode
21972 			 * Select.
21973 			 */
21974 			err = sr_change_blkmode(dev, cmd, arg, flag);
21975 		}
21976 		break;
21977 
21978 	case CDROMGDRVSPEED:
21979 	case CDROMSDRVSPEED:
21980 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
21981 		if (!ISCD(un)) {
21982 			err = ENOTTY;
21983 		} else if (un->un_f_mmc_cap == TRUE) {
21984 			/*
21985 			 * Note: In the future the driver implementation
21986 			 * for getting and
21987 			 * setting cd speed should entail:
21988 			 * 1) If non-mmc try the Toshiba mode page
21989 			 *    (sr_change_speed)
21990 			 * 2) If mmc but no support for Real Time Streaming try
21991 			 *    the SET CD SPEED (0xBB) command
21992 			 *   (sr_atapi_change_speed)
21993 			 * 3) If mmc and support for Real Time Streaming
21994 			 *    try the GET PERFORMANCE and SET STREAMING
21995 			 *    commands (not yet implemented, 4380808)
21996 			 */
21997 			/*
21998 			 * As per recent MMC spec, CD-ROM speed is variable
21999 			 * and changes with LBA. Since there is no such
22000 			 * things as drive speed now, fail this ioctl.
22001 			 *
22002 			 * Note: EINVAL is returned for consistancy of original
22003 			 * implementation which included support for getting
22004 			 * the drive speed of mmc devices but not setting
22005 			 * the drive speed. Thus EINVAL would be returned
22006 			 * if a set request was made for an mmc device.
22007 			 * We no longer support get or set speed for
22008 			 * mmc but need to remain consistent with regard
22009 			 * to the error code returned.
22010 			 */
22011 			err = EINVAL;
22012 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22013 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
22014 		} else {
22015 			err = sr_change_speed(dev, cmd, arg, flag);
22016 		}
22017 		break;
22018 
22019 	case CDROMCDDA:
22020 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
22021 		if (!ISCD(un)) {
22022 			err = ENOTTY;
22023 		} else {
22024 			err = sr_read_cdda(dev, (void *)arg, flag);
22025 		}
22026 		break;
22027 
22028 	case CDROMCDXA:
22029 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
22030 		if (!ISCD(un)) {
22031 			err = ENOTTY;
22032 		} else {
22033 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
22034 		}
22035 		break;
22036 
22037 	case CDROMSUBCODE:
22038 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
22039 		if (!ISCD(un)) {
22040 			err = ENOTTY;
22041 		} else {
22042 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
22043 		}
22044 		break;
22045 
22046 
22047 #ifdef SDDEBUG
22048 /* RESET/ABORTS testing ioctls */
22049 	case DKIOCRESET: {
22050 		int	reset_level;
22051 
22052 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
22053 			err = EFAULT;
22054 		} else {
22055 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
22056 			    "reset_level = 0x%lx\n", reset_level);
22057 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
22058 				err = 0;
22059 			} else {
22060 				err = EIO;
22061 			}
22062 		}
22063 		break;
22064 	}
22065 
22066 	case DKIOCABORT:
22067 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
22068 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
22069 			err = 0;
22070 		} else {
22071 			err = EIO;
22072 		}
22073 		break;
22074 #endif
22075 
22076 #ifdef SD_FAULT_INJECTION
22077 /* SDIOC FaultInjection testing ioctls */
22078 	case SDIOCSTART:
22079 	case SDIOCSTOP:
22080 	case SDIOCINSERTPKT:
22081 	case SDIOCINSERTXB:
22082 	case SDIOCINSERTUN:
22083 	case SDIOCINSERTARQ:
22084 	case SDIOCPUSH:
22085 	case SDIOCRETRIEVE:
22086 	case SDIOCRUN:
22087 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
22088 		    "SDIOC detected cmd:0x%X:\n", cmd);
22089 		/* call error generator */
22090 		sd_faultinjection_ioctl(cmd, arg, un);
22091 		err = 0;
22092 		break;
22093 
22094 #endif /* SD_FAULT_INJECTION */
22095 
22096 	case DKIOCFLUSHWRITECACHE:
22097 		{
22098 			struct dk_callback *dkc = (struct dk_callback *)arg;
22099 
22100 			mutex_enter(SD_MUTEX(un));
22101 			if (!un->un_f_sync_cache_supported ||
22102 			    !un->un_f_write_cache_enabled) {
22103 				err = un->un_f_sync_cache_supported ?
22104 				    0 : ENOTSUP;
22105 				mutex_exit(SD_MUTEX(un));
22106 				if ((flag & FKIOCTL) && dkc != NULL &&
22107 				    dkc->dkc_callback != NULL) {
22108 					(*dkc->dkc_callback)(dkc->dkc_cookie,
22109 					    err);
22110 					/*
22111 					 * Did callback and reported error.
22112 					 * Since we did a callback, ioctl
22113 					 * should return 0.
22114 					 */
22115 					err = 0;
22116 				}
22117 				break;
22118 			}
22119 			mutex_exit(SD_MUTEX(un));
22120 
22121 			if ((flag & FKIOCTL) && dkc != NULL &&
22122 			    dkc->dkc_callback != NULL) {
22123 				/* async SYNC CACHE request */
22124 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
22125 			} else {
22126 				/* synchronous SYNC CACHE request */
22127 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
22128 			}
22129 		}
22130 		break;
22131 
22132 	case DKIOCGETWCE: {
22133 
22134 		int wce;
22135 
22136 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
22137 			break;
22138 		}
22139 
22140 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
22141 			err = EFAULT;
22142 		}
22143 		break;
22144 	}
22145 
22146 	case DKIOCSETWCE: {
22147 
22148 		int wce, sync_supported;
22149 
22150 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
22151 			err = EFAULT;
22152 			break;
22153 		}
22154 
22155 		/*
22156 		 * Synchronize multiple threads trying to enable
22157 		 * or disable the cache via the un_f_wcc_cv
22158 		 * condition variable.
22159 		 */
22160 		mutex_enter(SD_MUTEX(un));
22161 
22162 		/*
22163 		 * Don't allow the cache to be enabled if the
22164 		 * config file has it disabled.
22165 		 */
22166 		if (un->un_f_opt_disable_cache && wce) {
22167 			mutex_exit(SD_MUTEX(un));
22168 			err = EINVAL;
22169 			break;
22170 		}
22171 
22172 		/*
22173 		 * Wait for write cache change in progress
22174 		 * bit to be clear before proceeding.
22175 		 */
22176 		while (un->un_f_wcc_inprog)
22177 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
22178 
22179 		un->un_f_wcc_inprog = 1;
22180 
22181 		if (un->un_f_write_cache_enabled && wce == 0) {
22182 			/*
22183 			 * Disable the write cache.  Don't clear
22184 			 * un_f_write_cache_enabled until after
22185 			 * the mode select and flush are complete.
22186 			 */
22187 			sync_supported = un->un_f_sync_cache_supported;
22188 
22189 			/*
22190 			 * If cache flush is suppressed, we assume that the
22191 			 * controller firmware will take care of managing the
22192 			 * write cache for us: no need to explicitly
22193 			 * disable it.
22194 			 */
22195 			if (!un->un_f_suppress_cache_flush) {
22196 				mutex_exit(SD_MUTEX(un));
22197 				if ((err = sd_cache_control(ssc,
22198 				    SD_CACHE_NOCHANGE,
22199 				    SD_CACHE_DISABLE)) == 0 &&
22200 				    sync_supported) {
22201 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
22202 					    NULL);
22203 				}
22204 			} else {
22205 				mutex_exit(SD_MUTEX(un));
22206 			}
22207 
22208 			mutex_enter(SD_MUTEX(un));
22209 			if (err == 0) {
22210 				un->un_f_write_cache_enabled = 0;
22211 			}
22212 
22213 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
22214 			/*
22215 			 * Set un_f_write_cache_enabled first, so there is
22216 			 * no window where the cache is enabled, but the
22217 			 * bit says it isn't.
22218 			 */
22219 			un->un_f_write_cache_enabled = 1;
22220 
22221 			/*
22222 			 * If cache flush is suppressed, we assume that the
22223 			 * controller firmware will take care of managing the
22224 			 * write cache for us: no need to explicitly
22225 			 * enable it.
22226 			 */
22227 			if (!un->un_f_suppress_cache_flush) {
22228 				mutex_exit(SD_MUTEX(un));
22229 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
22230 				    SD_CACHE_ENABLE);
22231 			} else {
22232 				mutex_exit(SD_MUTEX(un));
22233 			}
22234 
22235 			mutex_enter(SD_MUTEX(un));
22236 
22237 			if (err) {
22238 				un->un_f_write_cache_enabled = 0;
22239 			}
22240 		}
22241 
22242 		un->un_f_wcc_inprog = 0;
22243 		cv_broadcast(&un->un_wcc_cv);
22244 		mutex_exit(SD_MUTEX(un));
22245 		break;
22246 	}
22247 
22248 	default:
22249 		err = ENOTTY;
22250 		break;
22251 	}
22252 	mutex_enter(SD_MUTEX(un));
22253 	un->un_ncmds_in_driver--;
22254 	ASSERT(un->un_ncmds_in_driver >= 0);
22255 	mutex_exit(SD_MUTEX(un));
22256 
22257 
22258 done_without_assess:
22259 	sd_ssc_fini(ssc);
22260 
22261 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
22262 	return (err);
22263 
22264 done_with_assess:
22265 	mutex_enter(SD_MUTEX(un));
22266 	un->un_ncmds_in_driver--;
22267 	ASSERT(un->un_ncmds_in_driver >= 0);
22268 	mutex_exit(SD_MUTEX(un));
22269 
22270 done_quick_assess:
22271 	if (err != 0)
22272 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22273 	/* Uninitialize sd_ssc_t pointer */
22274 	sd_ssc_fini(ssc);
22275 
22276 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
22277 	return (err);
22278 }
22279 
22280 
22281 /*
22282  *    Function: sd_dkio_ctrl_info
22283  *
22284  * Description: This routine is the driver entry point for handling controller
22285  *		information ioctl requests (DKIOCINFO).
22286  *
22287  *   Arguments: dev  - the device number
22288  *		arg  - pointer to user provided dk_cinfo structure
22289  *		       specifying the controller type and attributes.
22290  *		flag - this argument is a pass through to ddi_copyxxx()
22291  *		       directly from the mode argument of ioctl().
22292  *
22293  * Return Code: 0
22294  *		EFAULT
22295  *		ENXIO
22296  */
22297 
22298 static int
22299 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
22300 {
22301 	struct sd_lun	*un = NULL;
22302 	struct dk_cinfo	*info;
22303 	dev_info_t	*pdip;
22304 	int		lun, tgt;
22305 
22306 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22307 		return (ENXIO);
22308 	}
22309 
22310 	info = (struct dk_cinfo *)
22311 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
22312 
22313 	switch (un->un_ctype) {
22314 	case CTYPE_CDROM:
22315 		info->dki_ctype = DKC_CDROM;
22316 		break;
22317 	default:
22318 		info->dki_ctype = DKC_SCSI_CCS;
22319 		break;
22320 	}
22321 	pdip = ddi_get_parent(SD_DEVINFO(un));
22322 	info->dki_cnum = ddi_get_instance(pdip);
22323 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
22324 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
22325 	} else {
22326 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
22327 		    DK_DEVLEN - 1);
22328 	}
22329 
22330 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22331 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
22332 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22333 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
22334 
22335 	/* Unit Information */
22336 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
22337 	info->dki_slave = ((tgt << 3) | lun);
22338 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
22339 	    DK_DEVLEN - 1);
22340 	info->dki_flags = DKI_FMTVOL;
22341 	info->dki_partition = SDPART(dev);
22342 
22343 	/* Max Transfer size of this device in blocks */
22344 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
22345 	info->dki_addr = 0;
22346 	info->dki_space = 0;
22347 	info->dki_prio = 0;
22348 	info->dki_vec = 0;
22349 
22350 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
22351 		kmem_free(info, sizeof (struct dk_cinfo));
22352 		return (EFAULT);
22353 	} else {
22354 		kmem_free(info, sizeof (struct dk_cinfo));
22355 		return (0);
22356 	}
22357 }
22358 
22359 
22360 /*
22361  *    Function: sd_get_media_info
22362  *
22363  * Description: This routine is the driver entry point for handling ioctl
22364  *		requests for the media type or command set profile used by the
22365  *		drive to operate on the media (DKIOCGMEDIAINFO).
22366  *
22367  *   Arguments: dev	- the device number
22368  *		arg	- pointer to user provided dk_minfo structure
22369  *			  specifying the media type, logical block size and
22370  *			  drive capacity.
22371  *		flag	- this argument is a pass through to ddi_copyxxx()
22372  *			  directly from the mode argument of ioctl().
22373  *
22374  * Return Code: 0
22375  *		EACCESS
22376  *		EFAULT
22377  *		ENXIO
22378  *		EIO
22379  */
22380 
22381 static int
22382 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
22383 {
22384 	struct sd_lun		*un = NULL;
22385 	struct uscsi_cmd	com;
22386 	struct scsi_inquiry	*sinq;
22387 	struct dk_minfo		media_info;
22388 	u_longlong_t		media_capacity;
22389 	uint64_t		capacity;
22390 	uint_t			lbasize;
22391 	uchar_t			*out_data;
22392 	uchar_t			*rqbuf;
22393 	int			rval = 0;
22394 	int			rtn;
22395 	sd_ssc_t		*ssc;
22396 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
22397 	    (un->un_state == SD_STATE_OFFLINE)) {
22398 		return (ENXIO);
22399 	}
22400 
22401 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
22402 
22403 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
22404 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
22405 
22406 	/* Issue a TUR to determine if the drive is ready with media present */
22407 	ssc = sd_ssc_init(un);
22408 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
22409 	if (rval == ENXIO) {
22410 		goto done;
22411 	} else if (rval != 0) {
22412 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22413 	}
22414 
22415 	/* Now get configuration data */
22416 	if (ISCD(un)) {
22417 		media_info.dki_media_type = DK_CDROM;
22418 
22419 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
22420 		if (un->un_f_mmc_cap == TRUE) {
22421 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
22422 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
22423 			    SD_PATH_STANDARD);
22424 
22425 			if (rtn) {
22426 				/*
22427 				 * We ignore all failures for CD and need to
22428 				 * put the assessment before processing code
22429 				 * to avoid missing assessment for FMA.
22430 				 */
22431 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22432 				/*
22433 				 * Failed for other than an illegal request
22434 				 * or command not supported
22435 				 */
22436 				if ((com.uscsi_status == STATUS_CHECK) &&
22437 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
22438 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
22439 					    (rqbuf[12] != 0x20)) {
22440 						rval = EIO;
22441 						goto no_assessment;
22442 					}
22443 				}
22444 			} else {
22445 				/*
22446 				 * The GET CONFIGURATION command succeeded
22447 				 * so set the media type according to the
22448 				 * returned data
22449 				 */
22450 				media_info.dki_media_type = out_data[6];
22451 				media_info.dki_media_type <<= 8;
22452 				media_info.dki_media_type |= out_data[7];
22453 			}
22454 		}
22455 	} else {
22456 		/*
22457 		 * The profile list is not available, so we attempt to identify
22458 		 * the media type based on the inquiry data
22459 		 */
22460 		sinq = un->un_sd->sd_inq;
22461 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
22462 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
22463 			/* This is a direct access device  or optical disk */
22464 			media_info.dki_media_type = DK_FIXED_DISK;
22465 
22466 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
22467 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
22468 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
22469 					media_info.dki_media_type = DK_ZIP;
22470 				} else if (
22471 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
22472 					media_info.dki_media_type = DK_JAZ;
22473 				}
22474 			}
22475 		} else {
22476 			/*
22477 			 * Not a CD, direct access or optical disk so return
22478 			 * unknown media
22479 			 */
22480 			media_info.dki_media_type = DK_UNKNOWN;
22481 		}
22482 	}
22483 
22484 	/* Now read the capacity so we can provide the lbasize and capacity */
22485 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
22486 	    SD_PATH_DIRECT);
22487 	switch (rval) {
22488 	case 0:
22489 		break;
22490 	case EACCES:
22491 		rval = EACCES;
22492 		goto done;
22493 	default:
22494 		rval = EIO;
22495 		goto done;
22496 	}
22497 
22498 	/*
22499 	 * If lun is expanded dynamically, update the un structure.
22500 	 */
22501 	mutex_enter(SD_MUTEX(un));
22502 	if ((un->un_f_blockcount_is_valid == TRUE) &&
22503 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
22504 	    (capacity > un->un_blockcount)) {
22505 		sd_update_block_info(un, lbasize, capacity);
22506 	}
22507 	mutex_exit(SD_MUTEX(un));
22508 
22509 	media_info.dki_lbsize = lbasize;
22510 	media_capacity = capacity;
22511 
22512 	/*
22513 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
22514 	 * un->un_sys_blocksize chunks. So we need to convert it into
22515 	 * cap.lbasize chunks.
22516 	 */
22517 	media_capacity *= un->un_sys_blocksize;
22518 	media_capacity /= lbasize;
22519 	media_info.dki_capacity = media_capacity;
22520 
22521 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
22522 		rval = EFAULT;
22523 		/* Put goto. Anybody might add some code below in future */
22524 		goto no_assessment;
22525 	}
22526 done:
22527 	if (rval != 0) {
22528 		if (rval == EIO)
22529 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
22530 		else
22531 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22532 	}
22533 no_assessment:
22534 	sd_ssc_fini(ssc);
22535 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
22536 	kmem_free(rqbuf, SENSE_LENGTH);
22537 	return (rval);
22538 }
22539 
22540 
22541 /*
22542  *    Function: sd_check_media
22543  *
22544  * Description: This utility routine implements the functionality for the
22545  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
22546  *		driver state changes from that specified by the user
22547  *		(inserted or ejected). For example, if the user specifies
22548  *		DKIO_EJECTED and the current media state is inserted this
22549  *		routine will immediately return DKIO_INSERTED. However, if the
22550  *		current media state is not inserted the user thread will be
22551  *		blocked until the drive state changes. If DKIO_NONE is specified
22552  *		the user thread will block until a drive state change occurs.
22553  *
22554  *   Arguments: dev  - the device number
22555  *		state  - user pointer to a dkio_state, updated with the current
22556  *			drive state at return.
22557  *
22558  * Return Code: ENXIO
22559  *		EIO
22560  *		EAGAIN
22561  *		EINTR
22562  */
22563 
22564 static int
22565 sd_check_media(dev_t dev, enum dkio_state state)
22566 {
22567 	struct sd_lun		*un = NULL;
22568 	enum dkio_state		prev_state;
22569 	opaque_t		token = NULL;
22570 	int			rval = 0;
22571 	sd_ssc_t		*ssc;
22572 
22573 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22574 		return (ENXIO);
22575 	}
22576 
22577 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
22578 
22579 	ssc = sd_ssc_init(un);
22580 
22581 	mutex_enter(SD_MUTEX(un));
22582 
22583 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
22584 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
22585 
22586 	prev_state = un->un_mediastate;
22587 
22588 	/* is there anything to do? */
22589 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
22590 		/*
22591 		 * submit the request to the scsi_watch service;
22592 		 * scsi_media_watch_cb() does the real work
22593 		 */
22594 		mutex_exit(SD_MUTEX(un));
22595 
22596 		/*
22597 		 * This change handles the case where a scsi watch request is
22598 		 * added to a device that is powered down. To accomplish this
22599 		 * we power up the device before adding the scsi watch request,
22600 		 * since the scsi watch sends a TUR directly to the device
22601 		 * which the device cannot handle if it is powered down.
22602 		 */
22603 		if (sd_pm_entry(un) != DDI_SUCCESS) {
22604 			mutex_enter(SD_MUTEX(un));
22605 			goto done;
22606 		}
22607 
22608 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
22609 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
22610 		    (caddr_t)dev);
22611 
22612 		sd_pm_exit(un);
22613 
22614 		mutex_enter(SD_MUTEX(un));
22615 		if (token == NULL) {
22616 			rval = EAGAIN;
22617 			goto done;
22618 		}
22619 
22620 		/*
22621 		 * This is a special case IOCTL that doesn't return
22622 		 * until the media state changes. Routine sdpower
22623 		 * knows about and handles this so don't count it
22624 		 * as an active cmd in the driver, which would
22625 		 * keep the device busy to the pm framework.
22626 		 * If the count isn't decremented the device can't
22627 		 * be powered down.
22628 		 */
22629 		un->un_ncmds_in_driver--;
22630 		ASSERT(un->un_ncmds_in_driver >= 0);
22631 
22632 		/*
22633 		 * if a prior request had been made, this will be the same
22634 		 * token, as scsi_watch was designed that way.
22635 		 */
22636 		un->un_swr_token = token;
22637 		un->un_specified_mediastate = state;
22638 
22639 		/*
22640 		 * now wait for media change
22641 		 * we will not be signalled unless mediastate == state but it is
22642 		 * still better to test for this condition, since there is a
22643 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
22644 		 */
22645 		SD_TRACE(SD_LOG_COMMON, un,
22646 		    "sd_check_media: waiting for media state change\n");
22647 		while (un->un_mediastate == state) {
22648 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
22649 				SD_TRACE(SD_LOG_COMMON, un,
22650 				    "sd_check_media: waiting for media state "
22651 				    "was interrupted\n");
22652 				un->un_ncmds_in_driver++;
22653 				rval = EINTR;
22654 				goto done;
22655 			}
22656 			SD_TRACE(SD_LOG_COMMON, un,
22657 			    "sd_check_media: received signal, state=%x\n",
22658 			    un->un_mediastate);
22659 		}
22660 		/*
22661 		 * Inc the counter to indicate the device once again
22662 		 * has an active outstanding cmd.
22663 		 */
22664 		un->un_ncmds_in_driver++;
22665 	}
22666 
22667 	/* invalidate geometry */
22668 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
22669 		sr_ejected(un);
22670 	}
22671 
22672 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
22673 		uint64_t	capacity;
22674 		uint_t		lbasize;
22675 
22676 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
22677 		mutex_exit(SD_MUTEX(un));
22678 		/*
22679 		 * Since the following routines use SD_PATH_DIRECT, we must
22680 		 * call PM directly before the upcoming disk accesses. This
22681 		 * may cause the disk to be power/spin up.
22682 		 */
22683 
22684 		if (sd_pm_entry(un) == DDI_SUCCESS) {
22685 			rval = sd_send_scsi_READ_CAPACITY(ssc,
22686 			    &capacity, &lbasize, SD_PATH_DIRECT);
22687 			if (rval != 0) {
22688 				sd_pm_exit(un);
22689 				if (rval == EIO)
22690 					sd_ssc_assessment(ssc,
22691 					    SD_FMT_STATUS_CHECK);
22692 				else
22693 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22694 				mutex_enter(SD_MUTEX(un));
22695 				goto done;
22696 			}
22697 		} else {
22698 			rval = EIO;
22699 			mutex_enter(SD_MUTEX(un));
22700 			goto done;
22701 		}
22702 		mutex_enter(SD_MUTEX(un));
22703 
22704 		sd_update_block_info(un, lbasize, capacity);
22705 
22706 		/*
22707 		 *  Check if the media in the device is writable or not
22708 		 */
22709 		if (ISCD(un)) {
22710 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
22711 		}
22712 
22713 		mutex_exit(SD_MUTEX(un));
22714 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
22715 		if ((cmlb_validate(un->un_cmlbhandle, 0,
22716 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
22717 			sd_set_pstats(un);
22718 			SD_TRACE(SD_LOG_IO_PARTITION, un,
22719 			    "sd_check_media: un:0x%p pstats created and "
22720 			    "set\n", un);
22721 		}
22722 
22723 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22724 		    SD_PATH_DIRECT);
22725 
22726 		sd_pm_exit(un);
22727 
22728 		if (rval != 0) {
22729 			if (rval == EIO)
22730 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
22731 			else
22732 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22733 		}
22734 
22735 		mutex_enter(SD_MUTEX(un));
22736 	}
22737 done:
22738 	sd_ssc_fini(ssc);
22739 	un->un_f_watcht_stopped = FALSE;
22740 		/*
22741 		 * Use of this local token and the mutex ensures that we avoid
22742 		 * some race conditions associated with terminating the
22743 		 * scsi watch.
22744 		 */
22745 	if (token) {
22746 		un->un_swr_token = (opaque_t)NULL;
22747 		mutex_exit(SD_MUTEX(un));
22748 		(void) scsi_watch_request_terminate(token,
22749 		    SCSI_WATCH_TERMINATE_WAIT);
22750 		mutex_enter(SD_MUTEX(un));
22751 	}
22752 
22753 	/*
22754 	 * Update the capacity kstat value, if no media previously
22755 	 * (capacity kstat is 0) and a media has been inserted
22756 	 * (un_f_blockcount_is_valid == TRUE)
22757 	 */
22758 	if (un->un_errstats) {
22759 		struct sd_errstats	*stp = NULL;
22760 
22761 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
22762 		if ((stp->sd_capacity.value.ui64 == 0) &&
22763 		    (un->un_f_blockcount_is_valid == TRUE)) {
22764 			stp->sd_capacity.value.ui64 =
22765 			    (uint64_t)((uint64_t)un->un_blockcount *
22766 			    un->un_sys_blocksize);
22767 		}
22768 	}
22769 	mutex_exit(SD_MUTEX(un));
22770 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
22771 	return (rval);
22772 }
22773 
22774 
22775 /*
22776  *    Function: sd_delayed_cv_broadcast
22777  *
22778  * Description: Delayed cv_broadcast to allow for target to recover from media
22779  *		insertion.
22780  *
22781  *   Arguments: arg - driver soft state (unit) structure
22782  */
22783 
22784 static void
22785 sd_delayed_cv_broadcast(void *arg)
22786 {
22787 	struct sd_lun *un = arg;
22788 
22789 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
22790 
22791 	mutex_enter(SD_MUTEX(un));
22792 	un->un_dcvb_timeid = NULL;
22793 	cv_broadcast(&un->un_state_cv);
22794 	mutex_exit(SD_MUTEX(un));
22795 }
22796 
22797 
22798 /*
22799  *    Function: sd_media_watch_cb
22800  *
22801  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
22802  *		routine processes the TUR sense data and updates the driver
22803  *		state if a transition has occurred. The user thread
22804  *		(sd_check_media) is then signalled.
22805  *
22806  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22807  *			among multiple watches that share this callback function
22808  *		resultp - scsi watch facility result packet containing scsi
22809  *			  packet, status byte and sense data
22810  *
22811  * Return Code: 0 for success, -1 for failure
22812  */
22813 
22814 static int
22815 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
22816 {
22817 	struct sd_lun			*un;
22818 	struct scsi_status		*statusp = resultp->statusp;
22819 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
22820 	enum dkio_state			state = DKIO_NONE;
22821 	dev_t				dev = (dev_t)arg;
22822 	uchar_t				actual_sense_length;
22823 	uint8_t				skey, asc, ascq;
22824 
22825 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22826 		return (-1);
22827 	}
22828 	actual_sense_length = resultp->actual_sense_length;
22829 
22830 	mutex_enter(SD_MUTEX(un));
22831 	SD_TRACE(SD_LOG_COMMON, un,
22832 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
22833 	    *((char *)statusp), (void *)sensep, actual_sense_length);
22834 
22835 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
22836 		un->un_mediastate = DKIO_DEV_GONE;
22837 		cv_broadcast(&un->un_state_cv);
22838 		mutex_exit(SD_MUTEX(un));
22839 
22840 		return (0);
22841 	}
22842 
22843 	/*
22844 	 * If there was a check condition then sensep points to valid sense data
22845 	 * If status was not a check condition but a reservation or busy status
22846 	 * then the new state is DKIO_NONE
22847 	 */
22848 	if (sensep != NULL) {
22849 		skey = scsi_sense_key(sensep);
22850 		asc = scsi_sense_asc(sensep);
22851 		ascq = scsi_sense_ascq(sensep);
22852 
22853 		SD_INFO(SD_LOG_COMMON, un,
22854 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
22855 		    skey, asc, ascq);
22856 		/* This routine only uses up to 13 bytes of sense data. */
22857 		if (actual_sense_length >= 13) {
22858 			if (skey == KEY_UNIT_ATTENTION) {
22859 				if (asc == 0x28) {
22860 					state = DKIO_INSERTED;
22861 				}
22862 			} else if (skey == KEY_NOT_READY) {
22863 				/*
22864 				 * Sense data of 02/06/00 means that the
22865 				 * drive could not read the media (No
22866 				 * reference position found). In this case
22867 				 * to prevent a hang on the DKIOCSTATE IOCTL
22868 				 * we set the media state to DKIO_INSERTED.
22869 				 */
22870 				if (asc == 0x06 && ascq == 0x00)
22871 					state = DKIO_INSERTED;
22872 
22873 				/*
22874 				 * if 02/04/02  means that the host
22875 				 * should send start command. Explicitly
22876 				 * leave the media state as is
22877 				 * (inserted) as the media is inserted
22878 				 * and host has stopped device for PM
22879 				 * reasons. Upon next true read/write
22880 				 * to this media will bring the
22881 				 * device to the right state good for
22882 				 * media access.
22883 				 */
22884 				if (asc == 0x3a) {
22885 					state = DKIO_EJECTED;
22886 				} else {
22887 					/*
22888 					 * If the drive is busy with an
22889 					 * operation or long write, keep the
22890 					 * media in an inserted state.
22891 					 */
22892 
22893 					if ((asc == 0x04) &&
22894 					    ((ascq == 0x02) ||
22895 					    (ascq == 0x07) ||
22896 					    (ascq == 0x08))) {
22897 						state = DKIO_INSERTED;
22898 					}
22899 				}
22900 			} else if (skey == KEY_NO_SENSE) {
22901 				if ((asc == 0x00) && (ascq == 0x00)) {
22902 					/*
22903 					 * Sense Data 00/00/00 does not provide
22904 					 * any information about the state of
22905 					 * the media. Ignore it.
22906 					 */
22907 					mutex_exit(SD_MUTEX(un));
22908 					return (0);
22909 				}
22910 			}
22911 		}
22912 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
22913 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
22914 		state = DKIO_INSERTED;
22915 	}
22916 
22917 	SD_TRACE(SD_LOG_COMMON, un,
22918 	    "sd_media_watch_cb: state=%x, specified=%x\n",
22919 	    state, un->un_specified_mediastate);
22920 
22921 	/*
22922 	 * now signal the waiting thread if this is *not* the specified state;
22923 	 * delay the signal if the state is DKIO_INSERTED to allow the target
22924 	 * to recover
22925 	 */
22926 	if (state != un->un_specified_mediastate) {
22927 		un->un_mediastate = state;
22928 		if (state == DKIO_INSERTED) {
22929 			/*
22930 			 * delay the signal to give the drive a chance
22931 			 * to do what it apparently needs to do
22932 			 */
22933 			SD_TRACE(SD_LOG_COMMON, un,
22934 			    "sd_media_watch_cb: delayed cv_broadcast\n");
22935 			if (un->un_dcvb_timeid == NULL) {
22936 				un->un_dcvb_timeid =
22937 				    timeout(sd_delayed_cv_broadcast, un,
22938 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
22939 			}
22940 		} else {
22941 			SD_TRACE(SD_LOG_COMMON, un,
22942 			    "sd_media_watch_cb: immediate cv_broadcast\n");
22943 			cv_broadcast(&un->un_state_cv);
22944 		}
22945 	}
22946 	mutex_exit(SD_MUTEX(un));
22947 	return (0);
22948 }
22949 
22950 
22951 /*
22952  *    Function: sd_dkio_get_temp
22953  *
22954  * Description: This routine is the driver entry point for handling ioctl
22955  *		requests to get the disk temperature.
22956  *
22957  *   Arguments: dev  - the device number
22958  *		arg  - pointer to user provided dk_temperature structure.
22959  *		flag - this argument is a pass through to ddi_copyxxx()
22960  *		       directly from the mode argument of ioctl().
22961  *
22962  * Return Code: 0
22963  *		EFAULT
22964  *		ENXIO
22965  *		EAGAIN
22966  */
22967 
22968 static int
22969 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
22970 {
22971 	struct sd_lun		*un = NULL;
22972 	struct dk_temperature	*dktemp = NULL;
22973 	uchar_t			*temperature_page;
22974 	int			rval = 0;
22975 	int			path_flag = SD_PATH_STANDARD;
22976 	sd_ssc_t		*ssc;
22977 
22978 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22979 		return (ENXIO);
22980 	}
22981 
22982 	ssc = sd_ssc_init(un);
22983 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
22984 
22985 	/* copyin the disk temp argument to get the user flags */
22986 	if (ddi_copyin((void *)arg, dktemp,
22987 	    sizeof (struct dk_temperature), flag) != 0) {
22988 		rval = EFAULT;
22989 		goto done;
22990 	}
22991 
22992 	/* Initialize the temperature to invalid. */
22993 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
22994 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
22995 
22996 	/*
22997 	 * Note: Investigate removing the "bypass pm" semantic.
22998 	 * Can we just bypass PM always?
22999 	 */
23000 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
23001 		path_flag = SD_PATH_DIRECT;
23002 		ASSERT(!mutex_owned(&un->un_pm_mutex));
23003 		mutex_enter(&un->un_pm_mutex);
23004 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
23005 			/*
23006 			 * If DKT_BYPASS_PM is set, and the drive happens to be
23007 			 * in low power mode, we can not wake it up, Need to
23008 			 * return EAGAIN.
23009 			 */
23010 			mutex_exit(&un->un_pm_mutex);
23011 			rval = EAGAIN;
23012 			goto done;
23013 		} else {
23014 			/*
23015 			 * Indicate to PM the device is busy. This is required
23016 			 * to avoid a race - i.e. the ioctl is issuing a
23017 			 * command and the pm framework brings down the device
23018 			 * to low power mode (possible power cut-off on some
23019 			 * platforms).
23020 			 */
23021 			mutex_exit(&un->un_pm_mutex);
23022 			if (sd_pm_entry(un) != DDI_SUCCESS) {
23023 				rval = EAGAIN;
23024 				goto done;
23025 			}
23026 		}
23027 	}
23028 
23029 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
23030 
23031 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
23032 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
23033 	if (rval != 0)
23034 		goto done2;
23035 
23036 	/*
23037 	 * For the current temperature verify that the parameter length is 0x02
23038 	 * and the parameter code is 0x00
23039 	 */
23040 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
23041 	    (temperature_page[5] == 0x00)) {
23042 		if (temperature_page[9] == 0xFF) {
23043 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
23044 		} else {
23045 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
23046 		}
23047 	}
23048 
23049 	/*
23050 	 * For the reference temperature verify that the parameter
23051 	 * length is 0x02 and the parameter code is 0x01
23052 	 */
23053 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
23054 	    (temperature_page[11] == 0x01)) {
23055 		if (temperature_page[15] == 0xFF) {
23056 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
23057 		} else {
23058 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
23059 		}
23060 	}
23061 
23062 	/* Do the copyout regardless of the temperature commands status. */
23063 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
23064 	    flag) != 0) {
23065 		rval = EFAULT;
23066 		goto done1;
23067 	}
23068 
23069 done2:
23070 	if (rval != 0) {
23071 		if (rval == EIO)
23072 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23073 		else
23074 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23075 	}
23076 done1:
23077 	if (path_flag == SD_PATH_DIRECT) {
23078 		sd_pm_exit(un);
23079 	}
23080 
23081 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
23082 done:
23083 	sd_ssc_fini(ssc);
23084 	if (dktemp != NULL) {
23085 		kmem_free(dktemp, sizeof (struct dk_temperature));
23086 	}
23087 
23088 	return (rval);
23089 }
23090 
23091 
23092 /*
23093  *    Function: sd_log_page_supported
23094  *
23095  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
23096  *		supported log pages.
23097  *
23098  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
23099  *                      structure for this target.
23100  *		log_page -
23101  *
23102  * Return Code: -1 - on error (log sense is optional and may not be supported).
23103  *		0  - log page not found.
23104  *  		1  - log page found.
23105  */
23106 
23107 static int
23108 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
23109 {
23110 	uchar_t *log_page_data;
23111 	int	i;
23112 	int	match = 0;
23113 	int	log_size;
23114 	int	status = 0;
23115 	struct sd_lun	*un;
23116 
23117 	ASSERT(ssc != NULL);
23118 	un = ssc->ssc_un;
23119 	ASSERT(un != NULL);
23120 
23121 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
23122 
23123 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
23124 	    SD_PATH_DIRECT);
23125 
23126 	if (status != 0) {
23127 		if (status == EIO) {
23128 			/*
23129 			 * Some disks do not support log sense, we
23130 			 * should ignore this kind of error(sense key is
23131 			 * 0x5 - illegal request).
23132 			 */
23133 			uint8_t *sensep;
23134 			int senlen;
23135 
23136 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
23137 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
23138 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
23139 
23140 			if (senlen > 0 &&
23141 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
23142 				sd_ssc_assessment(ssc,
23143 				    SD_FMT_IGNORE_COMPROMISE);
23144 			} else {
23145 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23146 			}
23147 		} else {
23148 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23149 		}
23150 
23151 		SD_ERROR(SD_LOG_COMMON, un,
23152 		    "sd_log_page_supported: failed log page retrieval\n");
23153 		kmem_free(log_page_data, 0xFF);
23154 		return (-1);
23155 	}
23156 
23157 	log_size = log_page_data[3];
23158 
23159 	/*
23160 	 * The list of supported log pages start from the fourth byte. Check
23161 	 * until we run out of log pages or a match is found.
23162 	 */
23163 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
23164 		if (log_page_data[i] == log_page) {
23165 			match++;
23166 		}
23167 	}
23168 	kmem_free(log_page_data, 0xFF);
23169 	return (match);
23170 }
23171 
23172 
23173 /*
23174  *    Function: sd_mhdioc_failfast
23175  *
23176  * Description: This routine is the driver entry point for handling ioctl
23177  *		requests to enable/disable the multihost failfast option.
23178  *		(MHIOCENFAILFAST)
23179  *
23180  *   Arguments: dev	- the device number
23181  *		arg	- user specified probing interval.
23182  *		flag	- this argument is a pass through to ddi_copyxxx()
23183  *			  directly from the mode argument of ioctl().
23184  *
23185  * Return Code: 0
23186  *		EFAULT
23187  *		ENXIO
23188  */
23189 
23190 static int
23191 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
23192 {
23193 	struct sd_lun	*un = NULL;
23194 	int		mh_time;
23195 	int		rval = 0;
23196 
23197 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23198 		return (ENXIO);
23199 	}
23200 
23201 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
23202 		return (EFAULT);
23203 
23204 	if (mh_time) {
23205 		mutex_enter(SD_MUTEX(un));
23206 		un->un_resvd_status |= SD_FAILFAST;
23207 		mutex_exit(SD_MUTEX(un));
23208 		/*
23209 		 * If mh_time is INT_MAX, then this ioctl is being used for
23210 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
23211 		 */
23212 		if (mh_time != INT_MAX) {
23213 			rval = sd_check_mhd(dev, mh_time);
23214 		}
23215 	} else {
23216 		(void) sd_check_mhd(dev, 0);
23217 		mutex_enter(SD_MUTEX(un));
23218 		un->un_resvd_status &= ~SD_FAILFAST;
23219 		mutex_exit(SD_MUTEX(un));
23220 	}
23221 	return (rval);
23222 }
23223 
23224 
23225 /*
23226  *    Function: sd_mhdioc_takeown
23227  *
23228  * Description: This routine is the driver entry point for handling ioctl
23229  *		requests to forcefully acquire exclusive access rights to the
23230  *		multihost disk (MHIOCTKOWN).
23231  *
23232  *   Arguments: dev	- the device number
23233  *		arg	- user provided structure specifying the delay
23234  *			  parameters in milliseconds
23235  *		flag	- this argument is a pass through to ddi_copyxxx()
23236  *			  directly from the mode argument of ioctl().
23237  *
23238  * Return Code: 0
23239  *		EFAULT
23240  *		ENXIO
23241  */
23242 
23243 static int
23244 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
23245 {
23246 	struct sd_lun		*un = NULL;
23247 	struct mhioctkown	*tkown = NULL;
23248 	int			rval = 0;
23249 
23250 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23251 		return (ENXIO);
23252 	}
23253 
23254 	if (arg != NULL) {
23255 		tkown = (struct mhioctkown *)
23256 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
23257 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
23258 		if (rval != 0) {
23259 			rval = EFAULT;
23260 			goto error;
23261 		}
23262 	}
23263 
23264 	rval = sd_take_ownership(dev, tkown);
23265 	mutex_enter(SD_MUTEX(un));
23266 	if (rval == 0) {
23267 		un->un_resvd_status |= SD_RESERVE;
23268 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
23269 			sd_reinstate_resv_delay =
23270 			    tkown->reinstate_resv_delay * 1000;
23271 		} else {
23272 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
23273 		}
23274 		/*
23275 		 * Give the scsi_watch routine interval set by
23276 		 * the MHIOCENFAILFAST ioctl precedence here.
23277 		 */
23278 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
23279 			mutex_exit(SD_MUTEX(un));
23280 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
23281 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
23282 			    "sd_mhdioc_takeown : %d\n",
23283 			    sd_reinstate_resv_delay);
23284 		} else {
23285 			mutex_exit(SD_MUTEX(un));
23286 		}
23287 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
23288 		    sd_mhd_reset_notify_cb, (caddr_t)un);
23289 	} else {
23290 		un->un_resvd_status &= ~SD_RESERVE;
23291 		mutex_exit(SD_MUTEX(un));
23292 	}
23293 
23294 error:
23295 	if (tkown != NULL) {
23296 		kmem_free(tkown, sizeof (struct mhioctkown));
23297 	}
23298 	return (rval);
23299 }
23300 
23301 
23302 /*
23303  *    Function: sd_mhdioc_release
23304  *
23305  * Description: This routine is the driver entry point for handling ioctl
23306  *		requests to release exclusive access rights to the multihost
23307  *		disk (MHIOCRELEASE).
23308  *
23309  *   Arguments: dev	- the device number
23310  *
23311  * Return Code: 0
23312  *		ENXIO
23313  */
23314 
23315 static int
23316 sd_mhdioc_release(dev_t dev)
23317 {
23318 	struct sd_lun		*un = NULL;
23319 	timeout_id_t		resvd_timeid_save;
23320 	int			resvd_status_save;
23321 	int			rval = 0;
23322 
23323 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23324 		return (ENXIO);
23325 	}
23326 
23327 	mutex_enter(SD_MUTEX(un));
23328 	resvd_status_save = un->un_resvd_status;
23329 	un->un_resvd_status &=
23330 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
23331 	if (un->un_resvd_timeid) {
23332 		resvd_timeid_save = un->un_resvd_timeid;
23333 		un->un_resvd_timeid = NULL;
23334 		mutex_exit(SD_MUTEX(un));
23335 		(void) untimeout(resvd_timeid_save);
23336 	} else {
23337 		mutex_exit(SD_MUTEX(un));
23338 	}
23339 
23340 	/*
23341 	 * destroy any pending timeout thread that may be attempting to
23342 	 * reinstate reservation on this device.
23343 	 */
23344 	sd_rmv_resv_reclaim_req(dev);
23345 
23346 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
23347 		mutex_enter(SD_MUTEX(un));
23348 		if ((un->un_mhd_token) &&
23349 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
23350 			mutex_exit(SD_MUTEX(un));
23351 			(void) sd_check_mhd(dev, 0);
23352 		} else {
23353 			mutex_exit(SD_MUTEX(un));
23354 		}
23355 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
23356 		    sd_mhd_reset_notify_cb, (caddr_t)un);
23357 	} else {
23358 		/*
23359 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
23360 		 */
23361 		mutex_enter(SD_MUTEX(un));
23362 		un->un_resvd_status = resvd_status_save;
23363 		mutex_exit(SD_MUTEX(un));
23364 	}
23365 	return (rval);
23366 }
23367 
23368 
23369 /*
23370  *    Function: sd_mhdioc_register_devid
23371  *
23372  * Description: This routine is the driver entry point for handling ioctl
23373  *		requests to register the device id (MHIOCREREGISTERDEVID).
23374  *
23375  *		Note: The implementation for this ioctl has been updated to
23376  *		be consistent with the original PSARC case (1999/357)
23377  *		(4375899, 4241671, 4220005)
23378  *
23379  *   Arguments: dev	- the device number
23380  *
23381  * Return Code: 0
23382  *		ENXIO
23383  */
23384 
23385 static int
23386 sd_mhdioc_register_devid(dev_t dev)
23387 {
23388 	struct sd_lun	*un = NULL;
23389 	int		rval = 0;
23390 	sd_ssc_t	*ssc;
23391 
23392 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23393 		return (ENXIO);
23394 	}
23395 
23396 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23397 
23398 	mutex_enter(SD_MUTEX(un));
23399 
23400 	/* If a devid already exists, de-register it */
23401 	if (un->un_devid != NULL) {
23402 		ddi_devid_unregister(SD_DEVINFO(un));
23403 		/*
23404 		 * After unregister devid, needs to free devid memory
23405 		 */
23406 		ddi_devid_free(un->un_devid);
23407 		un->un_devid = NULL;
23408 	}
23409 
23410 	/* Check for reservation conflict */
23411 	mutex_exit(SD_MUTEX(un));
23412 	ssc = sd_ssc_init(un);
23413 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
23414 	mutex_enter(SD_MUTEX(un));
23415 
23416 	switch (rval) {
23417 	case 0:
23418 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
23419 		break;
23420 	case EACCES:
23421 		break;
23422 	default:
23423 		rval = EIO;
23424 	}
23425 
23426 	mutex_exit(SD_MUTEX(un));
23427 	if (rval != 0) {
23428 		if (rval == EIO)
23429 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23430 		else
23431 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23432 	}
23433 	sd_ssc_fini(ssc);
23434 	return (rval);
23435 }
23436 
23437 
23438 /*
23439  *    Function: sd_mhdioc_inkeys
23440  *
23441  * Description: This routine is the driver entry point for handling ioctl
23442  *		requests to issue the SCSI-3 Persistent In Read Keys command
23443  *		to the device (MHIOCGRP_INKEYS).
23444  *
23445  *   Arguments: dev	- the device number
23446  *		arg	- user provided in_keys structure
23447  *		flag	- this argument is a pass through to ddi_copyxxx()
23448  *			  directly from the mode argument of ioctl().
23449  *
23450  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
23451  *		ENXIO
23452  *		EFAULT
23453  */
23454 
23455 static int
23456 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
23457 {
23458 	struct sd_lun		*un;
23459 	mhioc_inkeys_t		inkeys;
23460 	int			rval = 0;
23461 
23462 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23463 		return (ENXIO);
23464 	}
23465 
23466 #ifdef _MULTI_DATAMODEL
23467 	switch (ddi_model_convert_from(flag & FMODELS)) {
23468 	case DDI_MODEL_ILP32: {
23469 		struct mhioc_inkeys32	inkeys32;
23470 
23471 		if (ddi_copyin(arg, &inkeys32,
23472 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
23473 			return (EFAULT);
23474 		}
23475 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
23476 		if ((rval = sd_persistent_reservation_in_read_keys(un,
23477 		    &inkeys, flag)) != 0) {
23478 			return (rval);
23479 		}
23480 		inkeys32.generation = inkeys.generation;
23481 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
23482 		    flag) != 0) {
23483 			return (EFAULT);
23484 		}
23485 		break;
23486 	}
23487 	case DDI_MODEL_NONE:
23488 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
23489 		    flag) != 0) {
23490 			return (EFAULT);
23491 		}
23492 		if ((rval = sd_persistent_reservation_in_read_keys(un,
23493 		    &inkeys, flag)) != 0) {
23494 			return (rval);
23495 		}
23496 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
23497 		    flag) != 0) {
23498 			return (EFAULT);
23499 		}
23500 		break;
23501 	}
23502 
23503 #else /* ! _MULTI_DATAMODEL */
23504 
23505 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
23506 		return (EFAULT);
23507 	}
23508 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
23509 	if (rval != 0) {
23510 		return (rval);
23511 	}
23512 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
23513 		return (EFAULT);
23514 	}
23515 
23516 #endif /* _MULTI_DATAMODEL */
23517 
23518 	return (rval);
23519 }
23520 
23521 
23522 /*
23523  *    Function: sd_mhdioc_inresv
23524  *
23525  * Description: This routine is the driver entry point for handling ioctl
23526  *		requests to issue the SCSI-3 Persistent In Read Reservations
23527  *		command to the device (MHIOCGRP_INKEYS).
23528  *
23529  *   Arguments: dev	- the device number
23530  *		arg	- user provided in_resv structure
23531  *		flag	- this argument is a pass through to ddi_copyxxx()
23532  *			  directly from the mode argument of ioctl().
23533  *
23534  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
23535  *		ENXIO
23536  *		EFAULT
23537  */
23538 
23539 static int
23540 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
23541 {
23542 	struct sd_lun		*un;
23543 	mhioc_inresvs_t		inresvs;
23544 	int			rval = 0;
23545 
23546 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23547 		return (ENXIO);
23548 	}
23549 
23550 #ifdef _MULTI_DATAMODEL
23551 
23552 	switch (ddi_model_convert_from(flag & FMODELS)) {
23553 	case DDI_MODEL_ILP32: {
23554 		struct mhioc_inresvs32	inresvs32;
23555 
23556 		if (ddi_copyin(arg, &inresvs32,
23557 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
23558 			return (EFAULT);
23559 		}
23560 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
23561 		if ((rval = sd_persistent_reservation_in_read_resv(un,
23562 		    &inresvs, flag)) != 0) {
23563 			return (rval);
23564 		}
23565 		inresvs32.generation = inresvs.generation;
23566 		if (ddi_copyout(&inresvs32, arg,
23567 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
23568 			return (EFAULT);
23569 		}
23570 		break;
23571 	}
23572 	case DDI_MODEL_NONE:
23573 		if (ddi_copyin(arg, &inresvs,
23574 		    sizeof (mhioc_inresvs_t), flag) != 0) {
23575 			return (EFAULT);
23576 		}
23577 		if ((rval = sd_persistent_reservation_in_read_resv(un,
23578 		    &inresvs, flag)) != 0) {
23579 			return (rval);
23580 		}
23581 		if (ddi_copyout(&inresvs, arg,
23582 		    sizeof (mhioc_inresvs_t), flag) != 0) {
23583 			return (EFAULT);
23584 		}
23585 		break;
23586 	}
23587 
23588 #else /* ! _MULTI_DATAMODEL */
23589 
23590 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
23591 		return (EFAULT);
23592 	}
23593 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
23594 	if (rval != 0) {
23595 		return (rval);
23596 	}
23597 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
23598 		return (EFAULT);
23599 	}
23600 
23601 #endif /* ! _MULTI_DATAMODEL */
23602 
23603 	return (rval);
23604 }
23605 
23606 
23607 /*
23608  * The following routines support the clustering functionality described below
23609  * and implement lost reservation reclaim functionality.
23610  *
23611  * Clustering
23612  * ----------
23613  * The clustering code uses two different, independent forms of SCSI
23614  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
23615  * Persistent Group Reservations. For any particular disk, it will use either
23616  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
23617  *
23618  * SCSI-2
23619  * The cluster software takes ownership of a multi-hosted disk by issuing the
23620  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
23621  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
23622  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
23623  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
23624  * driver. The meaning of failfast is that if the driver (on this host) ever
23625  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
23626  * it should immediately panic the host. The motivation for this ioctl is that
23627  * if this host does encounter reservation conflict, the underlying cause is
23628  * that some other host of the cluster has decided that this host is no longer
23629  * in the cluster and has seized control of the disks for itself. Since this
23630  * host is no longer in the cluster, it ought to panic itself. The
23631  * MHIOCENFAILFAST ioctl does two things:
23632  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
23633  *      error to panic the host
23634  *      (b) it sets up a periodic timer to test whether this host still has
23635  *      "access" (in that no other host has reserved the device):  if the
23636  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
23637  *      purpose of that periodic timer is to handle scenarios where the host is
23638  *      otherwise temporarily quiescent, temporarily doing no real i/o.
23639  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
23640  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
23641  * the device itself.
23642  *
23643  * SCSI-3 PGR
23644  * A direct semantic implementation of the SCSI-3 Persistent Reservation
23645  * facility is supported through the shared multihost disk ioctls
23646  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
23647  * MHIOCGRP_PREEMPTANDABORT)
23648  *
23649  * Reservation Reclaim:
23650  * --------------------
23651  * To support the lost reservation reclaim operations this driver creates a
23652  * single thread to handle reinstating reservations on all devices that have
23653  * lost reservations sd_resv_reclaim_requests are logged for all devices that
23654  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
23655  * and the reservation reclaim thread loops through the requests to regain the
23656  * lost reservations.
23657  */
23658 
23659 /*
23660  *    Function: sd_check_mhd()
23661  *
23662  * Description: This function sets up and submits a scsi watch request or
23663  *		terminates an existing watch request. This routine is used in
23664  *		support of reservation reclaim.
23665  *
23666  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
23667  *			 among multiple watches that share the callback function
23668  *		interval - the number of microseconds specifying the watch
23669  *			   interval for issuing TEST UNIT READY commands. If
23670  *			   set to 0 the watch should be terminated. If the
23671  *			   interval is set to 0 and if the device is required
23672  *			   to hold reservation while disabling failfast, the
23673  *			   watch is restarted with an interval of
23674  *			   reinstate_resv_delay.
23675  *
23676  * Return Code: 0	   - Successful submit/terminate of scsi watch request
23677  *		ENXIO      - Indicates an invalid device was specified
23678  *		EAGAIN     - Unable to submit the scsi watch request
23679  */
23680 
23681 static int
23682 sd_check_mhd(dev_t dev, int interval)
23683 {
23684 	struct sd_lun	*un;
23685 	opaque_t	token;
23686 
23687 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23688 		return (ENXIO);
23689 	}
23690 
23691 	/* is this a watch termination request? */
23692 	if (interval == 0) {
23693 		mutex_enter(SD_MUTEX(un));
23694 		/* if there is an existing watch task then terminate it */
23695 		if (un->un_mhd_token) {
23696 			token = un->un_mhd_token;
23697 			un->un_mhd_token = NULL;
23698 			mutex_exit(SD_MUTEX(un));
23699 			(void) scsi_watch_request_terminate(token,
23700 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
23701 			mutex_enter(SD_MUTEX(un));
23702 		} else {
23703 			mutex_exit(SD_MUTEX(un));
23704 			/*
23705 			 * Note: If we return here we don't check for the
23706 			 * failfast case. This is the original legacy
23707 			 * implementation but perhaps we should be checking
23708 			 * the failfast case.
23709 			 */
23710 			return (0);
23711 		}
23712 		/*
23713 		 * If the device is required to hold reservation while
23714 		 * disabling failfast, we need to restart the scsi_watch
23715 		 * routine with an interval of reinstate_resv_delay.
23716 		 */
23717 		if (un->un_resvd_status & SD_RESERVE) {
23718 			interval = sd_reinstate_resv_delay/1000;
23719 		} else {
23720 			/* no failfast so bail */
23721 			mutex_exit(SD_MUTEX(un));
23722 			return (0);
23723 		}
23724 		mutex_exit(SD_MUTEX(un));
23725 	}
23726 
23727 	/*
23728 	 * adjust minimum time interval to 1 second,
23729 	 * and convert from msecs to usecs
23730 	 */
23731 	if (interval > 0 && interval < 1000) {
23732 		interval = 1000;
23733 	}
23734 	interval *= 1000;
23735 
23736 	/*
23737 	 * submit the request to the scsi_watch service
23738 	 */
23739 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
23740 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
23741 	if (token == NULL) {
23742 		return (EAGAIN);
23743 	}
23744 
23745 	/*
23746 	 * save token for termination later on
23747 	 */
23748 	mutex_enter(SD_MUTEX(un));
23749 	un->un_mhd_token = token;
23750 	mutex_exit(SD_MUTEX(un));
23751 	return (0);
23752 }
23753 
23754 
23755 /*
23756  *    Function: sd_mhd_watch_cb()
23757  *
23758  * Description: This function is the call back function used by the scsi watch
23759  *		facility. The scsi watch facility sends the "Test Unit Ready"
23760  *		and processes the status. If applicable (i.e. a "Unit Attention"
23761  *		status and automatic "Request Sense" not used) the scsi watch
23762  *		facility will send a "Request Sense" and retrieve the sense data
23763  *		to be passed to this callback function. In either case the
23764  *		automatic "Request Sense" or the facility submitting one, this
23765  *		callback is passed the status and sense data.
23766  *
23767  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
23768  *			among multiple watches that share this callback function
23769  *		resultp - scsi watch facility result packet containing scsi
23770  *			  packet, status byte and sense data
23771  *
23772  * Return Code: 0 - continue the watch task
23773  *		non-zero - terminate the watch task
23774  */
23775 
23776 static int
23777 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
23778 {
23779 	struct sd_lun			*un;
23780 	struct scsi_status		*statusp;
23781 	uint8_t				*sensep;
23782 	struct scsi_pkt			*pkt;
23783 	uchar_t				actual_sense_length;
23784 	dev_t  				dev = (dev_t)arg;
23785 
23786 	ASSERT(resultp != NULL);
23787 	statusp			= resultp->statusp;
23788 	sensep			= (uint8_t *)resultp->sensep;
23789 	pkt			= resultp->pkt;
23790 	actual_sense_length	= resultp->actual_sense_length;
23791 
23792 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23793 		return (ENXIO);
23794 	}
23795 
23796 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
23797 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
23798 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
23799 
23800 	/* Begin processing of the status and/or sense data */
23801 	if (pkt->pkt_reason != CMD_CMPLT) {
23802 		/* Handle the incomplete packet */
23803 		sd_mhd_watch_incomplete(un, pkt);
23804 		return (0);
23805 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
23806 		if (*((unsigned char *)statusp)
23807 		    == STATUS_RESERVATION_CONFLICT) {
23808 			/*
23809 			 * Handle a reservation conflict by panicking if
23810 			 * configured for failfast or by logging the conflict
23811 			 * and updating the reservation status
23812 			 */
23813 			mutex_enter(SD_MUTEX(un));
23814 			if ((un->un_resvd_status & SD_FAILFAST) &&
23815 			    (sd_failfast_enable)) {
23816 				sd_panic_for_res_conflict(un);
23817 				/*NOTREACHED*/
23818 			}
23819 			SD_INFO(SD_LOG_IOCTL_MHD, un,
23820 			    "sd_mhd_watch_cb: Reservation Conflict\n");
23821 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
23822 			mutex_exit(SD_MUTEX(un));
23823 		}
23824 	}
23825 
23826 	if (sensep != NULL) {
23827 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
23828 			mutex_enter(SD_MUTEX(un));
23829 			if ((scsi_sense_asc(sensep) ==
23830 			    SD_SCSI_RESET_SENSE_CODE) &&
23831 			    (un->un_resvd_status & SD_RESERVE)) {
23832 				/*
23833 				 * The additional sense code indicates a power
23834 				 * on or bus device reset has occurred; update
23835 				 * the reservation status.
23836 				 */
23837 				un->un_resvd_status |=
23838 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
23839 				SD_INFO(SD_LOG_IOCTL_MHD, un,
23840 				    "sd_mhd_watch_cb: Lost Reservation\n");
23841 			}
23842 		} else {
23843 			return (0);
23844 		}
23845 	} else {
23846 		mutex_enter(SD_MUTEX(un));
23847 	}
23848 
23849 	if ((un->un_resvd_status & SD_RESERVE) &&
23850 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
23851 		if (un->un_resvd_status & SD_WANT_RESERVE) {
23852 			/*
23853 			 * A reset occurred in between the last probe and this
23854 			 * one so if a timeout is pending cancel it.
23855 			 */
23856 			if (un->un_resvd_timeid) {
23857 				timeout_id_t temp_id = un->un_resvd_timeid;
23858 				un->un_resvd_timeid = NULL;
23859 				mutex_exit(SD_MUTEX(un));
23860 				(void) untimeout(temp_id);
23861 				mutex_enter(SD_MUTEX(un));
23862 			}
23863 			un->un_resvd_status &= ~SD_WANT_RESERVE;
23864 		}
23865 		if (un->un_resvd_timeid == 0) {
23866 			/* Schedule a timeout to handle the lost reservation */
23867 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
23868 			    (void *)dev,
23869 			    drv_usectohz(sd_reinstate_resv_delay));
23870 		}
23871 	}
23872 	mutex_exit(SD_MUTEX(un));
23873 	return (0);
23874 }
23875 
23876 
23877 /*
23878  *    Function: sd_mhd_watch_incomplete()
23879  *
23880  * Description: This function is used to find out why a scsi pkt sent by the
23881  *		scsi watch facility was not completed. Under some scenarios this
23882  *		routine will return. Otherwise it will send a bus reset to see
23883  *		if the drive is still online.
23884  *
23885  *   Arguments: un  - driver soft state (unit) structure
23886  *		pkt - incomplete scsi pkt
23887  */
23888 
23889 static void
23890 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
23891 {
23892 	int	be_chatty;
23893 	int	perr;
23894 
23895 	ASSERT(pkt != NULL);
23896 	ASSERT(un != NULL);
23897 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
23898 	perr		= (pkt->pkt_statistics & STAT_PERR);
23899 
23900 	mutex_enter(SD_MUTEX(un));
23901 	if (un->un_state == SD_STATE_DUMPING) {
23902 		mutex_exit(SD_MUTEX(un));
23903 		return;
23904 	}
23905 
23906 	switch (pkt->pkt_reason) {
23907 	case CMD_UNX_BUS_FREE:
23908 		/*
23909 		 * If we had a parity error that caused the target to drop BSY*,
23910 		 * don't be chatty about it.
23911 		 */
23912 		if (perr && be_chatty) {
23913 			be_chatty = 0;
23914 		}
23915 		break;
23916 	case CMD_TAG_REJECT:
23917 		/*
23918 		 * The SCSI-2 spec states that a tag reject will be sent by the
23919 		 * target if tagged queuing is not supported. A tag reject may
23920 		 * also be sent during certain initialization periods or to
23921 		 * control internal resources. For the latter case the target
23922 		 * may also return Queue Full.
23923 		 *
23924 		 * If this driver receives a tag reject from a target that is
23925 		 * going through an init period or controlling internal
23926 		 * resources tagged queuing will be disabled. This is a less
23927 		 * than optimal behavior but the driver is unable to determine
23928 		 * the target state and assumes tagged queueing is not supported
23929 		 */
23930 		pkt->pkt_flags = 0;
23931 		un->un_tagflags = 0;
23932 
23933 		if (un->un_f_opt_queueing == TRUE) {
23934 			un->un_throttle = min(un->un_throttle, 3);
23935 		} else {
23936 			un->un_throttle = 1;
23937 		}
23938 		mutex_exit(SD_MUTEX(un));
23939 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
23940 		mutex_enter(SD_MUTEX(un));
23941 		break;
23942 	case CMD_INCOMPLETE:
23943 		/*
23944 		 * The transport stopped with an abnormal state, fallthrough and
23945 		 * reset the target and/or bus unless selection did not complete
23946 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
23947 		 * go through a target/bus reset
23948 		 */
23949 		if (pkt->pkt_state == STATE_GOT_BUS) {
23950 			break;
23951 		}
23952 		/*FALLTHROUGH*/
23953 
23954 	case CMD_TIMEOUT:
23955 	default:
23956 		/*
23957 		 * The lun may still be running the command, so a lun reset
23958 		 * should be attempted. If the lun reset fails or cannot be
23959 		 * issued, than try a target reset. Lastly try a bus reset.
23960 		 */
23961 		if ((pkt->pkt_statistics &
23962 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
23963 			int reset_retval = 0;
23964 			mutex_exit(SD_MUTEX(un));
23965 			if (un->un_f_allow_bus_device_reset == TRUE) {
23966 				if (un->un_f_lun_reset_enabled == TRUE) {
23967 					reset_retval =
23968 					    scsi_reset(SD_ADDRESS(un),
23969 					    RESET_LUN);
23970 				}
23971 				if (reset_retval == 0) {
23972 					reset_retval =
23973 					    scsi_reset(SD_ADDRESS(un),
23974 					    RESET_TARGET);
23975 				}
23976 			}
23977 			if (reset_retval == 0) {
23978 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
23979 			}
23980 			mutex_enter(SD_MUTEX(un));
23981 		}
23982 		break;
23983 	}
23984 
23985 	/* A device/bus reset has occurred; update the reservation status. */
23986 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
23987 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
23988 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
23989 			un->un_resvd_status |=
23990 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
23991 			SD_INFO(SD_LOG_IOCTL_MHD, un,
23992 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
23993 		}
23994 	}
23995 
23996 	/*
23997 	 * The disk has been turned off; Update the device state.
23998 	 *
23999 	 * Note: Should we be offlining the disk here?
24000 	 */
24001 	if (pkt->pkt_state == STATE_GOT_BUS) {
24002 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
24003 		    "Disk not responding to selection\n");
24004 		if (un->un_state != SD_STATE_OFFLINE) {
24005 			New_state(un, SD_STATE_OFFLINE);
24006 		}
24007 	} else if (be_chatty) {
24008 		/*
24009 		 * suppress messages if they are all the same pkt reason;
24010 		 * with TQ, many (up to 256) are returned with the same
24011 		 * pkt_reason
24012 		 */
24013 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
24014 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
24015 			    "sd_mhd_watch_incomplete: "
24016 			    "SCSI transport failed: reason '%s'\n",
24017 			    scsi_rname(pkt->pkt_reason));
24018 		}
24019 	}
24020 	un->un_last_pkt_reason = pkt->pkt_reason;
24021 	mutex_exit(SD_MUTEX(un));
24022 }
24023 
24024 
24025 /*
24026  *    Function: sd_sname()
24027  *
24028  * Description: This is a simple little routine to return a string containing
24029  *		a printable description of command status byte for use in
24030  *		logging.
24031  *
24032  *   Arguments: status - pointer to a status byte
24033  *
24034  * Return Code: char * - string containing status description.
24035  */
24036 
24037 static char *
24038 sd_sname(uchar_t status)
24039 {
24040 	switch (status & STATUS_MASK) {
24041 	case STATUS_GOOD:
24042 		return ("good status");
24043 	case STATUS_CHECK:
24044 		return ("check condition");
24045 	case STATUS_MET:
24046 		return ("condition met");
24047 	case STATUS_BUSY:
24048 		return ("busy");
24049 	case STATUS_INTERMEDIATE:
24050 		return ("intermediate");
24051 	case STATUS_INTERMEDIATE_MET:
24052 		return ("intermediate - condition met");
24053 	case STATUS_RESERVATION_CONFLICT:
24054 		return ("reservation_conflict");
24055 	case STATUS_TERMINATED:
24056 		return ("command terminated");
24057 	case STATUS_QFULL:
24058 		return ("queue full");
24059 	default:
24060 		return ("<unknown status>");
24061 	}
24062 }
24063 
24064 
24065 /*
24066  *    Function: sd_mhd_resvd_recover()
24067  *
24068  * Description: This function adds a reservation entry to the
24069  *		sd_resv_reclaim_request list and signals the reservation
24070  *		reclaim thread that there is work pending. If the reservation
24071  *		reclaim thread has not been previously created this function
24072  *		will kick it off.
24073  *
24074  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24075  *			among multiple watches that share this callback function
24076  *
24077  *     Context: This routine is called by timeout() and is run in interrupt
24078  *		context. It must not sleep or call other functions which may
24079  *		sleep.
24080  */
24081 
24082 static void
24083 sd_mhd_resvd_recover(void *arg)
24084 {
24085 	dev_t			dev = (dev_t)arg;
24086 	struct sd_lun		*un;
24087 	struct sd_thr_request	*sd_treq = NULL;
24088 	struct sd_thr_request	*sd_cur = NULL;
24089 	struct sd_thr_request	*sd_prev = NULL;
24090 	int			already_there = 0;
24091 
24092 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24093 		return;
24094 	}
24095 
24096 	mutex_enter(SD_MUTEX(un));
24097 	un->un_resvd_timeid = NULL;
24098 	if (un->un_resvd_status & SD_WANT_RESERVE) {
24099 		/*
24100 		 * There was a reset so don't issue the reserve, allow the
24101 		 * sd_mhd_watch_cb callback function to notice this and
24102 		 * reschedule the timeout for reservation.
24103 		 */
24104 		mutex_exit(SD_MUTEX(un));
24105 		return;
24106 	}
24107 	mutex_exit(SD_MUTEX(un));
24108 
24109 	/*
24110 	 * Add this device to the sd_resv_reclaim_request list and the
24111 	 * sd_resv_reclaim_thread should take care of the rest.
24112 	 *
24113 	 * Note: We can't sleep in this context so if the memory allocation
24114 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
24115 	 * reschedule the timeout for reservation.  (4378460)
24116 	 */
24117 	sd_treq = (struct sd_thr_request *)
24118 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
24119 	if (sd_treq == NULL) {
24120 		return;
24121 	}
24122 
24123 	sd_treq->sd_thr_req_next = NULL;
24124 	sd_treq->dev = dev;
24125 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24126 	if (sd_tr.srq_thr_req_head == NULL) {
24127 		sd_tr.srq_thr_req_head = sd_treq;
24128 	} else {
24129 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
24130 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
24131 			if (sd_cur->dev == dev) {
24132 				/*
24133 				 * already in Queue so don't log
24134 				 * another request for the device
24135 				 */
24136 				already_there = 1;
24137 				break;
24138 			}
24139 			sd_prev = sd_cur;
24140 		}
24141 		if (!already_there) {
24142 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
24143 			    "logging request for %lx\n", dev);
24144 			sd_prev->sd_thr_req_next = sd_treq;
24145 		} else {
24146 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
24147 		}
24148 	}
24149 
24150 	/*
24151 	 * Create a kernel thread to do the reservation reclaim and free up this
24152 	 * thread. We cannot block this thread while we go away to do the
24153 	 * reservation reclaim
24154 	 */
24155 	if (sd_tr.srq_resv_reclaim_thread == NULL)
24156 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
24157 		    sd_resv_reclaim_thread, NULL,
24158 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
24159 
24160 	/* Tell the reservation reclaim thread that it has work to do */
24161 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
24162 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24163 }
24164 
24165 /*
24166  *    Function: sd_resv_reclaim_thread()
24167  *
24168  * Description: This function implements the reservation reclaim operations
24169  *
24170  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
24171  *		      among multiple watches that share this callback function
24172  */
24173 
24174 static void
24175 sd_resv_reclaim_thread()
24176 {
24177 	struct sd_lun		*un;
24178 	struct sd_thr_request	*sd_mhreq;
24179 
24180 	/* Wait for work */
24181 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24182 	if (sd_tr.srq_thr_req_head == NULL) {
24183 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
24184 		    &sd_tr.srq_resv_reclaim_mutex);
24185 	}
24186 
24187 	/* Loop while we have work */
24188 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
24189 		un = ddi_get_soft_state(sd_state,
24190 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
24191 		if (un == NULL) {
24192 			/*
24193 			 * softstate structure is NULL so just
24194 			 * dequeue the request and continue
24195 			 */
24196 			sd_tr.srq_thr_req_head =
24197 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
24198 			kmem_free(sd_tr.srq_thr_cur_req,
24199 			    sizeof (struct sd_thr_request));
24200 			continue;
24201 		}
24202 
24203 		/* dequeue the request */
24204 		sd_mhreq = sd_tr.srq_thr_cur_req;
24205 		sd_tr.srq_thr_req_head =
24206 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
24207 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24208 
24209 		/*
24210 		 * Reclaim reservation only if SD_RESERVE is still set. There
24211 		 * may have been a call to MHIOCRELEASE before we got here.
24212 		 */
24213 		mutex_enter(SD_MUTEX(un));
24214 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
24215 			/*
24216 			 * Note: The SD_LOST_RESERVE flag is cleared before
24217 			 * reclaiming the reservation. If this is done after the
24218 			 * call to sd_reserve_release a reservation loss in the
24219 			 * window between pkt completion of reserve cmd and
24220 			 * mutex_enter below may not be recognized
24221 			 */
24222 			un->un_resvd_status &= ~SD_LOST_RESERVE;
24223 			mutex_exit(SD_MUTEX(un));
24224 
24225 			if (sd_reserve_release(sd_mhreq->dev,
24226 			    SD_RESERVE) == 0) {
24227 				mutex_enter(SD_MUTEX(un));
24228 				un->un_resvd_status |= SD_RESERVE;
24229 				mutex_exit(SD_MUTEX(un));
24230 				SD_INFO(SD_LOG_IOCTL_MHD, un,
24231 				    "sd_resv_reclaim_thread: "
24232 				    "Reservation Recovered\n");
24233 			} else {
24234 				mutex_enter(SD_MUTEX(un));
24235 				un->un_resvd_status |= SD_LOST_RESERVE;
24236 				mutex_exit(SD_MUTEX(un));
24237 				SD_INFO(SD_LOG_IOCTL_MHD, un,
24238 				    "sd_resv_reclaim_thread: Failed "
24239 				    "Reservation Recovery\n");
24240 			}
24241 		} else {
24242 			mutex_exit(SD_MUTEX(un));
24243 		}
24244 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24245 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
24246 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
24247 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
24248 		/*
24249 		 * wakeup the destroy thread if anyone is waiting on
24250 		 * us to complete.
24251 		 */
24252 		cv_signal(&sd_tr.srq_inprocess_cv);
24253 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
24254 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
24255 	}
24256 
24257 	/*
24258 	 * cleanup the sd_tr structure now that this thread will not exist
24259 	 */
24260 	ASSERT(sd_tr.srq_thr_req_head == NULL);
24261 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
24262 	sd_tr.srq_resv_reclaim_thread = NULL;
24263 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24264 	thread_exit();
24265 }
24266 
24267 
24268 /*
24269  *    Function: sd_rmv_resv_reclaim_req()
24270  *
24271  * Description: This function removes any pending reservation reclaim requests
24272  *		for the specified device.
24273  *
24274  *   Arguments: dev - the device 'dev_t'
24275  */
24276 
24277 static void
24278 sd_rmv_resv_reclaim_req(dev_t dev)
24279 {
24280 	struct sd_thr_request *sd_mhreq;
24281 	struct sd_thr_request *sd_prev;
24282 
24283 	/* Remove a reservation reclaim request from the list */
24284 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24285 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
24286 		/*
24287 		 * We are attempting to reinstate reservation for
24288 		 * this device. We wait for sd_reserve_release()
24289 		 * to return before we return.
24290 		 */
24291 		cv_wait(&sd_tr.srq_inprocess_cv,
24292 		    &sd_tr.srq_resv_reclaim_mutex);
24293 	} else {
24294 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
24295 		if (sd_mhreq && sd_mhreq->dev == dev) {
24296 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
24297 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
24298 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24299 			return;
24300 		}
24301 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
24302 			if (sd_mhreq && sd_mhreq->dev == dev) {
24303 				break;
24304 			}
24305 			sd_prev = sd_mhreq;
24306 		}
24307 		if (sd_mhreq != NULL) {
24308 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
24309 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
24310 		}
24311 	}
24312 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24313 }
24314 
24315 
24316 /*
24317  *    Function: sd_mhd_reset_notify_cb()
24318  *
24319  * Description: This is a call back function for scsi_reset_notify. This
24320  *		function updates the softstate reserved status and logs the
24321  *		reset. The driver scsi watch facility callback function
24322  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
24323  *		will reclaim the reservation.
24324  *
24325  *   Arguments: arg  - driver soft state (unit) structure
24326  */
24327 
24328 static void
24329 sd_mhd_reset_notify_cb(caddr_t arg)
24330 {
24331 	struct sd_lun *un = (struct sd_lun *)arg;
24332 
24333 	mutex_enter(SD_MUTEX(un));
24334 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
24335 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
24336 		SD_INFO(SD_LOG_IOCTL_MHD, un,
24337 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
24338 	}
24339 	mutex_exit(SD_MUTEX(un));
24340 }
24341 
24342 
24343 /*
24344  *    Function: sd_take_ownership()
24345  *
24346  * Description: This routine implements an algorithm to achieve a stable
24347  *		reservation on disks which don't implement priority reserve,
24348  *		and makes sure that other host lose re-reservation attempts.
24349  *		This algorithm contains of a loop that keeps issuing the RESERVE
24350  *		for some period of time (min_ownership_delay, default 6 seconds)
24351  *		During that loop, it looks to see if there has been a bus device
24352  *		reset or bus reset (both of which cause an existing reservation
24353  *		to be lost). If the reservation is lost issue RESERVE until a
24354  *		period of min_ownership_delay with no resets has gone by, or
24355  *		until max_ownership_delay has expired. This loop ensures that
24356  *		the host really did manage to reserve the device, in spite of
24357  *		resets. The looping for min_ownership_delay (default six
24358  *		seconds) is important to early generation clustering products,
24359  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
24360  *		MHIOCENFAILFAST periodic timer of two seconds. By having
24361  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
24362  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
24363  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
24364  *		have already noticed, via the MHIOCENFAILFAST polling, that it
24365  *		no longer "owns" the disk and will have panicked itself.  Thus,
24366  *		the host issuing the MHIOCTKOWN is assured (with timing
24367  *		dependencies) that by the time it actually starts to use the
24368  *		disk for real work, the old owner is no longer accessing it.
24369  *
24370  *		min_ownership_delay is the minimum amount of time for which the
24371  *		disk must be reserved continuously devoid of resets before the
24372  *		MHIOCTKOWN ioctl will return success.
24373  *
24374  *		max_ownership_delay indicates the amount of time by which the
24375  *		take ownership should succeed or timeout with an error.
24376  *
24377  *   Arguments: dev - the device 'dev_t'
24378  *		*p  - struct containing timing info.
24379  *
24380  * Return Code: 0 for success or error code
24381  */
24382 
24383 static int
24384 sd_take_ownership(dev_t dev, struct mhioctkown *p)
24385 {
24386 	struct sd_lun	*un;
24387 	int		rval;
24388 	int		err;
24389 	int		reservation_count   = 0;
24390 	int		min_ownership_delay =  6000000; /* in usec */
24391 	int		max_ownership_delay = 30000000; /* in usec */
24392 	clock_t		start_time;	/* starting time of this algorithm */
24393 	clock_t		end_time;	/* time limit for giving up */
24394 	clock_t		ownership_time;	/* time limit for stable ownership */
24395 	clock_t		current_time;
24396 	clock_t		previous_current_time;
24397 
24398 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24399 		return (ENXIO);
24400 	}
24401 
24402 	/*
24403 	 * Attempt a device reservation. A priority reservation is requested.
24404 	 */
24405 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
24406 	    != SD_SUCCESS) {
24407 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
24408 		    "sd_take_ownership: return(1)=%d\n", rval);
24409 		return (rval);
24410 	}
24411 
24412 	/* Update the softstate reserved status to indicate the reservation */
24413 	mutex_enter(SD_MUTEX(un));
24414 	un->un_resvd_status |= SD_RESERVE;
24415 	un->un_resvd_status &=
24416 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
24417 	mutex_exit(SD_MUTEX(un));
24418 
24419 	if (p != NULL) {
24420 		if (p->min_ownership_delay != 0) {
24421 			min_ownership_delay = p->min_ownership_delay * 1000;
24422 		}
24423 		if (p->max_ownership_delay != 0) {
24424 			max_ownership_delay = p->max_ownership_delay * 1000;
24425 		}
24426 	}
24427 	SD_INFO(SD_LOG_IOCTL_MHD, un,
24428 	    "sd_take_ownership: min, max delays: %d, %d\n",
24429 	    min_ownership_delay, max_ownership_delay);
24430 
24431 	start_time = ddi_get_lbolt();
24432 	current_time	= start_time;
24433 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
24434 	end_time	= start_time + drv_usectohz(max_ownership_delay);
24435 
24436 	while (current_time - end_time < 0) {
24437 		delay(drv_usectohz(500000));
24438 
24439 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
24440 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
24441 				mutex_enter(SD_MUTEX(un));
24442 				rval = (un->un_resvd_status &
24443 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
24444 				mutex_exit(SD_MUTEX(un));
24445 				break;
24446 			}
24447 		}
24448 		previous_current_time = current_time;
24449 		current_time = ddi_get_lbolt();
24450 		mutex_enter(SD_MUTEX(un));
24451 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
24452 			ownership_time = ddi_get_lbolt() +
24453 			    drv_usectohz(min_ownership_delay);
24454 			reservation_count = 0;
24455 		} else {
24456 			reservation_count++;
24457 		}
24458 		un->un_resvd_status |= SD_RESERVE;
24459 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
24460 		mutex_exit(SD_MUTEX(un));
24461 
24462 		SD_INFO(SD_LOG_IOCTL_MHD, un,
24463 		    "sd_take_ownership: ticks for loop iteration=%ld, "
24464 		    "reservation=%s\n", (current_time - previous_current_time),
24465 		    reservation_count ? "ok" : "reclaimed");
24466 
24467 		if (current_time - ownership_time >= 0 &&
24468 		    reservation_count >= 4) {
24469 			rval = 0; /* Achieved a stable ownership */
24470 			break;
24471 		}
24472 		if (current_time - end_time >= 0) {
24473 			rval = EACCES; /* No ownership in max possible time */
24474 			break;
24475 		}
24476 	}
24477 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
24478 	    "sd_take_ownership: return(2)=%d\n", rval);
24479 	return (rval);
24480 }
24481 
24482 
24483 /*
24484  *    Function: sd_reserve_release()
24485  *
24486  * Description: This function builds and sends scsi RESERVE, RELEASE, and
24487  *		PRIORITY RESERVE commands based on a user specified command type
24488  *
24489  *   Arguments: dev - the device 'dev_t'
24490  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
24491  *		      SD_RESERVE, SD_RELEASE
24492  *
24493  * Return Code: 0 or Error Code
24494  */
24495 
24496 static int
24497 sd_reserve_release(dev_t dev, int cmd)
24498 {
24499 	struct uscsi_cmd	*com = NULL;
24500 	struct sd_lun		*un = NULL;
24501 	char			cdb[CDB_GROUP0];
24502 	int			rval;
24503 
24504 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
24505 	    (cmd == SD_PRIORITY_RESERVE));
24506 
24507 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24508 		return (ENXIO);
24509 	}
24510 
24511 	/* instantiate and initialize the command and cdb */
24512 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24513 	bzero(cdb, CDB_GROUP0);
24514 	com->uscsi_flags   = USCSI_SILENT;
24515 	com->uscsi_timeout = un->un_reserve_release_time;
24516 	com->uscsi_cdblen  = CDB_GROUP0;
24517 	com->uscsi_cdb	   = cdb;
24518 	if (cmd == SD_RELEASE) {
24519 		cdb[0] = SCMD_RELEASE;
24520 	} else {
24521 		cdb[0] = SCMD_RESERVE;
24522 	}
24523 
24524 	/* Send the command. */
24525 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24526 	    SD_PATH_STANDARD);
24527 
24528 	/*
24529 	 * "break" a reservation that is held by another host, by issuing a
24530 	 * reset if priority reserve is desired, and we could not get the
24531 	 * device.
24532 	 */
24533 	if ((cmd == SD_PRIORITY_RESERVE) &&
24534 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
24535 		/*
24536 		 * First try to reset the LUN. If we cannot, then try a target
24537 		 * reset, followed by a bus reset if the target reset fails.
24538 		 */
24539 		int reset_retval = 0;
24540 		if (un->un_f_lun_reset_enabled == TRUE) {
24541 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
24542 		}
24543 		if (reset_retval == 0) {
24544 			/* The LUN reset either failed or was not issued */
24545 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
24546 		}
24547 		if ((reset_retval == 0) &&
24548 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
24549 			rval = EIO;
24550 			kmem_free(com, sizeof (*com));
24551 			return (rval);
24552 		}
24553 
24554 		bzero(com, sizeof (struct uscsi_cmd));
24555 		com->uscsi_flags   = USCSI_SILENT;
24556 		com->uscsi_cdb	   = cdb;
24557 		com->uscsi_cdblen  = CDB_GROUP0;
24558 		com->uscsi_timeout = 5;
24559 
24560 		/*
24561 		 * Reissue the last reserve command, this time without request
24562 		 * sense.  Assume that it is just a regular reserve command.
24563 		 */
24564 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24565 		    SD_PATH_STANDARD);
24566 	}
24567 
24568 	/* Return an error if still getting a reservation conflict. */
24569 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
24570 		rval = EACCES;
24571 	}
24572 
24573 	kmem_free(com, sizeof (*com));
24574 	return (rval);
24575 }
24576 
24577 
24578 #define	SD_NDUMP_RETRIES	12
24579 /*
24580  *	System Crash Dump routine
24581  */
24582 
24583 static int
24584 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
24585 {
24586 	int		instance;
24587 	int		partition;
24588 	int		i;
24589 	int		err;
24590 	struct sd_lun	*un;
24591 	struct scsi_pkt *wr_pktp;
24592 	struct buf	*wr_bp;
24593 	struct buf	wr_buf;
24594 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
24595 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
24596 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
24597 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
24598 	size_t		io_start_offset;
24599 	int		doing_rmw = FALSE;
24600 	int		rval;
24601 	ssize_t		dma_resid;
24602 	daddr_t		oblkno;
24603 	diskaddr_t	nblks = 0;
24604 	diskaddr_t	start_block;
24605 
24606 	instance = SDUNIT(dev);
24607 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
24608 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
24609 		return (ENXIO);
24610 	}
24611 
24612 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
24613 
24614 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
24615 
24616 	partition = SDPART(dev);
24617 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
24618 
24619 	/* Validate blocks to dump at against partition size. */
24620 
24621 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
24622 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
24623 
24624 	if ((blkno + nblk) > nblks) {
24625 		SD_TRACE(SD_LOG_DUMP, un,
24626 		    "sddump: dump range larger than partition: "
24627 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
24628 		    blkno, nblk, nblks);
24629 		return (EINVAL);
24630 	}
24631 
24632 	mutex_enter(&un->un_pm_mutex);
24633 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24634 		struct scsi_pkt *start_pktp;
24635 
24636 		mutex_exit(&un->un_pm_mutex);
24637 
24638 		/*
24639 		 * use pm framework to power on HBA 1st
24640 		 */
24641 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
24642 
24643 		/*
24644 		 * Dump no long uses sdpower to power on a device, it's
24645 		 * in-line here so it can be done in polled mode.
24646 		 */
24647 
24648 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
24649 
24650 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
24651 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
24652 
24653 		if (start_pktp == NULL) {
24654 			/* We were not given a SCSI packet, fail. */
24655 			return (EIO);
24656 		}
24657 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
24658 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
24659 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
24660 		start_pktp->pkt_flags = FLAG_NOINTR;
24661 
24662 		mutex_enter(SD_MUTEX(un));
24663 		SD_FILL_SCSI1_LUN(un, start_pktp);
24664 		mutex_exit(SD_MUTEX(un));
24665 		/*
24666 		 * Scsi_poll returns 0 (success) if the command completes and
24667 		 * the status block is STATUS_GOOD.
24668 		 */
24669 		if (sd_scsi_poll(un, start_pktp) != 0) {
24670 			scsi_destroy_pkt(start_pktp);
24671 			return (EIO);
24672 		}
24673 		scsi_destroy_pkt(start_pktp);
24674 		(void) sd_ddi_pm_resume(un);
24675 	} else {
24676 		mutex_exit(&un->un_pm_mutex);
24677 	}
24678 
24679 	mutex_enter(SD_MUTEX(un));
24680 	un->un_throttle = 0;
24681 
24682 	/*
24683 	 * The first time through, reset the specific target device.
24684 	 * However, when cpr calls sddump we know that sd is in a
24685 	 * a good state so no bus reset is required.
24686 	 * Clear sense data via Request Sense cmd.
24687 	 * In sddump we don't care about allow_bus_device_reset anymore
24688 	 */
24689 
24690 	if ((un->un_state != SD_STATE_SUSPENDED) &&
24691 	    (un->un_state != SD_STATE_DUMPING)) {
24692 
24693 		New_state(un, SD_STATE_DUMPING);
24694 
24695 		if (un->un_f_is_fibre == FALSE) {
24696 			mutex_exit(SD_MUTEX(un));
24697 			/*
24698 			 * Attempt a bus reset for parallel scsi.
24699 			 *
24700 			 * Note: A bus reset is required because on some host
24701 			 * systems (i.e. E420R) a bus device reset is
24702 			 * insufficient to reset the state of the target.
24703 			 *
24704 			 * Note: Don't issue the reset for fibre-channel,
24705 			 * because this tends to hang the bus (loop) for
24706 			 * too long while everyone is logging out and in
24707 			 * and the deadman timer for dumping will fire
24708 			 * before the dump is complete.
24709 			 */
24710 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
24711 				mutex_enter(SD_MUTEX(un));
24712 				Restore_state(un);
24713 				mutex_exit(SD_MUTEX(un));
24714 				return (EIO);
24715 			}
24716 
24717 			/* Delay to give the device some recovery time. */
24718 			drv_usecwait(10000);
24719 
24720 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
24721 				SD_INFO(SD_LOG_DUMP, un,
24722 				    "sddump: sd_send_polled_RQS failed\n");
24723 			}
24724 			mutex_enter(SD_MUTEX(un));
24725 		}
24726 	}
24727 
24728 	/*
24729 	 * Convert the partition-relative block number to a
24730 	 * disk physical block number.
24731 	 */
24732 	blkno += start_block;
24733 
24734 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
24735 
24736 
24737 	/*
24738 	 * Check if the device has a non-512 block size.
24739 	 */
24740 	wr_bp = NULL;
24741 	if (NOT_DEVBSIZE(un)) {
24742 		tgt_byte_offset = blkno * un->un_sys_blocksize;
24743 		tgt_byte_count = nblk * un->un_sys_blocksize;
24744 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
24745 		    (tgt_byte_count % un->un_tgt_blocksize)) {
24746 			doing_rmw = TRUE;
24747 			/*
24748 			 * Calculate the block number and number of block
24749 			 * in terms of the media block size.
24750 			 */
24751 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
24752 			tgt_nblk =
24753 			    ((tgt_byte_offset + tgt_byte_count +
24754 			    (un->un_tgt_blocksize - 1)) /
24755 			    un->un_tgt_blocksize) - tgt_blkno;
24756 
24757 			/*
24758 			 * Invoke the routine which is going to do read part
24759 			 * of read-modify-write.
24760 			 * Note that this routine returns a pointer to
24761 			 * a valid bp in wr_bp.
24762 			 */
24763 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
24764 			    &wr_bp);
24765 			if (err) {
24766 				mutex_exit(SD_MUTEX(un));
24767 				return (err);
24768 			}
24769 			/*
24770 			 * Offset is being calculated as -
24771 			 * (original block # * system block size) -
24772 			 * (new block # * target block size)
24773 			 */
24774 			io_start_offset =
24775 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
24776 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
24777 
24778 			ASSERT((io_start_offset >= 0) &&
24779 			    (io_start_offset < un->un_tgt_blocksize));
24780 			/*
24781 			 * Do the modify portion of read modify write.
24782 			 */
24783 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
24784 			    (size_t)nblk * un->un_sys_blocksize);
24785 		} else {
24786 			doing_rmw = FALSE;
24787 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
24788 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
24789 		}
24790 
24791 		/* Convert blkno and nblk to target blocks */
24792 		blkno = tgt_blkno;
24793 		nblk = tgt_nblk;
24794 	} else {
24795 		wr_bp = &wr_buf;
24796 		bzero(wr_bp, sizeof (struct buf));
24797 		wr_bp->b_flags		= B_BUSY;
24798 		wr_bp->b_un.b_addr	= addr;
24799 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
24800 		wr_bp->b_resid		= 0;
24801 	}
24802 
24803 	mutex_exit(SD_MUTEX(un));
24804 
24805 	/*
24806 	 * Obtain a SCSI packet for the write command.
24807 	 * It should be safe to call the allocator here without
24808 	 * worrying about being locked for DVMA mapping because
24809 	 * the address we're passed is already a DVMA mapping
24810 	 *
24811 	 * We are also not going to worry about semaphore ownership
24812 	 * in the dump buffer. Dumping is single threaded at present.
24813 	 */
24814 
24815 	wr_pktp = NULL;
24816 
24817 	dma_resid = wr_bp->b_bcount;
24818 	oblkno = blkno;
24819 
24820 	while (dma_resid != 0) {
24821 
24822 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
24823 		wr_bp->b_flags &= ~B_ERROR;
24824 
24825 		if (un->un_partial_dma_supported == 1) {
24826 			blkno = oblkno +
24827 			    ((wr_bp->b_bcount - dma_resid) /
24828 			    un->un_tgt_blocksize);
24829 			nblk = dma_resid / un->un_tgt_blocksize;
24830 
24831 			if (wr_pktp) {
24832 				/*
24833 				 * Partial DMA transfers after initial transfer
24834 				 */
24835 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
24836 				    blkno, nblk);
24837 			} else {
24838 				/* Initial transfer */
24839 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
24840 				    un->un_pkt_flags, NULL_FUNC, NULL,
24841 				    blkno, nblk);
24842 			}
24843 		} else {
24844 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
24845 			    0, NULL_FUNC, NULL, blkno, nblk);
24846 		}
24847 
24848 		if (rval == 0) {
24849 			/* We were given a SCSI packet, continue. */
24850 			break;
24851 		}
24852 
24853 		if (i == 0) {
24854 			if (wr_bp->b_flags & B_ERROR) {
24855 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24856 				    "no resources for dumping; "
24857 				    "error code: 0x%x, retrying",
24858 				    geterror(wr_bp));
24859 			} else {
24860 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24861 				    "no resources for dumping; retrying");
24862 			}
24863 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
24864 			if (wr_bp->b_flags & B_ERROR) {
24865 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
24866 				    "no resources for dumping; error code: "
24867 				    "0x%x, retrying\n", geterror(wr_bp));
24868 			}
24869 		} else {
24870 			if (wr_bp->b_flags & B_ERROR) {
24871 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
24872 				    "no resources for dumping; "
24873 				    "error code: 0x%x, retries failed, "
24874 				    "giving up.\n", geterror(wr_bp));
24875 			} else {
24876 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
24877 				    "no resources for dumping; "
24878 				    "retries failed, giving up.\n");
24879 			}
24880 			mutex_enter(SD_MUTEX(un));
24881 			Restore_state(un);
24882 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
24883 				mutex_exit(SD_MUTEX(un));
24884 				scsi_free_consistent_buf(wr_bp);
24885 			} else {
24886 				mutex_exit(SD_MUTEX(un));
24887 			}
24888 			return (EIO);
24889 		}
24890 		drv_usecwait(10000);
24891 	}
24892 
24893 	if (un->un_partial_dma_supported == 1) {
24894 		/*
24895 		 * save the resid from PARTIAL_DMA
24896 		 */
24897 		dma_resid = wr_pktp->pkt_resid;
24898 		if (dma_resid != 0)
24899 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
24900 		wr_pktp->pkt_resid = 0;
24901 	} else {
24902 		dma_resid = 0;
24903 	}
24904 
24905 	/* SunBug 1222170 */
24906 	wr_pktp->pkt_flags = FLAG_NOINTR;
24907 
24908 	err = EIO;
24909 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
24910 
24911 		/*
24912 		 * Scsi_poll returns 0 (success) if the command completes and
24913 		 * the status block is STATUS_GOOD.  We should only check
24914 		 * errors if this condition is not true.  Even then we should
24915 		 * send our own request sense packet only if we have a check
24916 		 * condition and auto request sense has not been performed by
24917 		 * the hba.
24918 		 */
24919 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
24920 
24921 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
24922 		    (wr_pktp->pkt_resid == 0)) {
24923 			err = SD_SUCCESS;
24924 			break;
24925 		}
24926 
24927 		/*
24928 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
24929 		 */
24930 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
24931 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24932 			    "Error while dumping state...Device is gone\n");
24933 			break;
24934 		}
24935 
24936 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
24937 			SD_INFO(SD_LOG_DUMP, un,
24938 			    "sddump: write failed with CHECK, try # %d\n", i);
24939 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
24940 				(void) sd_send_polled_RQS(un);
24941 			}
24942 
24943 			continue;
24944 		}
24945 
24946 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
24947 			int reset_retval = 0;
24948 
24949 			SD_INFO(SD_LOG_DUMP, un,
24950 			    "sddump: write failed with BUSY, try # %d\n", i);
24951 
24952 			if (un->un_f_lun_reset_enabled == TRUE) {
24953 				reset_retval = scsi_reset(SD_ADDRESS(un),
24954 				    RESET_LUN);
24955 			}
24956 			if (reset_retval == 0) {
24957 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
24958 			}
24959 			(void) sd_send_polled_RQS(un);
24960 
24961 		} else {
24962 			SD_INFO(SD_LOG_DUMP, un,
24963 			    "sddump: write failed with 0x%x, try # %d\n",
24964 			    SD_GET_PKT_STATUS(wr_pktp), i);
24965 			mutex_enter(SD_MUTEX(un));
24966 			sd_reset_target(un, wr_pktp);
24967 			mutex_exit(SD_MUTEX(un));
24968 		}
24969 
24970 		/*
24971 		 * If we are not getting anywhere with lun/target resets,
24972 		 * let's reset the bus.
24973 		 */
24974 		if (i == SD_NDUMP_RETRIES/2) {
24975 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
24976 			(void) sd_send_polled_RQS(un);
24977 		}
24978 	}
24979 	}
24980 
24981 	scsi_destroy_pkt(wr_pktp);
24982 	mutex_enter(SD_MUTEX(un));
24983 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
24984 		mutex_exit(SD_MUTEX(un));
24985 		scsi_free_consistent_buf(wr_bp);
24986 	} else {
24987 		mutex_exit(SD_MUTEX(un));
24988 	}
24989 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
24990 	return (err);
24991 }
24992 
24993 /*
24994  *    Function: sd_scsi_poll()
24995  *
24996  * Description: This is a wrapper for the scsi_poll call.
24997  *
24998  *   Arguments: sd_lun - The unit structure
24999  *              scsi_pkt - The scsi packet being sent to the device.
25000  *
25001  * Return Code: 0 - Command completed successfully with good status
25002  *             -1 - Command failed.  This could indicate a check condition
25003  *                  or other status value requiring recovery action.
25004  *
25005  * NOTE: This code is only called off sddump().
25006  */
25007 
25008 static int
25009 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
25010 {
25011 	int status;
25012 
25013 	ASSERT(un != NULL);
25014 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25015 	ASSERT(pktp != NULL);
25016 
25017 	status = SD_SUCCESS;
25018 
25019 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
25020 		pktp->pkt_flags |= un->un_tagflags;
25021 		pktp->pkt_flags &= ~FLAG_NODISCON;
25022 	}
25023 
25024 	status = sd_ddi_scsi_poll(pktp);
25025 	/*
25026 	 * Scsi_poll returns 0 (success) if the command completes and the
25027 	 * status block is STATUS_GOOD.  We should only check errors if this
25028 	 * condition is not true.  Even then we should send our own request
25029 	 * sense packet only if we have a check condition and auto
25030 	 * request sense has not been performed by the hba.
25031 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
25032 	 */
25033 	if ((status != SD_SUCCESS) &&
25034 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
25035 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
25036 	    (pktp->pkt_reason != CMD_DEV_GONE))
25037 		(void) sd_send_polled_RQS(un);
25038 
25039 	return (status);
25040 }
25041 
25042 /*
25043  *    Function: sd_send_polled_RQS()
25044  *
25045  * Description: This sends the request sense command to a device.
25046  *
25047  *   Arguments: sd_lun - The unit structure
25048  *
25049  * Return Code: 0 - Command completed successfully with good status
25050  *             -1 - Command failed.
25051  *
25052  */
25053 
25054 static int
25055 sd_send_polled_RQS(struct sd_lun *un)
25056 {
25057 	int	ret_val;
25058 	struct	scsi_pkt	*rqs_pktp;
25059 	struct	buf		*rqs_bp;
25060 
25061 	ASSERT(un != NULL);
25062 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25063 
25064 	ret_val = SD_SUCCESS;
25065 
25066 	rqs_pktp = un->un_rqs_pktp;
25067 	rqs_bp	 = un->un_rqs_bp;
25068 
25069 	mutex_enter(SD_MUTEX(un));
25070 
25071 	if (un->un_sense_isbusy) {
25072 		ret_val = SD_FAILURE;
25073 		mutex_exit(SD_MUTEX(un));
25074 		return (ret_val);
25075 	}
25076 
25077 	/*
25078 	 * If the request sense buffer (and packet) is not in use,
25079 	 * let's set the un_sense_isbusy and send our packet
25080 	 */
25081 	un->un_sense_isbusy 	= 1;
25082 	rqs_pktp->pkt_resid  	= 0;
25083 	rqs_pktp->pkt_reason 	= 0;
25084 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
25085 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
25086 
25087 	mutex_exit(SD_MUTEX(un));
25088 
25089 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
25090 	    " 0x%p\n", rqs_bp->b_un.b_addr);
25091 
25092 	/*
25093 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
25094 	 * axle - it has a call into us!
25095 	 */
25096 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
25097 		SD_INFO(SD_LOG_COMMON, un,
25098 		    "sd_send_polled_RQS: RQS failed\n");
25099 	}
25100 
25101 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
25102 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
25103 
25104 	mutex_enter(SD_MUTEX(un));
25105 	un->un_sense_isbusy = 0;
25106 	mutex_exit(SD_MUTEX(un));
25107 
25108 	return (ret_val);
25109 }
25110 
25111 /*
25112  * Defines needed for localized version of the scsi_poll routine.
25113  */
25114 #define	CSEC		10000			/* usecs */
25115 #define	SEC_TO_CSEC	(1000000/CSEC)
25116 
25117 /*
25118  *    Function: sd_ddi_scsi_poll()
25119  *
25120  * Description: Localized version of the scsi_poll routine.  The purpose is to
25121  *		send a scsi_pkt to a device as a polled command.  This version
25122  *		is to ensure more robust handling of transport errors.
25123  *		Specifically this routine cures not ready, coming ready
25124  *		transition for power up and reset of sonoma's.  This can take
25125  *		up to 45 seconds for power-on and 20 seconds for reset of a
25126  * 		sonoma lun.
25127  *
25128  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
25129  *
25130  * Return Code: 0 - Command completed successfully with good status
25131  *             -1 - Command failed.
25132  *
25133  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
25134  * be fixed (removing this code), we need to determine how to handle the
25135  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
25136  *
25137  * NOTE: This code is only called off sddump().
25138  */
25139 static int
25140 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
25141 {
25142 	int			rval = -1;
25143 	int			savef;
25144 	long			savet;
25145 	void			(*savec)();
25146 	int			timeout;
25147 	int			busy_count;
25148 	int			poll_delay;
25149 	int			rc;
25150 	uint8_t			*sensep;
25151 	struct scsi_arq_status	*arqstat;
25152 	extern int		do_polled_io;
25153 
25154 	ASSERT(pkt->pkt_scbp);
25155 
25156 	/*
25157 	 * save old flags..
25158 	 */
25159 	savef = pkt->pkt_flags;
25160 	savec = pkt->pkt_comp;
25161 	savet = pkt->pkt_time;
25162 
25163 	pkt->pkt_flags |= FLAG_NOINTR;
25164 
25165 	/*
25166 	 * XXX there is nothing in the SCSA spec that states that we should not
25167 	 * do a callback for polled cmds; however, removing this will break sd
25168 	 * and probably other target drivers
25169 	 */
25170 	pkt->pkt_comp = NULL;
25171 
25172 	/*
25173 	 * we don't like a polled command without timeout.
25174 	 * 60 seconds seems long enough.
25175 	 */
25176 	if (pkt->pkt_time == 0)
25177 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
25178 
25179 	/*
25180 	 * Send polled cmd.
25181 	 *
25182 	 * We do some error recovery for various errors.  Tran_busy,
25183 	 * queue full, and non-dispatched commands are retried every 10 msec.
25184 	 * as they are typically transient failures.  Busy status and Not
25185 	 * Ready are retried every second as this status takes a while to
25186 	 * change.
25187 	 */
25188 	timeout = pkt->pkt_time * SEC_TO_CSEC;
25189 
25190 	for (busy_count = 0; busy_count < timeout; busy_count++) {
25191 		/*
25192 		 * Initialize pkt status variables.
25193 		 */
25194 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
25195 
25196 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
25197 			if (rc != TRAN_BUSY) {
25198 				/* Transport failed - give up. */
25199 				break;
25200 			} else {
25201 				/* Transport busy - try again. */
25202 				poll_delay = 1 * CSEC;		/* 10 msec. */
25203 			}
25204 		} else {
25205 			/*
25206 			 * Transport accepted - check pkt status.
25207 			 */
25208 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
25209 			if ((pkt->pkt_reason == CMD_CMPLT) &&
25210 			    (rc == STATUS_CHECK) &&
25211 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
25212 				arqstat =
25213 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
25214 				sensep = (uint8_t *)&arqstat->sts_sensedata;
25215 			} else {
25216 				sensep = NULL;
25217 			}
25218 
25219 			if ((pkt->pkt_reason == CMD_CMPLT) &&
25220 			    (rc == STATUS_GOOD)) {
25221 				/* No error - we're done */
25222 				rval = 0;
25223 				break;
25224 
25225 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
25226 				/* Lost connection - give up */
25227 				break;
25228 
25229 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
25230 			    (pkt->pkt_state == 0)) {
25231 				/* Pkt not dispatched - try again. */
25232 				poll_delay = 1 * CSEC;		/* 10 msec. */
25233 
25234 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
25235 			    (rc == STATUS_QFULL)) {
25236 				/* Queue full - try again. */
25237 				poll_delay = 1 * CSEC;		/* 10 msec. */
25238 
25239 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
25240 			    (rc == STATUS_BUSY)) {
25241 				/* Busy - try again. */
25242 				poll_delay = 100 * CSEC;	/* 1 sec. */
25243 				busy_count += (SEC_TO_CSEC - 1);
25244 
25245 			} else if ((sensep != NULL) &&
25246 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
25247 				/*
25248 				 * Unit Attention - try again.
25249 				 * Pretend it took 1 sec.
25250 				 * NOTE: 'continue' avoids poll_delay
25251 				 */
25252 				busy_count += (SEC_TO_CSEC - 1);
25253 				continue;
25254 
25255 			} else if ((sensep != NULL) &&
25256 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
25257 			    (scsi_sense_asc(sensep) == 0x04) &&
25258 			    (scsi_sense_ascq(sensep) == 0x01)) {
25259 				/*
25260 				 * Not ready -> ready - try again.
25261 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
25262 				 * ...same as STATUS_BUSY
25263 				 */
25264 				poll_delay = 100 * CSEC;	/* 1 sec. */
25265 				busy_count += (SEC_TO_CSEC - 1);
25266 
25267 			} else {
25268 				/* BAD status - give up. */
25269 				break;
25270 			}
25271 		}
25272 
25273 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
25274 		    !do_polled_io) {
25275 			delay(drv_usectohz(poll_delay));
25276 		} else {
25277 			/* we busy wait during cpr_dump or interrupt threads */
25278 			drv_usecwait(poll_delay);
25279 		}
25280 	}
25281 
25282 	pkt->pkt_flags = savef;
25283 	pkt->pkt_comp = savec;
25284 	pkt->pkt_time = savet;
25285 
25286 	/* return on error */
25287 	if (rval)
25288 		return (rval);
25289 
25290 	/*
25291 	 * This is not a performance critical code path.
25292 	 *
25293 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
25294 	 * issues associated with looking at DMA memory prior to
25295 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
25296 	 */
25297 	scsi_sync_pkt(pkt);
25298 	return (0);
25299 }
25300 
25301 
25302 
25303 /*
25304  *    Function: sd_persistent_reservation_in_read_keys
25305  *
25306  * Description: This routine is the driver entry point for handling CD-ROM
25307  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
25308  *		by sending the SCSI-3 PRIN commands to the device.
25309  *		Processes the read keys command response by copying the
25310  *		reservation key information into the user provided buffer.
25311  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
25312  *
25313  *   Arguments: un   -  Pointer to soft state struct for the target.
25314  *		usrp -	user provided pointer to multihost Persistent In Read
25315  *			Keys structure (mhioc_inkeys_t)
25316  *		flag -	this argument is a pass through to ddi_copyxxx()
25317  *			directly from the mode argument of ioctl().
25318  *
25319  * Return Code: 0   - Success
25320  *		EACCES
25321  *		ENOTSUP
25322  *		errno return code from sd_send_scsi_cmd()
25323  *
25324  *     Context: Can sleep. Does not return until command is completed.
25325  */
25326 
25327 static int
25328 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
25329     mhioc_inkeys_t *usrp, int flag)
25330 {
25331 #ifdef _MULTI_DATAMODEL
25332 	struct mhioc_key_list32	li32;
25333 #endif
25334 	sd_prin_readkeys_t	*in;
25335 	mhioc_inkeys_t		*ptr;
25336 	mhioc_key_list_t	li;
25337 	uchar_t			*data_bufp;
25338 	int 			data_len;
25339 	int			rval = 0;
25340 	size_t			copysz;
25341 	sd_ssc_t		*ssc;
25342 
25343 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
25344 		return (EINVAL);
25345 	}
25346 	bzero(&li, sizeof (mhioc_key_list_t));
25347 
25348 	ssc = sd_ssc_init(un);
25349 
25350 	/*
25351 	 * Get the listsize from user
25352 	 */
25353 #ifdef _MULTI_DATAMODEL
25354 
25355 	switch (ddi_model_convert_from(flag & FMODELS)) {
25356 	case DDI_MODEL_ILP32:
25357 		copysz = sizeof (struct mhioc_key_list32);
25358 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
25359 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25360 			    "sd_persistent_reservation_in_read_keys: "
25361 			    "failed ddi_copyin: mhioc_key_list32_t\n");
25362 			rval = EFAULT;
25363 			goto done;
25364 		}
25365 		li.listsize = li32.listsize;
25366 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
25367 		break;
25368 
25369 	case DDI_MODEL_NONE:
25370 		copysz = sizeof (mhioc_key_list_t);
25371 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
25372 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25373 			    "sd_persistent_reservation_in_read_keys: "
25374 			    "failed ddi_copyin: mhioc_key_list_t\n");
25375 			rval = EFAULT;
25376 			goto done;
25377 		}
25378 		break;
25379 	}
25380 
25381 #else /* ! _MULTI_DATAMODEL */
25382 	copysz = sizeof (mhioc_key_list_t);
25383 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
25384 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25385 		    "sd_persistent_reservation_in_read_keys: "
25386 		    "failed ddi_copyin: mhioc_key_list_t\n");
25387 		rval = EFAULT;
25388 		goto done;
25389 	}
25390 #endif
25391 
25392 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
25393 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
25394 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
25395 
25396 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
25397 	    data_len, data_bufp);
25398 	if (rval != 0) {
25399 		if (rval == EIO)
25400 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
25401 		else
25402 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
25403 		goto done;
25404 	}
25405 	in = (sd_prin_readkeys_t *)data_bufp;
25406 	ptr->generation = BE_32(in->generation);
25407 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
25408 
25409 	/*
25410 	 * Return the min(listsize, listlen) keys
25411 	 */
25412 #ifdef _MULTI_DATAMODEL
25413 
25414 	switch (ddi_model_convert_from(flag & FMODELS)) {
25415 	case DDI_MODEL_ILP32:
25416 		li32.listlen = li.listlen;
25417 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
25418 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25419 			    "sd_persistent_reservation_in_read_keys: "
25420 			    "failed ddi_copyout: mhioc_key_list32_t\n");
25421 			rval = EFAULT;
25422 			goto done;
25423 		}
25424 		break;
25425 
25426 	case DDI_MODEL_NONE:
25427 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
25428 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25429 			    "sd_persistent_reservation_in_read_keys: "
25430 			    "failed ddi_copyout: mhioc_key_list_t\n");
25431 			rval = EFAULT;
25432 			goto done;
25433 		}
25434 		break;
25435 	}
25436 
25437 #else /* ! _MULTI_DATAMODEL */
25438 
25439 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
25440 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25441 		    "sd_persistent_reservation_in_read_keys: "
25442 		    "failed ddi_copyout: mhioc_key_list_t\n");
25443 		rval = EFAULT;
25444 		goto done;
25445 	}
25446 
25447 #endif /* _MULTI_DATAMODEL */
25448 
25449 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
25450 	    li.listsize * MHIOC_RESV_KEY_SIZE);
25451 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
25452 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25453 		    "sd_persistent_reservation_in_read_keys: "
25454 		    "failed ddi_copyout: keylist\n");
25455 		rval = EFAULT;
25456 	}
25457 done:
25458 	sd_ssc_fini(ssc);
25459 	kmem_free(data_bufp, data_len);
25460 	return (rval);
25461 }
25462 
25463 
25464 /*
25465  *    Function: sd_persistent_reservation_in_read_resv
25466  *
25467  * Description: This routine is the driver entry point for handling CD-ROM
25468  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
25469  *		by sending the SCSI-3 PRIN commands to the device.
25470  *		Process the read persistent reservations command response by
25471  *		copying the reservation information into the user provided
25472  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
25473  *
25474  *   Arguments: un   -  Pointer to soft state struct for the target.
25475  *		usrp -	user provided pointer to multihost Persistent In Read
25476  *			Keys structure (mhioc_inkeys_t)
25477  *		flag -	this argument is a pass through to ddi_copyxxx()
25478  *			directly from the mode argument of ioctl().
25479  *
25480  * Return Code: 0   - Success
25481  *		EACCES
25482  *		ENOTSUP
25483  *		errno return code from sd_send_scsi_cmd()
25484  *
25485  *     Context: Can sleep. Does not return until command is completed.
25486  */
25487 
25488 static int
25489 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
25490     mhioc_inresvs_t *usrp, int flag)
25491 {
25492 #ifdef _MULTI_DATAMODEL
25493 	struct mhioc_resv_desc_list32 resvlist32;
25494 #endif
25495 	sd_prin_readresv_t	*in;
25496 	mhioc_inresvs_t		*ptr;
25497 	sd_readresv_desc_t	*readresv_ptr;
25498 	mhioc_resv_desc_list_t	resvlist;
25499 	mhioc_resv_desc_t 	resvdesc;
25500 	uchar_t			*data_bufp = NULL;
25501 	int 			data_len;
25502 	int			rval = 0;
25503 	int			i;
25504 	size_t			copysz;
25505 	mhioc_resv_desc_t	*bufp;
25506 	sd_ssc_t		*ssc;
25507 
25508 	if ((ptr = usrp) == NULL) {
25509 		return (EINVAL);
25510 	}
25511 
25512 	ssc = sd_ssc_init(un);
25513 
25514 	/*
25515 	 * Get the listsize from user
25516 	 */
25517 #ifdef _MULTI_DATAMODEL
25518 	switch (ddi_model_convert_from(flag & FMODELS)) {
25519 	case DDI_MODEL_ILP32:
25520 		copysz = sizeof (struct mhioc_resv_desc_list32);
25521 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
25522 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25523 			    "sd_persistent_reservation_in_read_resv: "
25524 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
25525 			rval = EFAULT;
25526 			goto done;
25527 		}
25528 		resvlist.listsize = resvlist32.listsize;
25529 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
25530 		break;
25531 
25532 	case DDI_MODEL_NONE:
25533 		copysz = sizeof (mhioc_resv_desc_list_t);
25534 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
25535 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25536 			    "sd_persistent_reservation_in_read_resv: "
25537 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
25538 			rval = EFAULT;
25539 			goto done;
25540 		}
25541 		break;
25542 	}
25543 #else /* ! _MULTI_DATAMODEL */
25544 	copysz = sizeof (mhioc_resv_desc_list_t);
25545 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
25546 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25547 		    "sd_persistent_reservation_in_read_resv: "
25548 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
25549 		rval = EFAULT;
25550 		goto done;
25551 	}
25552 #endif /* ! _MULTI_DATAMODEL */
25553 
25554 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
25555 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
25556 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
25557 
25558 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
25559 	    data_len, data_bufp);
25560 	if (rval != 0) {
25561 		if (rval == EIO)
25562 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
25563 		else
25564 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
25565 		goto done;
25566 	}
25567 	in = (sd_prin_readresv_t *)data_bufp;
25568 	ptr->generation = BE_32(in->generation);
25569 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
25570 
25571 	/*
25572 	 * Return the min(listsize, listlen( keys
25573 	 */
25574 #ifdef _MULTI_DATAMODEL
25575 
25576 	switch (ddi_model_convert_from(flag & FMODELS)) {
25577 	case DDI_MODEL_ILP32:
25578 		resvlist32.listlen = resvlist.listlen;
25579 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
25580 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25581 			    "sd_persistent_reservation_in_read_resv: "
25582 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
25583 			rval = EFAULT;
25584 			goto done;
25585 		}
25586 		break;
25587 
25588 	case DDI_MODEL_NONE:
25589 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
25590 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25591 			    "sd_persistent_reservation_in_read_resv: "
25592 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
25593 			rval = EFAULT;
25594 			goto done;
25595 		}
25596 		break;
25597 	}
25598 
25599 #else /* ! _MULTI_DATAMODEL */
25600 
25601 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
25602 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25603 		    "sd_persistent_reservation_in_read_resv: "
25604 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
25605 		rval = EFAULT;
25606 		goto done;
25607 	}
25608 
25609 #endif /* ! _MULTI_DATAMODEL */
25610 
25611 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
25612 	bufp = resvlist.list;
25613 	copysz = sizeof (mhioc_resv_desc_t);
25614 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
25615 	    i++, readresv_ptr++, bufp++) {
25616 
25617 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
25618 		    MHIOC_RESV_KEY_SIZE);
25619 		resvdesc.type  = readresv_ptr->type;
25620 		resvdesc.scope = readresv_ptr->scope;
25621 		resvdesc.scope_specific_addr =
25622 		    BE_32(readresv_ptr->scope_specific_addr);
25623 
25624 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
25625 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25626 			    "sd_persistent_reservation_in_read_resv: "
25627 			    "failed ddi_copyout: resvlist\n");
25628 			rval = EFAULT;
25629 			goto done;
25630 		}
25631 	}
25632 done:
25633 	sd_ssc_fini(ssc);
25634 	/* only if data_bufp is allocated, we need to free it */
25635 	if (data_bufp) {
25636 		kmem_free(data_bufp, data_len);
25637 	}
25638 	return (rval);
25639 }
25640 
25641 
25642 /*
25643  *    Function: sr_change_blkmode()
25644  *
25645  * Description: This routine is the driver entry point for handling CD-ROM
25646  *		block mode ioctl requests. Support for returning and changing
25647  *		the current block size in use by the device is implemented. The
25648  *		LBA size is changed via a MODE SELECT Block Descriptor.
25649  *
25650  *		This routine issues a mode sense with an allocation length of
25651  *		12 bytes for the mode page header and a single block descriptor.
25652  *
25653  *   Arguments: dev - the device 'dev_t'
25654  *		cmd - the request type; one of CDROMGBLKMODE (get) or
25655  *		      CDROMSBLKMODE (set)
25656  *		data - current block size or requested block size
25657  *		flag - this argument is a pass through to ddi_copyxxx() directly
25658  *		       from the mode argument of ioctl().
25659  *
25660  * Return Code: the code returned by sd_send_scsi_cmd()
25661  *		EINVAL if invalid arguments are provided
25662  *		EFAULT if ddi_copyxxx() fails
25663  *		ENXIO if fail ddi_get_soft_state
25664  *		EIO if invalid mode sense block descriptor length
25665  *
25666  */
25667 
25668 static int
25669 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
25670 {
25671 	struct sd_lun			*un = NULL;
25672 	struct mode_header		*sense_mhp, *select_mhp;
25673 	struct block_descriptor		*sense_desc, *select_desc;
25674 	int				current_bsize;
25675 	int				rval = EINVAL;
25676 	uchar_t				*sense = NULL;
25677 	uchar_t				*select = NULL;
25678 	sd_ssc_t			*ssc;
25679 
25680 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
25681 
25682 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25683 		return (ENXIO);
25684 	}
25685 
25686 	/*
25687 	 * The block length is changed via the Mode Select block descriptor, the
25688 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
25689 	 * required as part of this routine. Therefore the mode sense allocation
25690 	 * length is specified to be the length of a mode page header and a
25691 	 * block descriptor.
25692 	 */
25693 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
25694 
25695 	ssc = sd_ssc_init(un);
25696 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
25697 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
25698 	sd_ssc_fini(ssc);
25699 	if (rval != 0) {
25700 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25701 		    "sr_change_blkmode: Mode Sense Failed\n");
25702 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25703 		return (rval);
25704 	}
25705 
25706 	/* Check the block descriptor len to handle only 1 block descriptor */
25707 	sense_mhp = (struct mode_header *)sense;
25708 	if ((sense_mhp->bdesc_length == 0) ||
25709 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
25710 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25711 		    "sr_change_blkmode: Mode Sense returned invalid block"
25712 		    " descriptor length\n");
25713 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25714 		return (EIO);
25715 	}
25716 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
25717 	current_bsize = ((sense_desc->blksize_hi << 16) |
25718 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
25719 
25720 	/* Process command */
25721 	switch (cmd) {
25722 	case CDROMGBLKMODE:
25723 		/* Return the block size obtained during the mode sense */
25724 		if (ddi_copyout(&current_bsize, (void *)data,
25725 		    sizeof (int), flag) != 0)
25726 			rval = EFAULT;
25727 		break;
25728 	case CDROMSBLKMODE:
25729 		/* Validate the requested block size */
25730 		switch (data) {
25731 		case CDROM_BLK_512:
25732 		case CDROM_BLK_1024:
25733 		case CDROM_BLK_2048:
25734 		case CDROM_BLK_2056:
25735 		case CDROM_BLK_2336:
25736 		case CDROM_BLK_2340:
25737 		case CDROM_BLK_2352:
25738 		case CDROM_BLK_2368:
25739 		case CDROM_BLK_2448:
25740 		case CDROM_BLK_2646:
25741 		case CDROM_BLK_2647:
25742 			break;
25743 		default:
25744 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25745 			    "sr_change_blkmode: "
25746 			    "Block Size '%ld' Not Supported\n", data);
25747 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25748 			return (EINVAL);
25749 		}
25750 
25751 		/*
25752 		 * The current block size matches the requested block size so
25753 		 * there is no need to send the mode select to change the size
25754 		 */
25755 		if (current_bsize == data) {
25756 			break;
25757 		}
25758 
25759 		/* Build the select data for the requested block size */
25760 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
25761 		select_mhp = (struct mode_header *)select;
25762 		select_desc =
25763 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
25764 		/*
25765 		 * The LBA size is changed via the block descriptor, so the
25766 		 * descriptor is built according to the user data
25767 		 */
25768 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
25769 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
25770 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
25771 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
25772 
25773 		/* Send the mode select for the requested block size */
25774 		ssc = sd_ssc_init(un);
25775 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
25776 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
25777 		    SD_PATH_STANDARD);
25778 		sd_ssc_fini(ssc);
25779 		if (rval != 0) {
25780 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25781 			    "sr_change_blkmode: Mode Select Failed\n");
25782 			/*
25783 			 * The mode select failed for the requested block size,
25784 			 * so reset the data for the original block size and
25785 			 * send it to the target. The error is indicated by the
25786 			 * return value for the failed mode select.
25787 			 */
25788 			select_desc->blksize_hi  = sense_desc->blksize_hi;
25789 			select_desc->blksize_mid = sense_desc->blksize_mid;
25790 			select_desc->blksize_lo  = sense_desc->blksize_lo;
25791 			ssc = sd_ssc_init(un);
25792 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
25793 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
25794 			    SD_PATH_STANDARD);
25795 			sd_ssc_fini(ssc);
25796 		} else {
25797 			ASSERT(!mutex_owned(SD_MUTEX(un)));
25798 			mutex_enter(SD_MUTEX(un));
25799 			sd_update_block_info(un, (uint32_t)data, 0);
25800 			mutex_exit(SD_MUTEX(un));
25801 		}
25802 		break;
25803 	default:
25804 		/* should not reach here, but check anyway */
25805 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25806 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
25807 		rval = EINVAL;
25808 		break;
25809 	}
25810 
25811 	if (select) {
25812 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
25813 	}
25814 	if (sense) {
25815 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25816 	}
25817 	return (rval);
25818 }
25819 
25820 
25821 /*
25822  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
25823  * implement driver support for getting and setting the CD speed. The command
25824  * set used will be based on the device type. If the device has not been
25825  * identified as MMC the Toshiba vendor specific mode page will be used. If
25826  * the device is MMC but does not support the Real Time Streaming feature
25827  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
25828  * be used to read the speed.
25829  */
25830 
25831 /*
25832  *    Function: sr_change_speed()
25833  *
25834  * Description: This routine is the driver entry point for handling CD-ROM
25835  *		drive speed ioctl requests for devices supporting the Toshiba
25836  *		vendor specific drive speed mode page. Support for returning
25837  *		and changing the current drive speed in use by the device is
25838  *		implemented.
25839  *
25840  *   Arguments: dev - the device 'dev_t'
25841  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
25842  *		      CDROMSDRVSPEED (set)
25843  *		data - current drive speed or requested drive speed
25844  *		flag - this argument is a pass through to ddi_copyxxx() directly
25845  *		       from the mode argument of ioctl().
25846  *
25847  * Return Code: the code returned by sd_send_scsi_cmd()
25848  *		EINVAL if invalid arguments are provided
25849  *		EFAULT if ddi_copyxxx() fails
25850  *		ENXIO if fail ddi_get_soft_state
25851  *		EIO if invalid mode sense block descriptor length
25852  */
25853 
25854 static int
25855 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
25856 {
25857 	struct sd_lun			*un = NULL;
25858 	struct mode_header		*sense_mhp, *select_mhp;
25859 	struct mode_speed		*sense_page, *select_page;
25860 	int				current_speed;
25861 	int				rval = EINVAL;
25862 	int				bd_len;
25863 	uchar_t				*sense = NULL;
25864 	uchar_t				*select = NULL;
25865 	sd_ssc_t			*ssc;
25866 
25867 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
25868 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25869 		return (ENXIO);
25870 	}
25871 
25872 	/*
25873 	 * Note: The drive speed is being modified here according to a Toshiba
25874 	 * vendor specific mode page (0x31).
25875 	 */
25876 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
25877 
25878 	ssc = sd_ssc_init(un);
25879 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
25880 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
25881 	    SD_PATH_STANDARD);
25882 	sd_ssc_fini(ssc);
25883 	if (rval != 0) {
25884 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25885 		    "sr_change_speed: Mode Sense Failed\n");
25886 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25887 		return (rval);
25888 	}
25889 	sense_mhp  = (struct mode_header *)sense;
25890 
25891 	/* Check the block descriptor len to handle only 1 block descriptor */
25892 	bd_len = sense_mhp->bdesc_length;
25893 	if (bd_len > MODE_BLK_DESC_LENGTH) {
25894 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25895 		    "sr_change_speed: Mode Sense returned invalid block "
25896 		    "descriptor length\n");
25897 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25898 		return (EIO);
25899 	}
25900 
25901 	sense_page = (struct mode_speed *)
25902 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
25903 	current_speed = sense_page->speed;
25904 
25905 	/* Process command */
25906 	switch (cmd) {
25907 	case CDROMGDRVSPEED:
25908 		/* Return the drive speed obtained during the mode sense */
25909 		if (current_speed == 0x2) {
25910 			current_speed = CDROM_TWELVE_SPEED;
25911 		}
25912 		if (ddi_copyout(&current_speed, (void *)data,
25913 		    sizeof (int), flag) != 0) {
25914 			rval = EFAULT;
25915 		}
25916 		break;
25917 	case CDROMSDRVSPEED:
25918 		/* Validate the requested drive speed */
25919 		switch ((uchar_t)data) {
25920 		case CDROM_TWELVE_SPEED:
25921 			data = 0x2;
25922 			/*FALLTHROUGH*/
25923 		case CDROM_NORMAL_SPEED:
25924 		case CDROM_DOUBLE_SPEED:
25925 		case CDROM_QUAD_SPEED:
25926 		case CDROM_MAXIMUM_SPEED:
25927 			break;
25928 		default:
25929 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25930 			    "sr_change_speed: "
25931 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
25932 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25933 			return (EINVAL);
25934 		}
25935 
25936 		/*
25937 		 * The current drive speed matches the requested drive speed so
25938 		 * there is no need to send the mode select to change the speed
25939 		 */
25940 		if (current_speed == data) {
25941 			break;
25942 		}
25943 
25944 		/* Build the select data for the requested drive speed */
25945 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
25946 		select_mhp = (struct mode_header *)select;
25947 		select_mhp->bdesc_length = 0;
25948 		select_page =
25949 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
25950 		select_page =
25951 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
25952 		select_page->mode_page.code = CDROM_MODE_SPEED;
25953 		select_page->mode_page.length = 2;
25954 		select_page->speed = (uchar_t)data;
25955 
25956 		/* Send the mode select for the requested block size */
25957 		ssc = sd_ssc_init(un);
25958 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
25959 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
25960 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25961 		sd_ssc_fini(ssc);
25962 		if (rval != 0) {
25963 			/*
25964 			 * The mode select failed for the requested drive speed,
25965 			 * so reset the data for the original drive speed and
25966 			 * send it to the target. The error is indicated by the
25967 			 * return value for the failed mode select.
25968 			 */
25969 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25970 			    "sr_drive_speed: Mode Select Failed\n");
25971 			select_page->speed = sense_page->speed;
25972 			ssc = sd_ssc_init(un);
25973 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
25974 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
25975 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25976 			sd_ssc_fini(ssc);
25977 		}
25978 		break;
25979 	default:
25980 		/* should not reach here, but check anyway */
25981 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25982 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
25983 		rval = EINVAL;
25984 		break;
25985 	}
25986 
25987 	if (select) {
25988 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
25989 	}
25990 	if (sense) {
25991 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25992 	}
25993 
25994 	return (rval);
25995 }
25996 
25997 
25998 /*
25999  *    Function: sr_atapi_change_speed()
26000  *
26001  * Description: This routine is the driver entry point for handling CD-ROM
26002  *		drive speed ioctl requests for MMC devices that do not support
26003  *		the Real Time Streaming feature (0x107).
26004  *
26005  *		Note: This routine will use the SET SPEED command which may not
26006  *		be supported by all devices.
26007  *
26008  *   Arguments: dev- the device 'dev_t'
26009  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
26010  *		     CDROMSDRVSPEED (set)
26011  *		data- current drive speed or requested drive speed
26012  *		flag- this argument is a pass through to ddi_copyxxx() directly
26013  *		      from the mode argument of ioctl().
26014  *
26015  * Return Code: the code returned by sd_send_scsi_cmd()
26016  *		EINVAL if invalid arguments are provided
26017  *		EFAULT if ddi_copyxxx() fails
26018  *		ENXIO if fail ddi_get_soft_state
26019  *		EIO if invalid mode sense block descriptor length
26020  */
26021 
26022 static int
26023 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
26024 {
26025 	struct sd_lun			*un;
26026 	struct uscsi_cmd		*com = NULL;
26027 	struct mode_header_grp2		*sense_mhp;
26028 	uchar_t				*sense_page;
26029 	uchar_t				*sense = NULL;
26030 	char				cdb[CDB_GROUP5];
26031 	int				bd_len;
26032 	int				current_speed = 0;
26033 	int				max_speed = 0;
26034 	int				rval;
26035 	sd_ssc_t			*ssc;
26036 
26037 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
26038 
26039 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26040 		return (ENXIO);
26041 	}
26042 
26043 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
26044 
26045 	ssc = sd_ssc_init(un);
26046 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
26047 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
26048 	    SD_PATH_STANDARD);
26049 	sd_ssc_fini(ssc);
26050 	if (rval != 0) {
26051 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26052 		    "sr_atapi_change_speed: Mode Sense Failed\n");
26053 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26054 		return (rval);
26055 	}
26056 
26057 	/* Check the block descriptor len to handle only 1 block descriptor */
26058 	sense_mhp = (struct mode_header_grp2 *)sense;
26059 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
26060 	if (bd_len > MODE_BLK_DESC_LENGTH) {
26061 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26062 		    "sr_atapi_change_speed: Mode Sense returned invalid "
26063 		    "block descriptor length\n");
26064 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26065 		return (EIO);
26066 	}
26067 
26068 	/* Calculate the current and maximum drive speeds */
26069 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
26070 	current_speed = (sense_page[14] << 8) | sense_page[15];
26071 	max_speed = (sense_page[8] << 8) | sense_page[9];
26072 
26073 	/* Process the command */
26074 	switch (cmd) {
26075 	case CDROMGDRVSPEED:
26076 		current_speed /= SD_SPEED_1X;
26077 		if (ddi_copyout(&current_speed, (void *)data,
26078 		    sizeof (int), flag) != 0)
26079 			rval = EFAULT;
26080 		break;
26081 	case CDROMSDRVSPEED:
26082 		/* Convert the speed code to KB/sec */
26083 		switch ((uchar_t)data) {
26084 		case CDROM_NORMAL_SPEED:
26085 			current_speed = SD_SPEED_1X;
26086 			break;
26087 		case CDROM_DOUBLE_SPEED:
26088 			current_speed = 2 * SD_SPEED_1X;
26089 			break;
26090 		case CDROM_QUAD_SPEED:
26091 			current_speed = 4 * SD_SPEED_1X;
26092 			break;
26093 		case CDROM_TWELVE_SPEED:
26094 			current_speed = 12 * SD_SPEED_1X;
26095 			break;
26096 		case CDROM_MAXIMUM_SPEED:
26097 			current_speed = 0xffff;
26098 			break;
26099 		default:
26100 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26101 			    "sr_atapi_change_speed: invalid drive speed %d\n",
26102 			    (uchar_t)data);
26103 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26104 			return (EINVAL);
26105 		}
26106 
26107 		/* Check the request against the drive's max speed. */
26108 		if (current_speed != 0xffff) {
26109 			if (current_speed > max_speed) {
26110 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26111 				return (EINVAL);
26112 			}
26113 		}
26114 
26115 		/*
26116 		 * Build and send the SET SPEED command
26117 		 *
26118 		 * Note: The SET SPEED (0xBB) command used in this routine is
26119 		 * obsolete per the SCSI MMC spec but still supported in the
26120 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
26121 		 * therefore the command is still implemented in this routine.
26122 		 */
26123 		bzero(cdb, sizeof (cdb));
26124 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
26125 		cdb[2] = (uchar_t)(current_speed >> 8);
26126 		cdb[3] = (uchar_t)current_speed;
26127 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26128 		com->uscsi_cdb	   = (caddr_t)cdb;
26129 		com->uscsi_cdblen  = CDB_GROUP5;
26130 		com->uscsi_bufaddr = NULL;
26131 		com->uscsi_buflen  = 0;
26132 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
26133 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
26134 		break;
26135 	default:
26136 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26137 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
26138 		rval = EINVAL;
26139 	}
26140 
26141 	if (sense) {
26142 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26143 	}
26144 	if (com) {
26145 		kmem_free(com, sizeof (*com));
26146 	}
26147 	return (rval);
26148 }
26149 
26150 
26151 /*
26152  *    Function: sr_pause_resume()
26153  *
26154  * Description: This routine is the driver entry point for handling CD-ROM
26155  *		pause/resume ioctl requests. This only affects the audio play
26156  *		operation.
26157  *
26158  *   Arguments: dev - the device 'dev_t'
26159  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
26160  *		      for setting the resume bit of the cdb.
26161  *
26162  * Return Code: the code returned by sd_send_scsi_cmd()
26163  *		EINVAL if invalid mode specified
26164  *
26165  */
26166 
26167 static int
26168 sr_pause_resume(dev_t dev, int cmd)
26169 {
26170 	struct sd_lun		*un;
26171 	struct uscsi_cmd	*com;
26172 	char			cdb[CDB_GROUP1];
26173 	int			rval;
26174 
26175 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26176 		return (ENXIO);
26177 	}
26178 
26179 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26180 	bzero(cdb, CDB_GROUP1);
26181 	cdb[0] = SCMD_PAUSE_RESUME;
26182 	switch (cmd) {
26183 	case CDROMRESUME:
26184 		cdb[8] = 1;
26185 		break;
26186 	case CDROMPAUSE:
26187 		cdb[8] = 0;
26188 		break;
26189 	default:
26190 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
26191 		    " Command '%x' Not Supported\n", cmd);
26192 		rval = EINVAL;
26193 		goto done;
26194 	}
26195 
26196 	com->uscsi_cdb    = cdb;
26197 	com->uscsi_cdblen = CDB_GROUP1;
26198 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
26199 
26200 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26201 	    SD_PATH_STANDARD);
26202 
26203 done:
26204 	kmem_free(com, sizeof (*com));
26205 	return (rval);
26206 }
26207 
26208 
26209 /*
26210  *    Function: sr_play_msf()
26211  *
26212  * Description: This routine is the driver entry point for handling CD-ROM
26213  *		ioctl requests to output the audio signals at the specified
26214  *		starting address and continue the audio play until the specified
26215  *		ending address (CDROMPLAYMSF) The address is in Minute Second
26216  *		Frame (MSF) format.
26217  *
26218  *   Arguments: dev	- the device 'dev_t'
26219  *		data	- pointer to user provided audio msf structure,
26220  *		          specifying start/end addresses.
26221  *		flag	- this argument is a pass through to ddi_copyxxx()
26222  *		          directly from the mode argument of ioctl().
26223  *
26224  * Return Code: the code returned by sd_send_scsi_cmd()
26225  *		EFAULT if ddi_copyxxx() fails
26226  *		ENXIO if fail ddi_get_soft_state
26227  *		EINVAL if data pointer is NULL
26228  */
26229 
26230 static int
26231 sr_play_msf(dev_t dev, caddr_t data, int flag)
26232 {
26233 	struct sd_lun		*un;
26234 	struct uscsi_cmd	*com;
26235 	struct cdrom_msf	msf_struct;
26236 	struct cdrom_msf	*msf = &msf_struct;
26237 	char			cdb[CDB_GROUP1];
26238 	int			rval;
26239 
26240 	if (data == NULL) {
26241 		return (EINVAL);
26242 	}
26243 
26244 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26245 		return (ENXIO);
26246 	}
26247 
26248 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
26249 		return (EFAULT);
26250 	}
26251 
26252 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26253 	bzero(cdb, CDB_GROUP1);
26254 	cdb[0] = SCMD_PLAYAUDIO_MSF;
26255 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
26256 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
26257 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
26258 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
26259 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
26260 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
26261 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
26262 	} else {
26263 		cdb[3] = msf->cdmsf_min0;
26264 		cdb[4] = msf->cdmsf_sec0;
26265 		cdb[5] = msf->cdmsf_frame0;
26266 		cdb[6] = msf->cdmsf_min1;
26267 		cdb[7] = msf->cdmsf_sec1;
26268 		cdb[8] = msf->cdmsf_frame1;
26269 	}
26270 	com->uscsi_cdb    = cdb;
26271 	com->uscsi_cdblen = CDB_GROUP1;
26272 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
26273 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26274 	    SD_PATH_STANDARD);
26275 	kmem_free(com, sizeof (*com));
26276 	return (rval);
26277 }
26278 
26279 
26280 /*
26281  *    Function: sr_play_trkind()
26282  *
26283  * Description: This routine is the driver entry point for handling CD-ROM
26284  *		ioctl requests to output the audio signals at the specified
26285  *		starting address and continue the audio play until the specified
26286  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
26287  *		format.
26288  *
26289  *   Arguments: dev	- the device 'dev_t'
26290  *		data	- pointer to user provided audio track/index structure,
26291  *		          specifying start/end addresses.
26292  *		flag	- this argument is a pass through to ddi_copyxxx()
26293  *		          directly from the mode argument of ioctl().
26294  *
26295  * Return Code: the code returned by sd_send_scsi_cmd()
26296  *		EFAULT if ddi_copyxxx() fails
26297  *		ENXIO if fail ddi_get_soft_state
26298  *		EINVAL if data pointer is NULL
26299  */
26300 
26301 static int
26302 sr_play_trkind(dev_t dev, caddr_t data, int flag)
26303 {
26304 	struct cdrom_ti		ti_struct;
26305 	struct cdrom_ti		*ti = &ti_struct;
26306 	struct uscsi_cmd	*com = NULL;
26307 	char			cdb[CDB_GROUP1];
26308 	int			rval;
26309 
26310 	if (data == NULL) {
26311 		return (EINVAL);
26312 	}
26313 
26314 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
26315 		return (EFAULT);
26316 	}
26317 
26318 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26319 	bzero(cdb, CDB_GROUP1);
26320 	cdb[0] = SCMD_PLAYAUDIO_TI;
26321 	cdb[4] = ti->cdti_trk0;
26322 	cdb[5] = ti->cdti_ind0;
26323 	cdb[7] = ti->cdti_trk1;
26324 	cdb[8] = ti->cdti_ind1;
26325 	com->uscsi_cdb    = cdb;
26326 	com->uscsi_cdblen = CDB_GROUP1;
26327 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
26328 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26329 	    SD_PATH_STANDARD);
26330 	kmem_free(com, sizeof (*com));
26331 	return (rval);
26332 }
26333 
26334 
26335 /*
26336  *    Function: sr_read_all_subcodes()
26337  *
26338  * Description: This routine is the driver entry point for handling CD-ROM
26339  *		ioctl requests to return raw subcode data while the target is
26340  *		playing audio (CDROMSUBCODE).
26341  *
26342  *   Arguments: dev	- the device 'dev_t'
26343  *		data	- pointer to user provided cdrom subcode structure,
26344  *		          specifying the transfer length and address.
26345  *		flag	- this argument is a pass through to ddi_copyxxx()
26346  *		          directly from the mode argument of ioctl().
26347  *
26348  * Return Code: the code returned by sd_send_scsi_cmd()
26349  *		EFAULT if ddi_copyxxx() fails
26350  *		ENXIO if fail ddi_get_soft_state
26351  *		EINVAL if data pointer is NULL
26352  */
26353 
26354 static int
26355 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
26356 {
26357 	struct sd_lun		*un = NULL;
26358 	struct uscsi_cmd	*com = NULL;
26359 	struct cdrom_subcode	*subcode = NULL;
26360 	int			rval;
26361 	size_t			buflen;
26362 	char			cdb[CDB_GROUP5];
26363 
26364 #ifdef _MULTI_DATAMODEL
26365 	/* To support ILP32 applications in an LP64 world */
26366 	struct cdrom_subcode32		cdrom_subcode32;
26367 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
26368 #endif
26369 	if (data == NULL) {
26370 		return (EINVAL);
26371 	}
26372 
26373 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26374 		return (ENXIO);
26375 	}
26376 
26377 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
26378 
26379 #ifdef _MULTI_DATAMODEL
26380 	switch (ddi_model_convert_from(flag & FMODELS)) {
26381 	case DDI_MODEL_ILP32:
26382 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
26383 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26384 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
26385 			kmem_free(subcode, sizeof (struct cdrom_subcode));
26386 			return (EFAULT);
26387 		}
26388 		/* Convert the ILP32 uscsi data from the application to LP64 */
26389 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
26390 		break;
26391 	case DDI_MODEL_NONE:
26392 		if (ddi_copyin(data, subcode,
26393 		    sizeof (struct cdrom_subcode), flag)) {
26394 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26395 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
26396 			kmem_free(subcode, sizeof (struct cdrom_subcode));
26397 			return (EFAULT);
26398 		}
26399 		break;
26400 	}
26401 #else /* ! _MULTI_DATAMODEL */
26402 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
26403 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26404 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
26405 		kmem_free(subcode, sizeof (struct cdrom_subcode));
26406 		return (EFAULT);
26407 	}
26408 #endif /* _MULTI_DATAMODEL */
26409 
26410 	/*
26411 	 * Since MMC-2 expects max 3 bytes for length, check if the
26412 	 * length input is greater than 3 bytes
26413 	 */
26414 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
26415 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26416 		    "sr_read_all_subcodes: "
26417 		    "cdrom transfer length too large: %d (limit %d)\n",
26418 		    subcode->cdsc_length, 0xFFFFFF);
26419 		kmem_free(subcode, sizeof (struct cdrom_subcode));
26420 		return (EINVAL);
26421 	}
26422 
26423 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
26424 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26425 	bzero(cdb, CDB_GROUP5);
26426 
26427 	if (un->un_f_mmc_cap == TRUE) {
26428 		cdb[0] = (char)SCMD_READ_CD;
26429 		cdb[2] = (char)0xff;
26430 		cdb[3] = (char)0xff;
26431 		cdb[4] = (char)0xff;
26432 		cdb[5] = (char)0xff;
26433 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
26434 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
26435 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
26436 		cdb[10] = 1;
26437 	} else {
26438 		/*
26439 		 * Note: A vendor specific command (0xDF) is being used her to
26440 		 * request a read of all subcodes.
26441 		 */
26442 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
26443 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
26444 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
26445 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
26446 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
26447 	}
26448 	com->uscsi_cdb	   = cdb;
26449 	com->uscsi_cdblen  = CDB_GROUP5;
26450 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
26451 	com->uscsi_buflen  = buflen;
26452 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26453 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
26454 	    SD_PATH_STANDARD);
26455 	kmem_free(subcode, sizeof (struct cdrom_subcode));
26456 	kmem_free(com, sizeof (*com));
26457 	return (rval);
26458 }
26459 
26460 
26461 /*
26462  *    Function: sr_read_subchannel()
26463  *
26464  * Description: This routine is the driver entry point for handling CD-ROM
26465  *		ioctl requests to return the Q sub-channel data of the CD
26466  *		current position block. (CDROMSUBCHNL) The data includes the
26467  *		track number, index number, absolute CD-ROM address (LBA or MSF
26468  *		format per the user) , track relative CD-ROM address (LBA or MSF
26469  *		format per the user), control data and audio status.
26470  *
26471  *   Arguments: dev	- the device 'dev_t'
26472  *		data	- pointer to user provided cdrom sub-channel structure
26473  *		flag	- this argument is a pass through to ddi_copyxxx()
26474  *		          directly from the mode argument of ioctl().
26475  *
26476  * Return Code: the code returned by sd_send_scsi_cmd()
26477  *		EFAULT if ddi_copyxxx() fails
26478  *		ENXIO if fail ddi_get_soft_state
26479  *		EINVAL if data pointer is NULL
26480  */
26481 
26482 static int
26483 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
26484 {
26485 	struct sd_lun		*un;
26486 	struct uscsi_cmd	*com;
26487 	struct cdrom_subchnl	subchanel;
26488 	struct cdrom_subchnl	*subchnl = &subchanel;
26489 	char			cdb[CDB_GROUP1];
26490 	caddr_t			buffer;
26491 	int			rval;
26492 
26493 	if (data == NULL) {
26494 		return (EINVAL);
26495 	}
26496 
26497 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26498 	    (un->un_state == SD_STATE_OFFLINE)) {
26499 		return (ENXIO);
26500 	}
26501 
26502 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
26503 		return (EFAULT);
26504 	}
26505 
26506 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
26507 	bzero(cdb, CDB_GROUP1);
26508 	cdb[0] = SCMD_READ_SUBCHANNEL;
26509 	/* Set the MSF bit based on the user requested address format */
26510 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
26511 	/*
26512 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
26513 	 * returned
26514 	 */
26515 	cdb[2] = 0x40;
26516 	/*
26517 	 * Set byte 3 to specify the return data format. A value of 0x01
26518 	 * indicates that the CD-ROM current position should be returned.
26519 	 */
26520 	cdb[3] = 0x01;
26521 	cdb[8] = 0x10;
26522 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26523 	com->uscsi_cdb	   = cdb;
26524 	com->uscsi_cdblen  = CDB_GROUP1;
26525 	com->uscsi_bufaddr = buffer;
26526 	com->uscsi_buflen  = 16;
26527 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26528 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26529 	    SD_PATH_STANDARD);
26530 	if (rval != 0) {
26531 		kmem_free(buffer, 16);
26532 		kmem_free(com, sizeof (*com));
26533 		return (rval);
26534 	}
26535 
26536 	/* Process the returned Q sub-channel data */
26537 	subchnl->cdsc_audiostatus = buffer[1];
26538 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
26539 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
26540 	subchnl->cdsc_trk	= buffer[6];
26541 	subchnl->cdsc_ind	= buffer[7];
26542 	if (subchnl->cdsc_format & CDROM_LBA) {
26543 		subchnl->cdsc_absaddr.lba =
26544 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26545 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26546 		subchnl->cdsc_reladdr.lba =
26547 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
26548 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
26549 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
26550 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
26551 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
26552 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
26553 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
26554 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
26555 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
26556 	} else {
26557 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
26558 		subchnl->cdsc_absaddr.msf.second = buffer[10];
26559 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
26560 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
26561 		subchnl->cdsc_reladdr.msf.second = buffer[14];
26562 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
26563 	}
26564 	kmem_free(buffer, 16);
26565 	kmem_free(com, sizeof (*com));
26566 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
26567 	    != 0) {
26568 		return (EFAULT);
26569 	}
26570 	return (rval);
26571 }
26572 
26573 
26574 /*
26575  *    Function: sr_read_tocentry()
26576  *
26577  * Description: This routine is the driver entry point for handling CD-ROM
26578  *		ioctl requests to read from the Table of Contents (TOC)
26579  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
26580  *		fields, the starting address (LBA or MSF format per the user)
26581  *		and the data mode if the user specified track is a data track.
26582  *
26583  *		Note: The READ HEADER (0x44) command used in this routine is
26584  *		obsolete per the SCSI MMC spec but still supported in the
26585  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
26586  *		therefore the command is still implemented in this routine.
26587  *
26588  *   Arguments: dev	- the device 'dev_t'
26589  *		data	- pointer to user provided toc entry structure,
26590  *			  specifying the track # and the address format
26591  *			  (LBA or MSF).
26592  *		flag	- this argument is a pass through to ddi_copyxxx()
26593  *		          directly from the mode argument of ioctl().
26594  *
26595  * Return Code: the code returned by sd_send_scsi_cmd()
26596  *		EFAULT if ddi_copyxxx() fails
26597  *		ENXIO if fail ddi_get_soft_state
26598  *		EINVAL if data pointer is NULL
26599  */
26600 
26601 static int
26602 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
26603 {
26604 	struct sd_lun		*un = NULL;
26605 	struct uscsi_cmd	*com;
26606 	struct cdrom_tocentry	toc_entry;
26607 	struct cdrom_tocentry	*entry = &toc_entry;
26608 	caddr_t			buffer;
26609 	int			rval;
26610 	char			cdb[CDB_GROUP1];
26611 
26612 	if (data == NULL) {
26613 		return (EINVAL);
26614 	}
26615 
26616 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26617 	    (un->un_state == SD_STATE_OFFLINE)) {
26618 		return (ENXIO);
26619 	}
26620 
26621 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
26622 		return (EFAULT);
26623 	}
26624 
26625 	/* Validate the requested track and address format */
26626 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
26627 		return (EINVAL);
26628 	}
26629 
26630 	if (entry->cdte_track == 0) {
26631 		return (EINVAL);
26632 	}
26633 
26634 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
26635 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26636 	bzero(cdb, CDB_GROUP1);
26637 
26638 	cdb[0] = SCMD_READ_TOC;
26639 	/* Set the MSF bit based on the user requested address format  */
26640 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
26641 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
26642 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
26643 	} else {
26644 		cdb[6] = entry->cdte_track;
26645 	}
26646 
26647 	/*
26648 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
26649 	 * (4 byte TOC response header + 8 byte track descriptor)
26650 	 */
26651 	cdb[8] = 12;
26652 	com->uscsi_cdb	   = cdb;
26653 	com->uscsi_cdblen  = CDB_GROUP1;
26654 	com->uscsi_bufaddr = buffer;
26655 	com->uscsi_buflen  = 0x0C;
26656 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
26657 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26658 	    SD_PATH_STANDARD);
26659 	if (rval != 0) {
26660 		kmem_free(buffer, 12);
26661 		kmem_free(com, sizeof (*com));
26662 		return (rval);
26663 	}
26664 
26665 	/* Process the toc entry */
26666 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
26667 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
26668 	if (entry->cdte_format & CDROM_LBA) {
26669 		entry->cdte_addr.lba =
26670 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26671 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26672 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
26673 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
26674 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
26675 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
26676 		/*
26677 		 * Send a READ TOC command using the LBA address format to get
26678 		 * the LBA for the track requested so it can be used in the
26679 		 * READ HEADER request
26680 		 *
26681 		 * Note: The MSF bit of the READ HEADER command specifies the
26682 		 * output format. The block address specified in that command
26683 		 * must be in LBA format.
26684 		 */
26685 		cdb[1] = 0;
26686 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26687 		    SD_PATH_STANDARD);
26688 		if (rval != 0) {
26689 			kmem_free(buffer, 12);
26690 			kmem_free(com, sizeof (*com));
26691 			return (rval);
26692 		}
26693 	} else {
26694 		entry->cdte_addr.msf.minute	= buffer[9];
26695 		entry->cdte_addr.msf.second	= buffer[10];
26696 		entry->cdte_addr.msf.frame	= buffer[11];
26697 		/*
26698 		 * Send a READ TOC command using the LBA address format to get
26699 		 * the LBA for the track requested so it can be used in the
26700 		 * READ HEADER request
26701 		 *
26702 		 * Note: The MSF bit of the READ HEADER command specifies the
26703 		 * output format. The block address specified in that command
26704 		 * must be in LBA format.
26705 		 */
26706 		cdb[1] = 0;
26707 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26708 		    SD_PATH_STANDARD);
26709 		if (rval != 0) {
26710 			kmem_free(buffer, 12);
26711 			kmem_free(com, sizeof (*com));
26712 			return (rval);
26713 		}
26714 	}
26715 
26716 	/*
26717 	 * Build and send the READ HEADER command to determine the data mode of
26718 	 * the user specified track.
26719 	 */
26720 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
26721 	    (entry->cdte_track != CDROM_LEADOUT)) {
26722 		bzero(cdb, CDB_GROUP1);
26723 		cdb[0] = SCMD_READ_HEADER;
26724 		cdb[2] = buffer[8];
26725 		cdb[3] = buffer[9];
26726 		cdb[4] = buffer[10];
26727 		cdb[5] = buffer[11];
26728 		cdb[8] = 0x08;
26729 		com->uscsi_buflen = 0x08;
26730 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26731 		    SD_PATH_STANDARD);
26732 		if (rval == 0) {
26733 			entry->cdte_datamode = buffer[0];
26734 		} else {
26735 			/*
26736 			 * READ HEADER command failed, since this is
26737 			 * obsoleted in one spec, its better to return
26738 			 * -1 for an invlid track so that we can still
26739 			 * receive the rest of the TOC data.
26740 			 */
26741 			entry->cdte_datamode = (uchar_t)-1;
26742 		}
26743 	} else {
26744 		entry->cdte_datamode = (uchar_t)-1;
26745 	}
26746 
26747 	kmem_free(buffer, 12);
26748 	kmem_free(com, sizeof (*com));
26749 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
26750 		return (EFAULT);
26751 
26752 	return (rval);
26753 }
26754 
26755 
26756 /*
26757  *    Function: sr_read_tochdr()
26758  *
26759  * Description: This routine is the driver entry point for handling CD-ROM
26760  * 		ioctl requests to read the Table of Contents (TOC) header
26761  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
26762  *		and ending track numbers
26763  *
26764  *   Arguments: dev	- the device 'dev_t'
26765  *		data	- pointer to user provided toc header structure,
26766  *			  specifying the starting and ending track numbers.
26767  *		flag	- this argument is a pass through to ddi_copyxxx()
26768  *			  directly from the mode argument of ioctl().
26769  *
26770  * Return Code: the code returned by sd_send_scsi_cmd()
26771  *		EFAULT if ddi_copyxxx() fails
26772  *		ENXIO if fail ddi_get_soft_state
26773  *		EINVAL if data pointer is NULL
26774  */
26775 
26776 static int
26777 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
26778 {
26779 	struct sd_lun		*un;
26780 	struct uscsi_cmd	*com;
26781 	struct cdrom_tochdr	toc_header;
26782 	struct cdrom_tochdr	*hdr = &toc_header;
26783 	char			cdb[CDB_GROUP1];
26784 	int			rval;
26785 	caddr_t			buffer;
26786 
26787 	if (data == NULL) {
26788 		return (EINVAL);
26789 	}
26790 
26791 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26792 	    (un->un_state == SD_STATE_OFFLINE)) {
26793 		return (ENXIO);
26794 	}
26795 
26796 	buffer = kmem_zalloc(4, KM_SLEEP);
26797 	bzero(cdb, CDB_GROUP1);
26798 	cdb[0] = SCMD_READ_TOC;
26799 	/*
26800 	 * Specifying a track number of 0x00 in the READ TOC command indicates
26801 	 * that the TOC header should be returned
26802 	 */
26803 	cdb[6] = 0x00;
26804 	/*
26805 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
26806 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
26807 	 */
26808 	cdb[8] = 0x04;
26809 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26810 	com->uscsi_cdb	   = cdb;
26811 	com->uscsi_cdblen  = CDB_GROUP1;
26812 	com->uscsi_bufaddr = buffer;
26813 	com->uscsi_buflen  = 0x04;
26814 	com->uscsi_timeout = 300;
26815 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26816 
26817 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26818 	    SD_PATH_STANDARD);
26819 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
26820 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
26821 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
26822 	} else {
26823 		hdr->cdth_trk0 = buffer[2];
26824 		hdr->cdth_trk1 = buffer[3];
26825 	}
26826 	kmem_free(buffer, 4);
26827 	kmem_free(com, sizeof (*com));
26828 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
26829 		return (EFAULT);
26830 	}
26831 	return (rval);
26832 }
26833 
26834 
26835 /*
26836  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
26837  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
26838  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
26839  * digital audio and extended architecture digital audio. These modes are
26840  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
26841  * MMC specs.
26842  *
26843  * In addition to support for the various data formats these routines also
26844  * include support for devices that implement only the direct access READ
26845  * commands (0x08, 0x28), devices that implement the READ_CD commands
26846  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
26847  * READ CDXA commands (0xD8, 0xDB)
26848  */
26849 
26850 /*
26851  *    Function: sr_read_mode1()
26852  *
26853  * Description: This routine is the driver entry point for handling CD-ROM
26854  *		ioctl read mode1 requests (CDROMREADMODE1).
26855  *
26856  *   Arguments: dev	- the device 'dev_t'
26857  *		data	- pointer to user provided cd read structure specifying
26858  *			  the lba buffer address and length.
26859  *		flag	- this argument is a pass through to ddi_copyxxx()
26860  *			  directly from the mode argument of ioctl().
26861  *
26862  * Return Code: the code returned by sd_send_scsi_cmd()
26863  *		EFAULT if ddi_copyxxx() fails
26864  *		ENXIO if fail ddi_get_soft_state
26865  *		EINVAL if data pointer is NULL
26866  */
26867 
26868 static int
26869 sr_read_mode1(dev_t dev, caddr_t data, int flag)
26870 {
26871 	struct sd_lun		*un;
26872 	struct cdrom_read	mode1_struct;
26873 	struct cdrom_read	*mode1 = &mode1_struct;
26874 	int			rval;
26875 	sd_ssc_t		*ssc;
26876 
26877 #ifdef _MULTI_DATAMODEL
26878 	/* To support ILP32 applications in an LP64 world */
26879 	struct cdrom_read32	cdrom_read32;
26880 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
26881 #endif /* _MULTI_DATAMODEL */
26882 
26883 	if (data == NULL) {
26884 		return (EINVAL);
26885 	}
26886 
26887 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26888 	    (un->un_state == SD_STATE_OFFLINE)) {
26889 		return (ENXIO);
26890 	}
26891 
26892 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
26893 	    "sd_read_mode1: entry: un:0x%p\n", un);
26894 
26895 #ifdef _MULTI_DATAMODEL
26896 	switch (ddi_model_convert_from(flag & FMODELS)) {
26897 	case DDI_MODEL_ILP32:
26898 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
26899 			return (EFAULT);
26900 		}
26901 		/* Convert the ILP32 uscsi data from the application to LP64 */
26902 		cdrom_read32tocdrom_read(cdrd32, mode1);
26903 		break;
26904 	case DDI_MODEL_NONE:
26905 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
26906 			return (EFAULT);
26907 		}
26908 	}
26909 #else /* ! _MULTI_DATAMODEL */
26910 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
26911 		return (EFAULT);
26912 	}
26913 #endif /* _MULTI_DATAMODEL */
26914 
26915 	ssc = sd_ssc_init(un);
26916 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
26917 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
26918 	sd_ssc_fini(ssc);
26919 
26920 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
26921 	    "sd_read_mode1: exit: un:0x%p\n", un);
26922 
26923 	return (rval);
26924 }
26925 
26926 
26927 /*
26928  *    Function: sr_read_cd_mode2()
26929  *
26930  * Description: This routine is the driver entry point for handling CD-ROM
26931  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
26932  *		support the READ CD (0xBE) command or the 1st generation
26933  *		READ CD (0xD4) command.
26934  *
26935  *   Arguments: dev	- the device 'dev_t'
26936  *		data	- pointer to user provided cd read structure specifying
26937  *			  the lba buffer address and length.
26938  *		flag	- this argument is a pass through to ddi_copyxxx()
26939  *			  directly from the mode argument of ioctl().
26940  *
26941  * Return Code: the code returned by sd_send_scsi_cmd()
26942  *		EFAULT if ddi_copyxxx() fails
26943  *		ENXIO if fail ddi_get_soft_state
26944  *		EINVAL if data pointer is NULL
26945  */
26946 
26947 static int
26948 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
26949 {
26950 	struct sd_lun		*un;
26951 	struct uscsi_cmd	*com;
26952 	struct cdrom_read	mode2_struct;
26953 	struct cdrom_read	*mode2 = &mode2_struct;
26954 	uchar_t			cdb[CDB_GROUP5];
26955 	int			nblocks;
26956 	int			rval;
26957 #ifdef _MULTI_DATAMODEL
26958 	/*  To support ILP32 applications in an LP64 world */
26959 	struct cdrom_read32	cdrom_read32;
26960 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
26961 #endif /* _MULTI_DATAMODEL */
26962 
26963 	if (data == NULL) {
26964 		return (EINVAL);
26965 	}
26966 
26967 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26968 	    (un->un_state == SD_STATE_OFFLINE)) {
26969 		return (ENXIO);
26970 	}
26971 
26972 #ifdef _MULTI_DATAMODEL
26973 	switch (ddi_model_convert_from(flag & FMODELS)) {
26974 	case DDI_MODEL_ILP32:
26975 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
26976 			return (EFAULT);
26977 		}
26978 		/* Convert the ILP32 uscsi data from the application to LP64 */
26979 		cdrom_read32tocdrom_read(cdrd32, mode2);
26980 		break;
26981 	case DDI_MODEL_NONE:
26982 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
26983 			return (EFAULT);
26984 		}
26985 		break;
26986 	}
26987 
26988 #else /* ! _MULTI_DATAMODEL */
26989 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
26990 		return (EFAULT);
26991 	}
26992 #endif /* _MULTI_DATAMODEL */
26993 
26994 	bzero(cdb, sizeof (cdb));
26995 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
26996 		/* Read command supported by 1st generation atapi drives */
26997 		cdb[0] = SCMD_READ_CDD4;
26998 	} else {
26999 		/* Universal CD Access Command */
27000 		cdb[0] = SCMD_READ_CD;
27001 	}
27002 
27003 	/*
27004 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
27005 	 */
27006 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
27007 
27008 	/* set the start address */
27009 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
27010 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
27011 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
27012 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
27013 
27014 	/* set the transfer length */
27015 	nblocks = mode2->cdread_buflen / 2336;
27016 	cdb[6] = (uchar_t)(nblocks >> 16);
27017 	cdb[7] = (uchar_t)(nblocks >> 8);
27018 	cdb[8] = (uchar_t)nblocks;
27019 
27020 	/* set the filter bits */
27021 	cdb[9] = CDROM_READ_CD_USERDATA;
27022 
27023 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27024 	com->uscsi_cdb = (caddr_t)cdb;
27025 	com->uscsi_cdblen = sizeof (cdb);
27026 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
27027 	com->uscsi_buflen = mode2->cdread_buflen;
27028 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27029 
27030 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27031 	    SD_PATH_STANDARD);
27032 	kmem_free(com, sizeof (*com));
27033 	return (rval);
27034 }
27035 
27036 
27037 /*
27038  *    Function: sr_read_mode2()
27039  *
27040  * Description: This routine is the driver entry point for handling CD-ROM
27041  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
27042  *		do not support the READ CD (0xBE) command.
27043  *
27044  *   Arguments: dev	- the device 'dev_t'
27045  *		data	- pointer to user provided cd read structure specifying
27046  *			  the lba buffer address and length.
27047  *		flag	- this argument is a pass through to ddi_copyxxx()
27048  *			  directly from the mode argument of ioctl().
27049  *
27050  * Return Code: the code returned by sd_send_scsi_cmd()
27051  *		EFAULT if ddi_copyxxx() fails
27052  *		ENXIO if fail ddi_get_soft_state
27053  *		EINVAL if data pointer is NULL
27054  *		EIO if fail to reset block size
27055  *		EAGAIN if commands are in progress in the driver
27056  */
27057 
27058 static int
27059 sr_read_mode2(dev_t dev, caddr_t data, int flag)
27060 {
27061 	struct sd_lun		*un;
27062 	struct cdrom_read	mode2_struct;
27063 	struct cdrom_read	*mode2 = &mode2_struct;
27064 	int			rval;
27065 	uint32_t		restore_blksize;
27066 	struct uscsi_cmd	*com;
27067 	uchar_t			cdb[CDB_GROUP0];
27068 	int			nblocks;
27069 
27070 #ifdef _MULTI_DATAMODEL
27071 	/* To support ILP32 applications in an LP64 world */
27072 	struct cdrom_read32	cdrom_read32;
27073 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
27074 #endif /* _MULTI_DATAMODEL */
27075 
27076 	if (data == NULL) {
27077 		return (EINVAL);
27078 	}
27079 
27080 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27081 	    (un->un_state == SD_STATE_OFFLINE)) {
27082 		return (ENXIO);
27083 	}
27084 
27085 	/*
27086 	 * Because this routine will update the device and driver block size
27087 	 * being used we want to make sure there are no commands in progress.
27088 	 * If commands are in progress the user will have to try again.
27089 	 *
27090 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
27091 	 * in sdioctl to protect commands from sdioctl through to the top of
27092 	 * sd_uscsi_strategy. See sdioctl for details.
27093 	 */
27094 	mutex_enter(SD_MUTEX(un));
27095 	if (un->un_ncmds_in_driver != 1) {
27096 		mutex_exit(SD_MUTEX(un));
27097 		return (EAGAIN);
27098 	}
27099 	mutex_exit(SD_MUTEX(un));
27100 
27101 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27102 	    "sd_read_mode2: entry: un:0x%p\n", un);
27103 
27104 #ifdef _MULTI_DATAMODEL
27105 	switch (ddi_model_convert_from(flag & FMODELS)) {
27106 	case DDI_MODEL_ILP32:
27107 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
27108 			return (EFAULT);
27109 		}
27110 		/* Convert the ILP32 uscsi data from the application to LP64 */
27111 		cdrom_read32tocdrom_read(cdrd32, mode2);
27112 		break;
27113 	case DDI_MODEL_NONE:
27114 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
27115 			return (EFAULT);
27116 		}
27117 		break;
27118 	}
27119 #else /* ! _MULTI_DATAMODEL */
27120 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
27121 		return (EFAULT);
27122 	}
27123 #endif /* _MULTI_DATAMODEL */
27124 
27125 	/* Store the current target block size for restoration later */
27126 	restore_blksize = un->un_tgt_blocksize;
27127 
27128 	/* Change the device and soft state target block size to 2336 */
27129 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
27130 		rval = EIO;
27131 		goto done;
27132 	}
27133 
27134 
27135 	bzero(cdb, sizeof (cdb));
27136 
27137 	/* set READ operation */
27138 	cdb[0] = SCMD_READ;
27139 
27140 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
27141 	mode2->cdread_lba >>= 2;
27142 
27143 	/* set the start address */
27144 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
27145 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
27146 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
27147 
27148 	/* set the transfer length */
27149 	nblocks = mode2->cdread_buflen / 2336;
27150 	cdb[4] = (uchar_t)nblocks & 0xFF;
27151 
27152 	/* build command */
27153 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27154 	com->uscsi_cdb = (caddr_t)cdb;
27155 	com->uscsi_cdblen = sizeof (cdb);
27156 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
27157 	com->uscsi_buflen = mode2->cdread_buflen;
27158 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27159 
27160 	/*
27161 	 * Issue SCSI command with user space address for read buffer.
27162 	 *
27163 	 * This sends the command through main channel in the driver.
27164 	 *
27165 	 * Since this is accessed via an IOCTL call, we go through the
27166 	 * standard path, so that if the device was powered down, then
27167 	 * it would be 'awakened' to handle the command.
27168 	 */
27169 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27170 	    SD_PATH_STANDARD);
27171 
27172 	kmem_free(com, sizeof (*com));
27173 
27174 	/* Restore the device and soft state target block size */
27175 	if (sr_sector_mode(dev, restore_blksize) != 0) {
27176 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27177 		    "can't do switch back to mode 1\n");
27178 		/*
27179 		 * If sd_send_scsi_READ succeeded we still need to report
27180 		 * an error because we failed to reset the block size
27181 		 */
27182 		if (rval == 0) {
27183 			rval = EIO;
27184 		}
27185 	}
27186 
27187 done:
27188 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27189 	    "sd_read_mode2: exit: un:0x%p\n", un);
27190 
27191 	return (rval);
27192 }
27193 
27194 
27195 /*
27196  *    Function: sr_sector_mode()
27197  *
27198  * Description: This utility function is used by sr_read_mode2 to set the target
27199  *		block size based on the user specified size. This is a legacy
27200  *		implementation based upon a vendor specific mode page
27201  *
27202  *   Arguments: dev	- the device 'dev_t'
27203  *		data	- flag indicating if block size is being set to 2336 or
27204  *			  512.
27205  *
27206  * Return Code: the code returned by sd_send_scsi_cmd()
27207  *		EFAULT if ddi_copyxxx() fails
27208  *		ENXIO if fail ddi_get_soft_state
27209  *		EINVAL if data pointer is NULL
27210  */
27211 
27212 static int
27213 sr_sector_mode(dev_t dev, uint32_t blksize)
27214 {
27215 	struct sd_lun	*un;
27216 	uchar_t		*sense;
27217 	uchar_t		*select;
27218 	int		rval;
27219 	sd_ssc_t	*ssc;
27220 
27221 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27222 	    (un->un_state == SD_STATE_OFFLINE)) {
27223 		return (ENXIO);
27224 	}
27225 
27226 	sense = kmem_zalloc(20, KM_SLEEP);
27227 
27228 	/* Note: This is a vendor specific mode page (0x81) */
27229 	ssc = sd_ssc_init(un);
27230 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
27231 	    SD_PATH_STANDARD);
27232 	sd_ssc_fini(ssc);
27233 	if (rval != 0) {
27234 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
27235 		    "sr_sector_mode: Mode Sense failed\n");
27236 		kmem_free(sense, 20);
27237 		return (rval);
27238 	}
27239 	select = kmem_zalloc(20, KM_SLEEP);
27240 	select[3] = 0x08;
27241 	select[10] = ((blksize >> 8) & 0xff);
27242 	select[11] = (blksize & 0xff);
27243 	select[12] = 0x01;
27244 	select[13] = 0x06;
27245 	select[14] = sense[14];
27246 	select[15] = sense[15];
27247 	if (blksize == SD_MODE2_BLKSIZE) {
27248 		select[14] |= 0x01;
27249 	}
27250 
27251 	ssc = sd_ssc_init(un);
27252 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
27253 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27254 	sd_ssc_fini(ssc);
27255 	if (rval != 0) {
27256 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
27257 		    "sr_sector_mode: Mode Select failed\n");
27258 	} else {
27259 		/*
27260 		 * Only update the softstate block size if we successfully
27261 		 * changed the device block mode.
27262 		 */
27263 		mutex_enter(SD_MUTEX(un));
27264 		sd_update_block_info(un, blksize, 0);
27265 		mutex_exit(SD_MUTEX(un));
27266 	}
27267 	kmem_free(sense, 20);
27268 	kmem_free(select, 20);
27269 	return (rval);
27270 }
27271 
27272 
27273 /*
27274  *    Function: sr_read_cdda()
27275  *
27276  * Description: This routine is the driver entry point for handling CD-ROM
27277  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
27278  *		the target supports CDDA these requests are handled via a vendor
27279  *		specific command (0xD8) If the target does not support CDDA
27280  *		these requests are handled via the READ CD command (0xBE).
27281  *
27282  *   Arguments: dev	- the device 'dev_t'
27283  *		data	- pointer to user provided CD-DA structure specifying
27284  *			  the track starting address, transfer length, and
27285  *			  subcode options.
27286  *		flag	- this argument is a pass through to ddi_copyxxx()
27287  *			  directly from the mode argument of ioctl().
27288  *
27289  * Return Code: the code returned by sd_send_scsi_cmd()
27290  *		EFAULT if ddi_copyxxx() fails
27291  *		ENXIO if fail ddi_get_soft_state
27292  *		EINVAL if invalid arguments are provided
27293  *		ENOTTY
27294  */
27295 
27296 static int
27297 sr_read_cdda(dev_t dev, caddr_t data, int flag)
27298 {
27299 	struct sd_lun			*un;
27300 	struct uscsi_cmd		*com;
27301 	struct cdrom_cdda		*cdda;
27302 	int				rval;
27303 	size_t				buflen;
27304 	char				cdb[CDB_GROUP5];
27305 
27306 #ifdef _MULTI_DATAMODEL
27307 	/* To support ILP32 applications in an LP64 world */
27308 	struct cdrom_cdda32	cdrom_cdda32;
27309 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
27310 #endif /* _MULTI_DATAMODEL */
27311 
27312 	if (data == NULL) {
27313 		return (EINVAL);
27314 	}
27315 
27316 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27317 		return (ENXIO);
27318 	}
27319 
27320 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
27321 
27322 #ifdef _MULTI_DATAMODEL
27323 	switch (ddi_model_convert_from(flag & FMODELS)) {
27324 	case DDI_MODEL_ILP32:
27325 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
27326 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27327 			    "sr_read_cdda: ddi_copyin Failed\n");
27328 			kmem_free(cdda, sizeof (struct cdrom_cdda));
27329 			return (EFAULT);
27330 		}
27331 		/* Convert the ILP32 uscsi data from the application to LP64 */
27332 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
27333 		break;
27334 	case DDI_MODEL_NONE:
27335 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
27336 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27337 			    "sr_read_cdda: ddi_copyin Failed\n");
27338 			kmem_free(cdda, sizeof (struct cdrom_cdda));
27339 			return (EFAULT);
27340 		}
27341 		break;
27342 	}
27343 #else /* ! _MULTI_DATAMODEL */
27344 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
27345 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27346 		    "sr_read_cdda: ddi_copyin Failed\n");
27347 		kmem_free(cdda, sizeof (struct cdrom_cdda));
27348 		return (EFAULT);
27349 	}
27350 #endif /* _MULTI_DATAMODEL */
27351 
27352 	/*
27353 	 * Since MMC-2 expects max 3 bytes for length, check if the
27354 	 * length input is greater than 3 bytes
27355 	 */
27356 	if ((cdda->cdda_length & 0xFF000000) != 0) {
27357 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
27358 		    "cdrom transfer length too large: %d (limit %d)\n",
27359 		    cdda->cdda_length, 0xFFFFFF);
27360 		kmem_free(cdda, sizeof (struct cdrom_cdda));
27361 		return (EINVAL);
27362 	}
27363 
27364 	switch (cdda->cdda_subcode) {
27365 	case CDROM_DA_NO_SUBCODE:
27366 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
27367 		break;
27368 	case CDROM_DA_SUBQ:
27369 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
27370 		break;
27371 	case CDROM_DA_ALL_SUBCODE:
27372 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
27373 		break;
27374 	case CDROM_DA_SUBCODE_ONLY:
27375 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
27376 		break;
27377 	default:
27378 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27379 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
27380 		    cdda->cdda_subcode);
27381 		kmem_free(cdda, sizeof (struct cdrom_cdda));
27382 		return (EINVAL);
27383 	}
27384 
27385 	/* Build and send the command */
27386 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27387 	bzero(cdb, CDB_GROUP5);
27388 
27389 	if (un->un_f_cfg_cdda == TRUE) {
27390 		cdb[0] = (char)SCMD_READ_CD;
27391 		cdb[1] = 0x04;
27392 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
27393 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
27394 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
27395 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
27396 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
27397 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
27398 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
27399 		cdb[9] = 0x10;
27400 		switch (cdda->cdda_subcode) {
27401 		case CDROM_DA_NO_SUBCODE :
27402 			cdb[10] = 0x0;
27403 			break;
27404 		case CDROM_DA_SUBQ :
27405 			cdb[10] = 0x2;
27406 			break;
27407 		case CDROM_DA_ALL_SUBCODE :
27408 			cdb[10] = 0x1;
27409 			break;
27410 		case CDROM_DA_SUBCODE_ONLY :
27411 			/* FALLTHROUGH */
27412 		default :
27413 			kmem_free(cdda, sizeof (struct cdrom_cdda));
27414 			kmem_free(com, sizeof (*com));
27415 			return (ENOTTY);
27416 		}
27417 	} else {
27418 		cdb[0] = (char)SCMD_READ_CDDA;
27419 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
27420 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
27421 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
27422 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
27423 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
27424 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
27425 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
27426 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
27427 		cdb[10] = cdda->cdda_subcode;
27428 	}
27429 
27430 	com->uscsi_cdb = cdb;
27431 	com->uscsi_cdblen = CDB_GROUP5;
27432 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
27433 	com->uscsi_buflen = buflen;
27434 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27435 
27436 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27437 	    SD_PATH_STANDARD);
27438 
27439 	kmem_free(cdda, sizeof (struct cdrom_cdda));
27440 	kmem_free(com, sizeof (*com));
27441 	return (rval);
27442 }
27443 
27444 
27445 /*
27446  *    Function: sr_read_cdxa()
27447  *
27448  * Description: This routine is the driver entry point for handling CD-ROM
27449  *		ioctl requests to return CD-XA (Extended Architecture) data.
27450  *		(CDROMCDXA).
27451  *
27452  *   Arguments: dev	- the device 'dev_t'
27453  *		data	- pointer to user provided CD-XA structure specifying
27454  *			  the data starting address, transfer length, and format
27455  *		flag	- this argument is a pass through to ddi_copyxxx()
27456  *			  directly from the mode argument of ioctl().
27457  *
27458  * Return Code: the code returned by sd_send_scsi_cmd()
27459  *		EFAULT if ddi_copyxxx() fails
27460  *		ENXIO if fail ddi_get_soft_state
27461  *		EINVAL if data pointer is NULL
27462  */
27463 
27464 static int
27465 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
27466 {
27467 	struct sd_lun		*un;
27468 	struct uscsi_cmd	*com;
27469 	struct cdrom_cdxa	*cdxa;
27470 	int			rval;
27471 	size_t			buflen;
27472 	char			cdb[CDB_GROUP5];
27473 	uchar_t			read_flags;
27474 
27475 #ifdef _MULTI_DATAMODEL
27476 	/* To support ILP32 applications in an LP64 world */
27477 	struct cdrom_cdxa32		cdrom_cdxa32;
27478 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
27479 #endif /* _MULTI_DATAMODEL */
27480 
27481 	if (data == NULL) {
27482 		return (EINVAL);
27483 	}
27484 
27485 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27486 		return (ENXIO);
27487 	}
27488 
27489 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
27490 
27491 #ifdef _MULTI_DATAMODEL
27492 	switch (ddi_model_convert_from(flag & FMODELS)) {
27493 	case DDI_MODEL_ILP32:
27494 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
27495 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27496 			return (EFAULT);
27497 		}
27498 		/*
27499 		 * Convert the ILP32 uscsi data from the
27500 		 * application to LP64 for internal use.
27501 		 */
27502 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
27503 		break;
27504 	case DDI_MODEL_NONE:
27505 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
27506 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27507 			return (EFAULT);
27508 		}
27509 		break;
27510 	}
27511 #else /* ! _MULTI_DATAMODEL */
27512 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
27513 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27514 		return (EFAULT);
27515 	}
27516 #endif /* _MULTI_DATAMODEL */
27517 
27518 	/*
27519 	 * Since MMC-2 expects max 3 bytes for length, check if the
27520 	 * length input is greater than 3 bytes
27521 	 */
27522 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
27523 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
27524 		    "cdrom transfer length too large: %d (limit %d)\n",
27525 		    cdxa->cdxa_length, 0xFFFFFF);
27526 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27527 		return (EINVAL);
27528 	}
27529 
27530 	switch (cdxa->cdxa_format) {
27531 	case CDROM_XA_DATA:
27532 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
27533 		read_flags = 0x10;
27534 		break;
27535 	case CDROM_XA_SECTOR_DATA:
27536 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
27537 		read_flags = 0xf8;
27538 		break;
27539 	case CDROM_XA_DATA_W_ERROR:
27540 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
27541 		read_flags = 0xfc;
27542 		break;
27543 	default:
27544 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27545 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
27546 		    cdxa->cdxa_format);
27547 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27548 		return (EINVAL);
27549 	}
27550 
27551 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27552 	bzero(cdb, CDB_GROUP5);
27553 	if (un->un_f_mmc_cap == TRUE) {
27554 		cdb[0] = (char)SCMD_READ_CD;
27555 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
27556 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
27557 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
27558 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
27559 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
27560 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
27561 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
27562 		cdb[9] = (char)read_flags;
27563 	} else {
27564 		/*
27565 		 * Note: A vendor specific command (0xDB) is being used her to
27566 		 * request a read of all subcodes.
27567 		 */
27568 		cdb[0] = (char)SCMD_READ_CDXA;
27569 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
27570 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
27571 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
27572 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
27573 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
27574 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
27575 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
27576 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
27577 		cdb[10] = cdxa->cdxa_format;
27578 	}
27579 	com->uscsi_cdb	   = cdb;
27580 	com->uscsi_cdblen  = CDB_GROUP5;
27581 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
27582 	com->uscsi_buflen  = buflen;
27583 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27584 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27585 	    SD_PATH_STANDARD);
27586 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27587 	kmem_free(com, sizeof (*com));
27588 	return (rval);
27589 }
27590 
27591 
27592 /*
27593  *    Function: sr_eject()
27594  *
27595  * Description: This routine is the driver entry point for handling CD-ROM
27596  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
27597  *
27598  *   Arguments: dev	- the device 'dev_t'
27599  *
27600  * Return Code: the code returned by sd_send_scsi_cmd()
27601  */
27602 
27603 static int
27604 sr_eject(dev_t dev)
27605 {
27606 	struct sd_lun	*un;
27607 	int		rval;
27608 	sd_ssc_t	*ssc;
27609 
27610 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27611 	    (un->un_state == SD_STATE_OFFLINE)) {
27612 		return (ENXIO);
27613 	}
27614 
27615 	/*
27616 	 * To prevent race conditions with the eject
27617 	 * command, keep track of an eject command as
27618 	 * it progresses. If we are already handling
27619 	 * an eject command in the driver for the given
27620 	 * unit and another request to eject is received
27621 	 * immediately return EAGAIN so we don't lose
27622 	 * the command if the current eject command fails.
27623 	 */
27624 	mutex_enter(SD_MUTEX(un));
27625 	if (un->un_f_ejecting == TRUE) {
27626 		mutex_exit(SD_MUTEX(un));
27627 		return (EAGAIN);
27628 	}
27629 	un->un_f_ejecting = TRUE;
27630 	mutex_exit(SD_MUTEX(un));
27631 
27632 	ssc = sd_ssc_init(un);
27633 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
27634 	    SD_PATH_STANDARD);
27635 	sd_ssc_fini(ssc);
27636 
27637 	if (rval != 0) {
27638 		mutex_enter(SD_MUTEX(un));
27639 		un->un_f_ejecting = FALSE;
27640 		mutex_exit(SD_MUTEX(un));
27641 		return (rval);
27642 	}
27643 
27644 	ssc = sd_ssc_init(un);
27645 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_EJECT,
27646 	    SD_PATH_STANDARD);
27647 	sd_ssc_fini(ssc);
27648 
27649 	if (rval == 0) {
27650 		mutex_enter(SD_MUTEX(un));
27651 		sr_ejected(un);
27652 		un->un_mediastate = DKIO_EJECTED;
27653 		un->un_f_ejecting = FALSE;
27654 		cv_broadcast(&un->un_state_cv);
27655 		mutex_exit(SD_MUTEX(un));
27656 	} else {
27657 		mutex_enter(SD_MUTEX(un));
27658 		un->un_f_ejecting = FALSE;
27659 		mutex_exit(SD_MUTEX(un));
27660 	}
27661 	return (rval);
27662 }
27663 
27664 
27665 /*
27666  *    Function: sr_ejected()
27667  *
27668  * Description: This routine updates the soft state structure to invalidate the
27669  *		geometry information after the media has been ejected or a
27670  *		media eject has been detected.
27671  *
27672  *   Arguments: un - driver soft state (unit) structure
27673  */
27674 
27675 static void
27676 sr_ejected(struct sd_lun *un)
27677 {
27678 	struct sd_errstats *stp;
27679 
27680 	ASSERT(un != NULL);
27681 	ASSERT(mutex_owned(SD_MUTEX(un)));
27682 
27683 	un->un_f_blockcount_is_valid	= FALSE;
27684 	un->un_f_tgt_blocksize_is_valid	= FALSE;
27685 	mutex_exit(SD_MUTEX(un));
27686 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
27687 	mutex_enter(SD_MUTEX(un));
27688 
27689 	if (un->un_errstats != NULL) {
27690 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
27691 		stp->sd_capacity.value.ui64 = 0;
27692 	}
27693 }
27694 
27695 
27696 /*
27697  *    Function: sr_check_wp()
27698  *
27699  * Description: This routine checks the write protection of a removable
27700  *      media disk and hotpluggable devices via the write protect bit of
27701  *      the Mode Page Header device specific field. Some devices choke
27702  *      on unsupported mode page. In order to workaround this issue,
27703  *      this routine has been implemented to use 0x3f mode page(request
27704  *      for all pages) for all device types.
27705  *
27706  *   Arguments: dev             - the device 'dev_t'
27707  *
27708  * Return Code: int indicating if the device is write protected (1) or not (0)
27709  *
27710  *     Context: Kernel thread.
27711  *
27712  */
27713 
27714 static int
27715 sr_check_wp(dev_t dev)
27716 {
27717 	struct sd_lun	*un;
27718 	uchar_t		device_specific;
27719 	uchar_t		*sense;
27720 	int		hdrlen;
27721 	int		rval = FALSE;
27722 	int		status;
27723 	sd_ssc_t	*ssc;
27724 
27725 	/*
27726 	 * Note: The return codes for this routine should be reworked to
27727 	 * properly handle the case of a NULL softstate.
27728 	 */
27729 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27730 		return (FALSE);
27731 	}
27732 
27733 	if (un->un_f_cfg_is_atapi == TRUE) {
27734 		/*
27735 		 * The mode page contents are not required; set the allocation
27736 		 * length for the mode page header only
27737 		 */
27738 		hdrlen = MODE_HEADER_LENGTH_GRP2;
27739 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
27740 		ssc = sd_ssc_init(un);
27741 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
27742 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
27743 		sd_ssc_fini(ssc);
27744 		if (status != 0)
27745 			goto err_exit;
27746 		device_specific =
27747 		    ((struct mode_header_grp2 *)sense)->device_specific;
27748 	} else {
27749 		hdrlen = MODE_HEADER_LENGTH;
27750 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
27751 		ssc = sd_ssc_init(un);
27752 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
27753 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
27754 		sd_ssc_fini(ssc);
27755 		if (status != 0)
27756 			goto err_exit;
27757 		device_specific =
27758 		    ((struct mode_header *)sense)->device_specific;
27759 	}
27760 
27761 
27762 	/*
27763 	 * Write protect mode sense failed; not all disks
27764 	 * understand this query. Return FALSE assuming that
27765 	 * these devices are not writable.
27766 	 */
27767 	if (device_specific & WRITE_PROTECT) {
27768 		rval = TRUE;
27769 	}
27770 
27771 err_exit:
27772 	kmem_free(sense, hdrlen);
27773 	return (rval);
27774 }
27775 
27776 /*
27777  *    Function: sr_volume_ctrl()
27778  *
27779  * Description: This routine is the driver entry point for handling CD-ROM
27780  *		audio output volume ioctl requests. (CDROMVOLCTRL)
27781  *
27782  *   Arguments: dev	- the device 'dev_t'
27783  *		data	- pointer to user audio volume control structure
27784  *		flag	- this argument is a pass through to ddi_copyxxx()
27785  *			  directly from the mode argument of ioctl().
27786  *
27787  * Return Code: the code returned by sd_send_scsi_cmd()
27788  *		EFAULT if ddi_copyxxx() fails
27789  *		ENXIO if fail ddi_get_soft_state
27790  *		EINVAL if data pointer is NULL
27791  *
27792  */
27793 
27794 static int
27795 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
27796 {
27797 	struct sd_lun		*un;
27798 	struct cdrom_volctrl    volume;
27799 	struct cdrom_volctrl    *vol = &volume;
27800 	uchar_t			*sense_page;
27801 	uchar_t			*select_page;
27802 	uchar_t			*sense;
27803 	uchar_t			*select;
27804 	int			sense_buflen;
27805 	int			select_buflen;
27806 	int			rval;
27807 	sd_ssc_t		*ssc;
27808 
27809 	if (data == NULL) {
27810 		return (EINVAL);
27811 	}
27812 
27813 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27814 	    (un->un_state == SD_STATE_OFFLINE)) {
27815 		return (ENXIO);
27816 	}
27817 
27818 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
27819 		return (EFAULT);
27820 	}
27821 
27822 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
27823 		struct mode_header_grp2		*sense_mhp;
27824 		struct mode_header_grp2		*select_mhp;
27825 		int				bd_len;
27826 
27827 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
27828 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
27829 		    MODEPAGE_AUDIO_CTRL_LEN;
27830 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
27831 		select = kmem_zalloc(select_buflen, KM_SLEEP);
27832 		ssc = sd_ssc_init(un);
27833 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
27834 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
27835 		    SD_PATH_STANDARD);
27836 		sd_ssc_fini(ssc);
27837 
27838 		if (rval != 0) {
27839 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
27840 			    "sr_volume_ctrl: Mode Sense Failed\n");
27841 			kmem_free(sense, sense_buflen);
27842 			kmem_free(select, select_buflen);
27843 			return (rval);
27844 		}
27845 		sense_mhp = (struct mode_header_grp2 *)sense;
27846 		select_mhp = (struct mode_header_grp2 *)select;
27847 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
27848 		    sense_mhp->bdesc_length_lo;
27849 		if (bd_len > MODE_BLK_DESC_LENGTH) {
27850 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27851 			    "sr_volume_ctrl: Mode Sense returned invalid "
27852 			    "block descriptor length\n");
27853 			kmem_free(sense, sense_buflen);
27854 			kmem_free(select, select_buflen);
27855 			return (EIO);
27856 		}
27857 		sense_page = (uchar_t *)
27858 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27859 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
27860 		select_mhp->length_msb = 0;
27861 		select_mhp->length_lsb = 0;
27862 		select_mhp->bdesc_length_hi = 0;
27863 		select_mhp->bdesc_length_lo = 0;
27864 	} else {
27865 		struct mode_header		*sense_mhp, *select_mhp;
27866 
27867 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
27868 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
27869 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
27870 		select = kmem_zalloc(select_buflen, KM_SLEEP);
27871 		ssc = sd_ssc_init(un);
27872 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27873 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
27874 		    SD_PATH_STANDARD);
27875 		sd_ssc_fini(ssc);
27876 
27877 		if (rval != 0) {
27878 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27879 			    "sr_volume_ctrl: Mode Sense Failed\n");
27880 			kmem_free(sense, sense_buflen);
27881 			kmem_free(select, select_buflen);
27882 			return (rval);
27883 		}
27884 		sense_mhp  = (struct mode_header *)sense;
27885 		select_mhp = (struct mode_header *)select;
27886 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
27887 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27888 			    "sr_volume_ctrl: Mode Sense returned invalid "
27889 			    "block descriptor length\n");
27890 			kmem_free(sense, sense_buflen);
27891 			kmem_free(select, select_buflen);
27892 			return (EIO);
27893 		}
27894 		sense_page = (uchar_t *)
27895 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27896 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
27897 		select_mhp->length = 0;
27898 		select_mhp->bdesc_length = 0;
27899 	}
27900 	/*
27901 	 * Note: An audio control data structure could be created and overlayed
27902 	 * on the following in place of the array indexing method implemented.
27903 	 */
27904 
27905 	/* Build the select data for the user volume data */
27906 	select_page[0] = MODEPAGE_AUDIO_CTRL;
27907 	select_page[1] = 0xE;
27908 	/* Set the immediate bit */
27909 	select_page[2] = 0x04;
27910 	/* Zero out reserved fields */
27911 	select_page[3] = 0x00;
27912 	select_page[4] = 0x00;
27913 	/* Return sense data for fields not to be modified */
27914 	select_page[5] = sense_page[5];
27915 	select_page[6] = sense_page[6];
27916 	select_page[7] = sense_page[7];
27917 	/* Set the user specified volume levels for channel 0 and 1 */
27918 	select_page[8] = 0x01;
27919 	select_page[9] = vol->channel0;
27920 	select_page[10] = 0x02;
27921 	select_page[11] = vol->channel1;
27922 	/* Channel 2 and 3 are currently unsupported so return the sense data */
27923 	select_page[12] = sense_page[12];
27924 	select_page[13] = sense_page[13];
27925 	select_page[14] = sense_page[14];
27926 	select_page[15] = sense_page[15];
27927 
27928 	ssc = sd_ssc_init(un);
27929 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
27930 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
27931 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27932 	} else {
27933 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27934 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27935 	}
27936 	sd_ssc_fini(ssc);
27937 
27938 	kmem_free(sense, sense_buflen);
27939 	kmem_free(select, select_buflen);
27940 	return (rval);
27941 }
27942 
27943 
27944 /*
27945  *    Function: sr_read_sony_session_offset()
27946  *
27947  * Description: This routine is the driver entry point for handling CD-ROM
27948  *		ioctl requests for session offset information. (CDROMREADOFFSET)
27949  *		The address of the first track in the last session of a
27950  *		multi-session CD-ROM is returned
27951  *
27952  *		Note: This routine uses a vendor specific key value in the
27953  *		command control field without implementing any vendor check here
27954  *		or in the ioctl routine.
27955  *
27956  *   Arguments: dev	- the device 'dev_t'
27957  *		data	- pointer to an int to hold the requested address
27958  *		flag	- this argument is a pass through to ddi_copyxxx()
27959  *			  directly from the mode argument of ioctl().
27960  *
27961  * Return Code: the code returned by sd_send_scsi_cmd()
27962  *		EFAULT if ddi_copyxxx() fails
27963  *		ENXIO if fail ddi_get_soft_state
27964  *		EINVAL if data pointer is NULL
27965  */
27966 
27967 static int
27968 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
27969 {
27970 	struct sd_lun		*un;
27971 	struct uscsi_cmd	*com;
27972 	caddr_t			buffer;
27973 	char			cdb[CDB_GROUP1];
27974 	int			session_offset = 0;
27975 	int			rval;
27976 
27977 	if (data == NULL) {
27978 		return (EINVAL);
27979 	}
27980 
27981 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27982 	    (un->un_state == SD_STATE_OFFLINE)) {
27983 		return (ENXIO);
27984 	}
27985 
27986 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
27987 	bzero(cdb, CDB_GROUP1);
27988 	cdb[0] = SCMD_READ_TOC;
27989 	/*
27990 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
27991 	 * (4 byte TOC response header + 8 byte response data)
27992 	 */
27993 	cdb[8] = SONY_SESSION_OFFSET_LEN;
27994 	/* Byte 9 is the control byte. A vendor specific value is used */
27995 	cdb[9] = SONY_SESSION_OFFSET_KEY;
27996 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27997 	com->uscsi_cdb = cdb;
27998 	com->uscsi_cdblen = CDB_GROUP1;
27999 	com->uscsi_bufaddr = buffer;
28000 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
28001 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28002 
28003 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28004 	    SD_PATH_STANDARD);
28005 	if (rval != 0) {
28006 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
28007 		kmem_free(com, sizeof (*com));
28008 		return (rval);
28009 	}
28010 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
28011 		session_offset =
28012 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
28013 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
28014 		/*
28015 		 * Offset returned offset in current lbasize block's. Convert to
28016 		 * 2k block's to return to the user
28017 		 */
28018 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
28019 			session_offset >>= 2;
28020 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
28021 			session_offset >>= 1;
28022 		}
28023 	}
28024 
28025 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
28026 		rval = EFAULT;
28027 	}
28028 
28029 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
28030 	kmem_free(com, sizeof (*com));
28031 	return (rval);
28032 }
28033 
28034 
28035 /*
28036  *    Function: sd_wm_cache_constructor()
28037  *
28038  * Description: Cache Constructor for the wmap cache for the read/modify/write
28039  * 		devices.
28040  *
28041  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
28042  *		un	- sd_lun structure for the device.
28043  *		flag	- the km flags passed to constructor
28044  *
28045  * Return Code: 0 on success.
28046  *		-1 on failure.
28047  */
28048 
28049 /*ARGSUSED*/
28050 static int
28051 sd_wm_cache_constructor(void *wm, void *un, int flags)
28052 {
28053 	bzero(wm, sizeof (struct sd_w_map));
28054 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
28055 	return (0);
28056 }
28057 
28058 
28059 /*
28060  *    Function: sd_wm_cache_destructor()
28061  *
28062  * Description: Cache destructor for the wmap cache for the read/modify/write
28063  * 		devices.
28064  *
28065  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
28066  *		un	- sd_lun structure for the device.
28067  */
28068 /*ARGSUSED*/
28069 static void
28070 sd_wm_cache_destructor(void *wm, void *un)
28071 {
28072 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
28073 }
28074 
28075 
28076 /*
28077  *    Function: sd_range_lock()
28078  *
28079  * Description: Lock the range of blocks specified as parameter to ensure
28080  *		that read, modify write is atomic and no other i/o writes
28081  *		to the same location. The range is specified in terms
28082  *		of start and end blocks. Block numbers are the actual
28083  *		media block numbers and not system.
28084  *
28085  *   Arguments: un	- sd_lun structure for the device.
28086  *		startb - The starting block number
28087  *		endb - The end block number
28088  *		typ - type of i/o - simple/read_modify_write
28089  *
28090  * Return Code: wm  - pointer to the wmap structure.
28091  *
28092  *     Context: This routine can sleep.
28093  */
28094 
28095 static struct sd_w_map *
28096 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
28097 {
28098 	struct sd_w_map *wmp = NULL;
28099 	struct sd_w_map *sl_wmp = NULL;
28100 	struct sd_w_map *tmp_wmp;
28101 	wm_state state = SD_WM_CHK_LIST;
28102 
28103 
28104 	ASSERT(un != NULL);
28105 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28106 
28107 	mutex_enter(SD_MUTEX(un));
28108 
28109 	while (state != SD_WM_DONE) {
28110 
28111 		switch (state) {
28112 		case SD_WM_CHK_LIST:
28113 			/*
28114 			 * This is the starting state. Check the wmap list
28115 			 * to see if the range is currently available.
28116 			 */
28117 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
28118 				/*
28119 				 * If this is a simple write and no rmw
28120 				 * i/o is pending then try to lock the
28121 				 * range as the range should be available.
28122 				 */
28123 				state = SD_WM_LOCK_RANGE;
28124 			} else {
28125 				tmp_wmp = sd_get_range(un, startb, endb);
28126 				if (tmp_wmp != NULL) {
28127 					if ((wmp != NULL) && ONLIST(un, wmp)) {
28128 						/*
28129 						 * Should not keep onlist wmps
28130 						 * while waiting this macro
28131 						 * will also do wmp = NULL;
28132 						 */
28133 						FREE_ONLIST_WMAP(un, wmp);
28134 					}
28135 					/*
28136 					 * sl_wmp is the wmap on which wait
28137 					 * is done, since the tmp_wmp points
28138 					 * to the inuse wmap, set sl_wmp to
28139 					 * tmp_wmp and change the state to sleep
28140 					 */
28141 					sl_wmp = tmp_wmp;
28142 					state = SD_WM_WAIT_MAP;
28143 				} else {
28144 					state = SD_WM_LOCK_RANGE;
28145 				}
28146 
28147 			}
28148 			break;
28149 
28150 		case SD_WM_LOCK_RANGE:
28151 			ASSERT(un->un_wm_cache);
28152 			/*
28153 			 * The range need to be locked, try to get a wmap.
28154 			 * First attempt it with NO_SLEEP, want to avoid a sleep
28155 			 * if possible as we will have to release the sd mutex
28156 			 * if we have to sleep.
28157 			 */
28158 			if (wmp == NULL)
28159 				wmp = kmem_cache_alloc(un->un_wm_cache,
28160 				    KM_NOSLEEP);
28161 			if (wmp == NULL) {
28162 				mutex_exit(SD_MUTEX(un));
28163 				_NOTE(DATA_READABLE_WITHOUT_LOCK
28164 				    (sd_lun::un_wm_cache))
28165 				wmp = kmem_cache_alloc(un->un_wm_cache,
28166 				    KM_SLEEP);
28167 				mutex_enter(SD_MUTEX(un));
28168 				/*
28169 				 * we released the mutex so recheck and go to
28170 				 * check list state.
28171 				 */
28172 				state = SD_WM_CHK_LIST;
28173 			} else {
28174 				/*
28175 				 * We exit out of state machine since we
28176 				 * have the wmap. Do the housekeeping first.
28177 				 * place the wmap on the wmap list if it is not
28178 				 * on it already and then set the state to done.
28179 				 */
28180 				wmp->wm_start = startb;
28181 				wmp->wm_end = endb;
28182 				wmp->wm_flags = typ | SD_WM_BUSY;
28183 				if (typ & SD_WTYPE_RMW) {
28184 					un->un_rmw_count++;
28185 				}
28186 				/*
28187 				 * If not already on the list then link
28188 				 */
28189 				if (!ONLIST(un, wmp)) {
28190 					wmp->wm_next = un->un_wm;
28191 					wmp->wm_prev = NULL;
28192 					if (wmp->wm_next)
28193 						wmp->wm_next->wm_prev = wmp;
28194 					un->un_wm = wmp;
28195 				}
28196 				state = SD_WM_DONE;
28197 			}
28198 			break;
28199 
28200 		case SD_WM_WAIT_MAP:
28201 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
28202 			/*
28203 			 * Wait is done on sl_wmp, which is set in the
28204 			 * check_list state.
28205 			 */
28206 			sl_wmp->wm_wanted_count++;
28207 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
28208 			sl_wmp->wm_wanted_count--;
28209 			/*
28210 			 * We can reuse the memory from the completed sl_wmp
28211 			 * lock range for our new lock, but only if noone is
28212 			 * waiting for it.
28213 			 */
28214 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
28215 			if (sl_wmp->wm_wanted_count == 0) {
28216 				if (wmp != NULL)
28217 					CHK_N_FREEWMP(un, wmp);
28218 				wmp = sl_wmp;
28219 			}
28220 			sl_wmp = NULL;
28221 			/*
28222 			 * After waking up, need to recheck for availability of
28223 			 * range.
28224 			 */
28225 			state = SD_WM_CHK_LIST;
28226 			break;
28227 
28228 		default:
28229 			panic("sd_range_lock: "
28230 			    "Unknown state %d in sd_range_lock", state);
28231 			/*NOTREACHED*/
28232 		} /* switch(state) */
28233 
28234 	} /* while(state != SD_WM_DONE) */
28235 
28236 	mutex_exit(SD_MUTEX(un));
28237 
28238 	ASSERT(wmp != NULL);
28239 
28240 	return (wmp);
28241 }
28242 
28243 
28244 /*
28245  *    Function: sd_get_range()
28246  *
28247  * Description: Find if there any overlapping I/O to this one
28248  *		Returns the write-map of 1st such I/O, NULL otherwise.
28249  *
28250  *   Arguments: un	- sd_lun structure for the device.
28251  *		startb - The starting block number
28252  *		endb - The end block number
28253  *
28254  * Return Code: wm  - pointer to the wmap structure.
28255  */
28256 
28257 static struct sd_w_map *
28258 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
28259 {
28260 	struct sd_w_map *wmp;
28261 
28262 	ASSERT(un != NULL);
28263 
28264 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
28265 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
28266 			continue;
28267 		}
28268 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
28269 			break;
28270 		}
28271 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
28272 			break;
28273 		}
28274 	}
28275 
28276 	return (wmp);
28277 }
28278 
28279 
28280 /*
28281  *    Function: sd_free_inlist_wmap()
28282  *
28283  * Description: Unlink and free a write map struct.
28284  *
28285  *   Arguments: un      - sd_lun structure for the device.
28286  *		wmp	- sd_w_map which needs to be unlinked.
28287  */
28288 
28289 static void
28290 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
28291 {
28292 	ASSERT(un != NULL);
28293 
28294 	if (un->un_wm == wmp) {
28295 		un->un_wm = wmp->wm_next;
28296 	} else {
28297 		wmp->wm_prev->wm_next = wmp->wm_next;
28298 	}
28299 
28300 	if (wmp->wm_next) {
28301 		wmp->wm_next->wm_prev = wmp->wm_prev;
28302 	}
28303 
28304 	wmp->wm_next = wmp->wm_prev = NULL;
28305 
28306 	kmem_cache_free(un->un_wm_cache, wmp);
28307 }
28308 
28309 
28310 /*
28311  *    Function: sd_range_unlock()
28312  *
28313  * Description: Unlock the range locked by wm.
28314  *		Free write map if nobody else is waiting on it.
28315  *
28316  *   Arguments: un      - sd_lun structure for the device.
28317  *              wmp     - sd_w_map which needs to be unlinked.
28318  */
28319 
28320 static void
28321 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
28322 {
28323 	ASSERT(un != NULL);
28324 	ASSERT(wm != NULL);
28325 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28326 
28327 	mutex_enter(SD_MUTEX(un));
28328 
28329 	if (wm->wm_flags & SD_WTYPE_RMW) {
28330 		un->un_rmw_count--;
28331 	}
28332 
28333 	if (wm->wm_wanted_count) {
28334 		wm->wm_flags = 0;
28335 		/*
28336 		 * Broadcast that the wmap is available now.
28337 		 */
28338 		cv_broadcast(&wm->wm_avail);
28339 	} else {
28340 		/*
28341 		 * If no one is waiting on the map, it should be free'ed.
28342 		 */
28343 		sd_free_inlist_wmap(un, wm);
28344 	}
28345 
28346 	mutex_exit(SD_MUTEX(un));
28347 }
28348 
28349 
28350 /*
28351  *    Function: sd_read_modify_write_task
28352  *
28353  * Description: Called from a taskq thread to initiate the write phase of
28354  *		a read-modify-write request.  This is used for targets where
28355  *		un->un_sys_blocksize != un->un_tgt_blocksize.
28356  *
28357  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
28358  *
28359  *     Context: Called under taskq thread context.
28360  */
28361 
28362 static void
28363 sd_read_modify_write_task(void *arg)
28364 {
28365 	struct sd_mapblocksize_info	*bsp;
28366 	struct buf	*bp;
28367 	struct sd_xbuf	*xp;
28368 	struct sd_lun	*un;
28369 
28370 	bp = arg;	/* The bp is given in arg */
28371 	ASSERT(bp != NULL);
28372 
28373 	/* Get the pointer to the layer-private data struct */
28374 	xp = SD_GET_XBUF(bp);
28375 	ASSERT(xp != NULL);
28376 	bsp = xp->xb_private;
28377 	ASSERT(bsp != NULL);
28378 
28379 	un = SD_GET_UN(bp);
28380 	ASSERT(un != NULL);
28381 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28382 
28383 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
28384 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
28385 
28386 	/*
28387 	 * This is the write phase of a read-modify-write request, called
28388 	 * under the context of a taskq thread in response to the completion
28389 	 * of the read portion of the rmw request completing under interrupt
28390 	 * context. The write request must be sent from here down the iostart
28391 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
28392 	 * we use the layer index saved in the layer-private data area.
28393 	 */
28394 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
28395 
28396 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
28397 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
28398 }
28399 
28400 
28401 /*
28402  *    Function: sddump_do_read_of_rmw()
28403  *
28404  * Description: This routine will be called from sddump, If sddump is called
28405  *		with an I/O which not aligned on device blocksize boundary
28406  *		then the write has to be converted to read-modify-write.
28407  *		Do the read part here in order to keep sddump simple.
28408  *		Note - That the sd_mutex is held across the call to this
28409  *		routine.
28410  *
28411  *   Arguments: un	- sd_lun
28412  *		blkno	- block number in terms of media block size.
28413  *		nblk	- number of blocks.
28414  *		bpp	- pointer to pointer to the buf structure. On return
28415  *			from this function, *bpp points to the valid buffer
28416  *			to which the write has to be done.
28417  *
28418  * Return Code: 0 for success or errno-type return code
28419  */
28420 
28421 static int
28422 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
28423 	struct buf **bpp)
28424 {
28425 	int err;
28426 	int i;
28427 	int rval;
28428 	struct buf *bp;
28429 	struct scsi_pkt *pkt = NULL;
28430 	uint32_t target_blocksize;
28431 
28432 	ASSERT(un != NULL);
28433 	ASSERT(mutex_owned(SD_MUTEX(un)));
28434 
28435 	target_blocksize = un->un_tgt_blocksize;
28436 
28437 	mutex_exit(SD_MUTEX(un));
28438 
28439 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
28440 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
28441 	if (bp == NULL) {
28442 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28443 		    "no resources for dumping; giving up");
28444 		err = ENOMEM;
28445 		goto done;
28446 	}
28447 
28448 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
28449 	    blkno, nblk);
28450 	if (rval != 0) {
28451 		scsi_free_consistent_buf(bp);
28452 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28453 		    "no resources for dumping; giving up");
28454 		err = ENOMEM;
28455 		goto done;
28456 	}
28457 
28458 	pkt->pkt_flags |= FLAG_NOINTR;
28459 
28460 	err = EIO;
28461 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
28462 
28463 		/*
28464 		 * Scsi_poll returns 0 (success) if the command completes and
28465 		 * the status block is STATUS_GOOD.  We should only check
28466 		 * errors if this condition is not true.  Even then we should
28467 		 * send our own request sense packet only if we have a check
28468 		 * condition and auto request sense has not been performed by
28469 		 * the hba.
28470 		 */
28471 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
28472 
28473 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
28474 			err = 0;
28475 			break;
28476 		}
28477 
28478 		/*
28479 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
28480 		 * no need to read RQS data.
28481 		 */
28482 		if (pkt->pkt_reason == CMD_DEV_GONE) {
28483 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28484 			    "Error while dumping state with rmw..."
28485 			    "Device is gone\n");
28486 			break;
28487 		}
28488 
28489 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
28490 			SD_INFO(SD_LOG_DUMP, un,
28491 			    "sddump: read failed with CHECK, try # %d\n", i);
28492 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
28493 				(void) sd_send_polled_RQS(un);
28494 			}
28495 
28496 			continue;
28497 		}
28498 
28499 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
28500 			int reset_retval = 0;
28501 
28502 			SD_INFO(SD_LOG_DUMP, un,
28503 			    "sddump: read failed with BUSY, try # %d\n", i);
28504 
28505 			if (un->un_f_lun_reset_enabled == TRUE) {
28506 				reset_retval = scsi_reset(SD_ADDRESS(un),
28507 				    RESET_LUN);
28508 			}
28509 			if (reset_retval == 0) {
28510 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
28511 			}
28512 			(void) sd_send_polled_RQS(un);
28513 
28514 		} else {
28515 			SD_INFO(SD_LOG_DUMP, un,
28516 			    "sddump: read failed with 0x%x, try # %d\n",
28517 			    SD_GET_PKT_STATUS(pkt), i);
28518 			mutex_enter(SD_MUTEX(un));
28519 			sd_reset_target(un, pkt);
28520 			mutex_exit(SD_MUTEX(un));
28521 		}
28522 
28523 		/*
28524 		 * If we are not getting anywhere with lun/target resets,
28525 		 * let's reset the bus.
28526 		 */
28527 		if (i > SD_NDUMP_RETRIES/2) {
28528 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
28529 			(void) sd_send_polled_RQS(un);
28530 		}
28531 
28532 	}
28533 	scsi_destroy_pkt(pkt);
28534 
28535 	if (err != 0) {
28536 		scsi_free_consistent_buf(bp);
28537 		*bpp = NULL;
28538 	} else {
28539 		*bpp = bp;
28540 	}
28541 
28542 done:
28543 	mutex_enter(SD_MUTEX(un));
28544 	return (err);
28545 }
28546 
28547 
28548 /*
28549  *    Function: sd_failfast_flushq
28550  *
28551  * Description: Take all bp's on the wait queue that have B_FAILFAST set
28552  *		in b_flags and move them onto the failfast queue, then kick
28553  *		off a thread to return all bp's on the failfast queue to
28554  *		their owners with an error set.
28555  *
28556  *   Arguments: un - pointer to the soft state struct for the instance.
28557  *
28558  *     Context: may execute in interrupt context.
28559  */
28560 
28561 static void
28562 sd_failfast_flushq(struct sd_lun *un)
28563 {
28564 	struct buf *bp;
28565 	struct buf *next_waitq_bp;
28566 	struct buf *prev_waitq_bp = NULL;
28567 
28568 	ASSERT(un != NULL);
28569 	ASSERT(mutex_owned(SD_MUTEX(un)));
28570 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
28571 	ASSERT(un->un_failfast_bp == NULL);
28572 
28573 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
28574 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
28575 
28576 	/*
28577 	 * Check if we should flush all bufs when entering failfast state, or
28578 	 * just those with B_FAILFAST set.
28579 	 */
28580 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
28581 		/*
28582 		 * Move *all* bp's on the wait queue to the failfast flush
28583 		 * queue, including those that do NOT have B_FAILFAST set.
28584 		 */
28585 		if (un->un_failfast_headp == NULL) {
28586 			ASSERT(un->un_failfast_tailp == NULL);
28587 			un->un_failfast_headp = un->un_waitq_headp;
28588 		} else {
28589 			ASSERT(un->un_failfast_tailp != NULL);
28590 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
28591 		}
28592 
28593 		un->un_failfast_tailp = un->un_waitq_tailp;
28594 
28595 		/* update kstat for each bp moved out of the waitq */
28596 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
28597 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
28598 		}
28599 
28600 		/* empty the waitq */
28601 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
28602 
28603 	} else {
28604 		/*
28605 		 * Go thru the wait queue, pick off all entries with
28606 		 * B_FAILFAST set, and move these onto the failfast queue.
28607 		 */
28608 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
28609 			/*
28610 			 * Save the pointer to the next bp on the wait queue,
28611 			 * so we get to it on the next iteration of this loop.
28612 			 */
28613 			next_waitq_bp = bp->av_forw;
28614 
28615 			/*
28616 			 * If this bp from the wait queue does NOT have
28617 			 * B_FAILFAST set, just move on to the next element
28618 			 * in the wait queue. Note, this is the only place
28619 			 * where it is correct to set prev_waitq_bp.
28620 			 */
28621 			if ((bp->b_flags & B_FAILFAST) == 0) {
28622 				prev_waitq_bp = bp;
28623 				continue;
28624 			}
28625 
28626 			/*
28627 			 * Remove the bp from the wait queue.
28628 			 */
28629 			if (bp == un->un_waitq_headp) {
28630 				/* The bp is the first element of the waitq. */
28631 				un->un_waitq_headp = next_waitq_bp;
28632 				if (un->un_waitq_headp == NULL) {
28633 					/* The wait queue is now empty */
28634 					un->un_waitq_tailp = NULL;
28635 				}
28636 			} else {
28637 				/*
28638 				 * The bp is either somewhere in the middle
28639 				 * or at the end of the wait queue.
28640 				 */
28641 				ASSERT(un->un_waitq_headp != NULL);
28642 				ASSERT(prev_waitq_bp != NULL);
28643 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
28644 				    == 0);
28645 				if (bp == un->un_waitq_tailp) {
28646 					/* bp is the last entry on the waitq. */
28647 					ASSERT(next_waitq_bp == NULL);
28648 					un->un_waitq_tailp = prev_waitq_bp;
28649 				}
28650 				prev_waitq_bp->av_forw = next_waitq_bp;
28651 			}
28652 			bp->av_forw = NULL;
28653 
28654 			/*
28655 			 * update kstat since the bp is moved out of
28656 			 * the waitq
28657 			 */
28658 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
28659 
28660 			/*
28661 			 * Now put the bp onto the failfast queue.
28662 			 */
28663 			if (un->un_failfast_headp == NULL) {
28664 				/* failfast queue is currently empty */
28665 				ASSERT(un->un_failfast_tailp == NULL);
28666 				un->un_failfast_headp =
28667 				    un->un_failfast_tailp = bp;
28668 			} else {
28669 				/* Add the bp to the end of the failfast q */
28670 				ASSERT(un->un_failfast_tailp != NULL);
28671 				ASSERT(un->un_failfast_tailp->b_flags &
28672 				    B_FAILFAST);
28673 				un->un_failfast_tailp->av_forw = bp;
28674 				un->un_failfast_tailp = bp;
28675 			}
28676 		}
28677 	}
28678 
28679 	/*
28680 	 * Now return all bp's on the failfast queue to their owners.
28681 	 */
28682 	while ((bp = un->un_failfast_headp) != NULL) {
28683 
28684 		un->un_failfast_headp = bp->av_forw;
28685 		if (un->un_failfast_headp == NULL) {
28686 			un->un_failfast_tailp = NULL;
28687 		}
28688 
28689 		/*
28690 		 * We want to return the bp with a failure error code, but
28691 		 * we do not want a call to sd_start_cmds() to occur here,
28692 		 * so use sd_return_failed_command_no_restart() instead of
28693 		 * sd_return_failed_command().
28694 		 */
28695 		sd_return_failed_command_no_restart(un, bp, EIO);
28696 	}
28697 
28698 	/* Flush the xbuf queues if required. */
28699 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
28700 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
28701 	}
28702 
28703 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
28704 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
28705 }
28706 
28707 
28708 /*
28709  *    Function: sd_failfast_flushq_callback
28710  *
28711  * Description: Return TRUE if the given bp meets the criteria for failfast
28712  *		flushing. Used with ddi_xbuf_flushq(9F).
28713  *
28714  *   Arguments: bp - ptr to buf struct to be examined.
28715  *
28716  *     Context: Any
28717  */
28718 
28719 static int
28720 sd_failfast_flushq_callback(struct buf *bp)
28721 {
28722 	/*
28723 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
28724 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
28725 	 */
28726 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
28727 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
28728 }
28729 
28730 
28731 
28732 /*
28733  * Function: sd_setup_next_xfer
28734  *
28735  * Description: Prepare next I/O operation using DMA_PARTIAL
28736  *
28737  */
28738 
28739 static int
28740 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
28741     struct scsi_pkt *pkt, struct sd_xbuf *xp)
28742 {
28743 	ssize_t	num_blks_not_xfered;
28744 	daddr_t	strt_blk_num;
28745 	ssize_t	bytes_not_xfered;
28746 	int	rval;
28747 
28748 	ASSERT(pkt->pkt_resid == 0);
28749 
28750 	/*
28751 	 * Calculate next block number and amount to be transferred.
28752 	 *
28753 	 * How much data NOT transfered to the HBA yet.
28754 	 */
28755 	bytes_not_xfered = xp->xb_dma_resid;
28756 
28757 	/*
28758 	 * figure how many blocks NOT transfered to the HBA yet.
28759 	 */
28760 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
28761 
28762 	/*
28763 	 * set starting block number to the end of what WAS transfered.
28764 	 */
28765 	strt_blk_num = xp->xb_blkno +
28766 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
28767 
28768 	/*
28769 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
28770 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
28771 	 * the disk mutex here.
28772 	 */
28773 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
28774 	    strt_blk_num, num_blks_not_xfered);
28775 
28776 	if (rval == 0) {
28777 
28778 		/*
28779 		 * Success.
28780 		 *
28781 		 * Adjust things if there are still more blocks to be
28782 		 * transfered.
28783 		 */
28784 		xp->xb_dma_resid = pkt->pkt_resid;
28785 		pkt->pkt_resid = 0;
28786 
28787 		return (1);
28788 	}
28789 
28790 	/*
28791 	 * There's really only one possible return value from
28792 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
28793 	 * returns NULL.
28794 	 */
28795 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
28796 
28797 	bp->b_resid = bp->b_bcount;
28798 	bp->b_flags |= B_ERROR;
28799 
28800 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28801 	    "Error setting up next portion of DMA transfer\n");
28802 
28803 	return (0);
28804 }
28805 
28806 /*
28807  *    Function: sd_panic_for_res_conflict
28808  *
28809  * Description: Call panic with a string formatted with "Reservation Conflict"
28810  *		and a human readable identifier indicating the SD instance
28811  *		that experienced the reservation conflict.
28812  *
28813  *   Arguments: un - pointer to the soft state struct for the instance.
28814  *
28815  *     Context: may execute in interrupt context.
28816  */
28817 
28818 #define	SD_RESV_CONFLICT_FMT_LEN 40
28819 void
28820 sd_panic_for_res_conflict(struct sd_lun *un)
28821 {
28822 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
28823 	char path_str[MAXPATHLEN];
28824 
28825 	(void) snprintf(panic_str, sizeof (panic_str),
28826 	    "Reservation Conflict\nDisk: %s",
28827 	    ddi_pathname(SD_DEVINFO(un), path_str));
28828 
28829 	panic(panic_str);
28830 }
28831 
28832 /*
28833  * Note: The following sd_faultinjection_ioctl( ) routines implement
28834  * driver support for handling fault injection for error analysis
28835  * causing faults in multiple layers of the driver.
28836  *
28837  */
28838 
28839 #ifdef SD_FAULT_INJECTION
28840 static uint_t   sd_fault_injection_on = 0;
28841 
28842 /*
28843  *    Function: sd_faultinjection_ioctl()
28844  *
28845  * Description: This routine is the driver entry point for handling
28846  *              faultinjection ioctls to inject errors into the
28847  *              layer model
28848  *
28849  *   Arguments: cmd	- the ioctl cmd received
28850  *		arg	- the arguments from user and returns
28851  */
28852 
28853 static void
28854 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
28855 
28856 	uint_t i = 0;
28857 	uint_t rval;
28858 
28859 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
28860 
28861 	mutex_enter(SD_MUTEX(un));
28862 
28863 	switch (cmd) {
28864 	case SDIOCRUN:
28865 		/* Allow pushed faults to be injected */
28866 		SD_INFO(SD_LOG_SDTEST, un,
28867 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
28868 
28869 		sd_fault_injection_on = 1;
28870 
28871 		SD_INFO(SD_LOG_IOERR, un,
28872 		    "sd_faultinjection_ioctl: run finished\n");
28873 		break;
28874 
28875 	case SDIOCSTART:
28876 		/* Start Injection Session */
28877 		SD_INFO(SD_LOG_SDTEST, un,
28878 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
28879 
28880 		sd_fault_injection_on = 0;
28881 		un->sd_injection_mask = 0xFFFFFFFF;
28882 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
28883 			un->sd_fi_fifo_pkt[i] = NULL;
28884 			un->sd_fi_fifo_xb[i] = NULL;
28885 			un->sd_fi_fifo_un[i] = NULL;
28886 			un->sd_fi_fifo_arq[i] = NULL;
28887 		}
28888 		un->sd_fi_fifo_start = 0;
28889 		un->sd_fi_fifo_end = 0;
28890 
28891 		mutex_enter(&(un->un_fi_mutex));
28892 		un->sd_fi_log[0] = '\0';
28893 		un->sd_fi_buf_len = 0;
28894 		mutex_exit(&(un->un_fi_mutex));
28895 
28896 		SD_INFO(SD_LOG_IOERR, un,
28897 		    "sd_faultinjection_ioctl: start finished\n");
28898 		break;
28899 
28900 	case SDIOCSTOP:
28901 		/* Stop Injection Session */
28902 		SD_INFO(SD_LOG_SDTEST, un,
28903 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
28904 		sd_fault_injection_on = 0;
28905 		un->sd_injection_mask = 0x0;
28906 
28907 		/* Empty stray or unuseds structs from fifo */
28908 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
28909 			if (un->sd_fi_fifo_pkt[i] != NULL) {
28910 				kmem_free(un->sd_fi_fifo_pkt[i],
28911 				    sizeof (struct sd_fi_pkt));
28912 			}
28913 			if (un->sd_fi_fifo_xb[i] != NULL) {
28914 				kmem_free(un->sd_fi_fifo_xb[i],
28915 				    sizeof (struct sd_fi_xb));
28916 			}
28917 			if (un->sd_fi_fifo_un[i] != NULL) {
28918 				kmem_free(un->sd_fi_fifo_un[i],
28919 				    sizeof (struct sd_fi_un));
28920 			}
28921 			if (un->sd_fi_fifo_arq[i] != NULL) {
28922 				kmem_free(un->sd_fi_fifo_arq[i],
28923 				    sizeof (struct sd_fi_arq));
28924 			}
28925 			un->sd_fi_fifo_pkt[i] = NULL;
28926 			un->sd_fi_fifo_un[i] = NULL;
28927 			un->sd_fi_fifo_xb[i] = NULL;
28928 			un->sd_fi_fifo_arq[i] = NULL;
28929 		}
28930 		un->sd_fi_fifo_start = 0;
28931 		un->sd_fi_fifo_end = 0;
28932 
28933 		SD_INFO(SD_LOG_IOERR, un,
28934 		    "sd_faultinjection_ioctl: stop finished\n");
28935 		break;
28936 
28937 	case SDIOCINSERTPKT:
28938 		/* Store a packet struct to be pushed onto fifo */
28939 		SD_INFO(SD_LOG_SDTEST, un,
28940 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
28941 
28942 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
28943 
28944 		sd_fault_injection_on = 0;
28945 
28946 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
28947 		if (un->sd_fi_fifo_pkt[i] != NULL) {
28948 			kmem_free(un->sd_fi_fifo_pkt[i],
28949 			    sizeof (struct sd_fi_pkt));
28950 		}
28951 		if (arg != NULL) {
28952 			un->sd_fi_fifo_pkt[i] =
28953 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
28954 			if (un->sd_fi_fifo_pkt[i] == NULL) {
28955 				/* Alloc failed don't store anything */
28956 				break;
28957 			}
28958 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
28959 			    sizeof (struct sd_fi_pkt), 0);
28960 			if (rval == -1) {
28961 				kmem_free(un->sd_fi_fifo_pkt[i],
28962 				    sizeof (struct sd_fi_pkt));
28963 				un->sd_fi_fifo_pkt[i] = NULL;
28964 			}
28965 		} else {
28966 			SD_INFO(SD_LOG_IOERR, un,
28967 			    "sd_faultinjection_ioctl: pkt null\n");
28968 		}
28969 		break;
28970 
28971 	case SDIOCINSERTXB:
28972 		/* Store a xb struct to be pushed onto fifo */
28973 		SD_INFO(SD_LOG_SDTEST, un,
28974 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
28975 
28976 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
28977 
28978 		sd_fault_injection_on = 0;
28979 
28980 		if (un->sd_fi_fifo_xb[i] != NULL) {
28981 			kmem_free(un->sd_fi_fifo_xb[i],
28982 			    sizeof (struct sd_fi_xb));
28983 			un->sd_fi_fifo_xb[i] = NULL;
28984 		}
28985 		if (arg != NULL) {
28986 			un->sd_fi_fifo_xb[i] =
28987 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
28988 			if (un->sd_fi_fifo_xb[i] == NULL) {
28989 				/* Alloc failed don't store anything */
28990 				break;
28991 			}
28992 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
28993 			    sizeof (struct sd_fi_xb), 0);
28994 
28995 			if (rval == -1) {
28996 				kmem_free(un->sd_fi_fifo_xb[i],
28997 				    sizeof (struct sd_fi_xb));
28998 				un->sd_fi_fifo_xb[i] = NULL;
28999 			}
29000 		} else {
29001 			SD_INFO(SD_LOG_IOERR, un,
29002 			    "sd_faultinjection_ioctl: xb null\n");
29003 		}
29004 		break;
29005 
29006 	case SDIOCINSERTUN:
29007 		/* Store a un struct to be pushed onto fifo */
29008 		SD_INFO(SD_LOG_SDTEST, un,
29009 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
29010 
29011 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29012 
29013 		sd_fault_injection_on = 0;
29014 
29015 		if (un->sd_fi_fifo_un[i] != NULL) {
29016 			kmem_free(un->sd_fi_fifo_un[i],
29017 			    sizeof (struct sd_fi_un));
29018 			un->sd_fi_fifo_un[i] = NULL;
29019 		}
29020 		if (arg != NULL) {
29021 			un->sd_fi_fifo_un[i] =
29022 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
29023 			if (un->sd_fi_fifo_un[i] == NULL) {
29024 				/* Alloc failed don't store anything */
29025 				break;
29026 			}
29027 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
29028 			    sizeof (struct sd_fi_un), 0);
29029 			if (rval == -1) {
29030 				kmem_free(un->sd_fi_fifo_un[i],
29031 				    sizeof (struct sd_fi_un));
29032 				un->sd_fi_fifo_un[i] = NULL;
29033 			}
29034 
29035 		} else {
29036 			SD_INFO(SD_LOG_IOERR, un,
29037 			    "sd_faultinjection_ioctl: un null\n");
29038 		}
29039 
29040 		break;
29041 
29042 	case SDIOCINSERTARQ:
29043 		/* Store a arq struct to be pushed onto fifo */
29044 		SD_INFO(SD_LOG_SDTEST, un,
29045 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
29046 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29047 
29048 		sd_fault_injection_on = 0;
29049 
29050 		if (un->sd_fi_fifo_arq[i] != NULL) {
29051 			kmem_free(un->sd_fi_fifo_arq[i],
29052 			    sizeof (struct sd_fi_arq));
29053 			un->sd_fi_fifo_arq[i] = NULL;
29054 		}
29055 		if (arg != NULL) {
29056 			un->sd_fi_fifo_arq[i] =
29057 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
29058 			if (un->sd_fi_fifo_arq[i] == NULL) {
29059 				/* Alloc failed don't store anything */
29060 				break;
29061 			}
29062 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
29063 			    sizeof (struct sd_fi_arq), 0);
29064 			if (rval == -1) {
29065 				kmem_free(un->sd_fi_fifo_arq[i],
29066 				    sizeof (struct sd_fi_arq));
29067 				un->sd_fi_fifo_arq[i] = NULL;
29068 			}
29069 
29070 		} else {
29071 			SD_INFO(SD_LOG_IOERR, un,
29072 			    "sd_faultinjection_ioctl: arq null\n");
29073 		}
29074 
29075 		break;
29076 
29077 	case SDIOCPUSH:
29078 		/* Push stored xb, pkt, un, and arq onto fifo */
29079 		sd_fault_injection_on = 0;
29080 
29081 		if (arg != NULL) {
29082 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
29083 			if (rval != -1 &&
29084 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
29085 				un->sd_fi_fifo_end += i;
29086 			}
29087 		} else {
29088 			SD_INFO(SD_LOG_IOERR, un,
29089 			    "sd_faultinjection_ioctl: push arg null\n");
29090 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
29091 				un->sd_fi_fifo_end++;
29092 			}
29093 		}
29094 		SD_INFO(SD_LOG_IOERR, un,
29095 		    "sd_faultinjection_ioctl: push to end=%d\n",
29096 		    un->sd_fi_fifo_end);
29097 		break;
29098 
29099 	case SDIOCRETRIEVE:
29100 		/* Return buffer of log from Injection session */
29101 		SD_INFO(SD_LOG_SDTEST, un,
29102 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
29103 
29104 		sd_fault_injection_on = 0;
29105 
29106 		mutex_enter(&(un->un_fi_mutex));
29107 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
29108 		    un->sd_fi_buf_len+1, 0);
29109 		mutex_exit(&(un->un_fi_mutex));
29110 
29111 		if (rval == -1) {
29112 			/*
29113 			 * arg is possibly invalid setting
29114 			 * it to NULL for return
29115 			 */
29116 			arg = NULL;
29117 		}
29118 		break;
29119 	}
29120 
29121 	mutex_exit(SD_MUTEX(un));
29122 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
29123 			    " exit\n");
29124 }
29125 
29126 
29127 /*
29128  *    Function: sd_injection_log()
29129  *
29130  * Description: This routine adds buff to the already existing injection log
29131  *              for retrieval via faultinjection_ioctl for use in fault
29132  *              detection and recovery
29133  *
29134  *   Arguments: buf - the string to add to the log
29135  */
29136 
29137 static void
29138 sd_injection_log(char *buf, struct sd_lun *un)
29139 {
29140 	uint_t len;
29141 
29142 	ASSERT(un != NULL);
29143 	ASSERT(buf != NULL);
29144 
29145 	mutex_enter(&(un->un_fi_mutex));
29146 
29147 	len = min(strlen(buf), 255);
29148 	/* Add logged value to Injection log to be returned later */
29149 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
29150 		uint_t	offset = strlen((char *)un->sd_fi_log);
29151 		char *destp = (char *)un->sd_fi_log + offset;
29152 		int i;
29153 		for (i = 0; i < len; i++) {
29154 			*destp++ = *buf++;
29155 		}
29156 		un->sd_fi_buf_len += len;
29157 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
29158 	}
29159 
29160 	mutex_exit(&(un->un_fi_mutex));
29161 }
29162 
29163 
29164 /*
29165  *    Function: sd_faultinjection()
29166  *
29167  * Description: This routine takes the pkt and changes its
29168  *		content based on error injection scenerio.
29169  *
29170  *   Arguments: pktp	- packet to be changed
29171  */
29172 
29173 static void
29174 sd_faultinjection(struct scsi_pkt *pktp)
29175 {
29176 	uint_t i;
29177 	struct sd_fi_pkt *fi_pkt;
29178 	struct sd_fi_xb *fi_xb;
29179 	struct sd_fi_un *fi_un;
29180 	struct sd_fi_arq *fi_arq;
29181 	struct buf *bp;
29182 	struct sd_xbuf *xb;
29183 	struct sd_lun *un;
29184 
29185 	ASSERT(pktp != NULL);
29186 
29187 	/* pull bp xb and un from pktp */
29188 	bp = (struct buf *)pktp->pkt_private;
29189 	xb = SD_GET_XBUF(bp);
29190 	un = SD_GET_UN(bp);
29191 
29192 	ASSERT(un != NULL);
29193 
29194 	mutex_enter(SD_MUTEX(un));
29195 
29196 	SD_TRACE(SD_LOG_SDTEST, un,
29197 	    "sd_faultinjection: entry Injection from sdintr\n");
29198 
29199 	/* if injection is off return */
29200 	if (sd_fault_injection_on == 0 ||
29201 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
29202 		mutex_exit(SD_MUTEX(un));
29203 		return;
29204 	}
29205 
29206 	SD_INFO(SD_LOG_SDTEST, un,
29207 	    "sd_faultinjection: is working for copying\n");
29208 
29209 	/* take next set off fifo */
29210 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
29211 
29212 	fi_pkt = un->sd_fi_fifo_pkt[i];
29213 	fi_xb = un->sd_fi_fifo_xb[i];
29214 	fi_un = un->sd_fi_fifo_un[i];
29215 	fi_arq = un->sd_fi_fifo_arq[i];
29216 
29217 
29218 	/* set variables accordingly */
29219 	/* set pkt if it was on fifo */
29220 	if (fi_pkt != NULL) {
29221 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
29222 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
29223 		if (fi_pkt->pkt_cdbp != 0xff)
29224 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
29225 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
29226 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
29227 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
29228 
29229 	}
29230 	/* set xb if it was on fifo */
29231 	if (fi_xb != NULL) {
29232 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
29233 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
29234 		if (fi_xb->xb_retry_count != 0)
29235 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
29236 		SD_CONDSET(xb, xb, xb_victim_retry_count,
29237 		    "xb_victim_retry_count");
29238 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
29239 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
29240 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
29241 
29242 		/* copy in block data from sense */
29243 		/*
29244 		 * if (fi_xb->xb_sense_data[0] != -1) {
29245 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
29246 		 *	SENSE_LENGTH);
29247 		 * }
29248 		 */
29249 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
29250 
29251 		/* copy in extended sense codes */
29252 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29253 		    xb, es_code, "es_code");
29254 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29255 		    xb, es_key, "es_key");
29256 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29257 		    xb, es_add_code, "es_add_code");
29258 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29259 		    xb, es_qual_code, "es_qual_code");
29260 		struct scsi_extended_sense *esp;
29261 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
29262 		esp->es_class = CLASS_EXTENDED_SENSE;
29263 	}
29264 
29265 	/* set un if it was on fifo */
29266 	if (fi_un != NULL) {
29267 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
29268 		SD_CONDSET(un, un, un_ctype, "un_ctype");
29269 		SD_CONDSET(un, un, un_reset_retry_count,
29270 		    "un_reset_retry_count");
29271 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
29272 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
29273 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
29274 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
29275 		    "un_f_allow_bus_device_reset");
29276 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
29277 
29278 	}
29279 
29280 	/* copy in auto request sense if it was on fifo */
29281 	if (fi_arq != NULL) {
29282 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
29283 	}
29284 
29285 	/* free structs */
29286 	if (un->sd_fi_fifo_pkt[i] != NULL) {
29287 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
29288 	}
29289 	if (un->sd_fi_fifo_xb[i] != NULL) {
29290 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
29291 	}
29292 	if (un->sd_fi_fifo_un[i] != NULL) {
29293 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
29294 	}
29295 	if (un->sd_fi_fifo_arq[i] != NULL) {
29296 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
29297 	}
29298 
29299 	/*
29300 	 * kmem_free does not gurantee to set to NULL
29301 	 * since we uses these to determine if we set
29302 	 * values or not lets confirm they are always
29303 	 * NULL after free
29304 	 */
29305 	un->sd_fi_fifo_pkt[i] = NULL;
29306 	un->sd_fi_fifo_un[i] = NULL;
29307 	un->sd_fi_fifo_xb[i] = NULL;
29308 	un->sd_fi_fifo_arq[i] = NULL;
29309 
29310 	un->sd_fi_fifo_start++;
29311 
29312 	mutex_exit(SD_MUTEX(un));
29313 
29314 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
29315 }
29316 
29317 #endif /* SD_FAULT_INJECTION */
29318 
29319 /*
29320  * This routine is invoked in sd_unit_attach(). Before calling it, the
29321  * properties in conf file should be processed already, and "hotpluggable"
29322  * property was processed also.
29323  *
29324  * The sd driver distinguishes 3 different type of devices: removable media,
29325  * non-removable media, and hotpluggable. Below the differences are defined:
29326  *
29327  * 1. Device ID
29328  *
29329  *     The device ID of a device is used to identify this device. Refer to
29330  *     ddi_devid_register(9F).
29331  *
29332  *     For a non-removable media disk device which can provide 0x80 or 0x83
29333  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
29334  *     device ID is created to identify this device. For other non-removable
29335  *     media devices, a default device ID is created only if this device has
29336  *     at least 2 alter cylinders. Otherwise, this device has no devid.
29337  *
29338  *     -------------------------------------------------------
29339  *     removable media   hotpluggable  | Can Have Device ID
29340  *     -------------------------------------------------------
29341  *         false             false     |     Yes
29342  *         false             true      |     Yes
29343  *         true                x       |     No
29344  *     ------------------------------------------------------
29345  *
29346  *
29347  * 2. SCSI group 4 commands
29348  *
29349  *     In SCSI specs, only some commands in group 4 command set can use
29350  *     8-byte addresses that can be used to access >2TB storage spaces.
29351  *     Other commands have no such capability. Without supporting group4,
29352  *     it is impossible to make full use of storage spaces of a disk with
29353  *     capacity larger than 2TB.
29354  *
29355  *     -----------------------------------------------
29356  *     removable media   hotpluggable   LP64  |  Group
29357  *     -----------------------------------------------
29358  *           false          false       false |   1
29359  *           false          false       true  |   4
29360  *           false          true        false |   1
29361  *           false          true        true  |   4
29362  *           true             x           x   |   5
29363  *     -----------------------------------------------
29364  *
29365  *
29366  * 3. Check for VTOC Label
29367  *
29368  *     If a direct-access disk has no EFI label, sd will check if it has a
29369  *     valid VTOC label. Now, sd also does that check for removable media
29370  *     and hotpluggable devices.
29371  *
29372  *     --------------------------------------------------------------
29373  *     Direct-Access   removable media    hotpluggable |  Check Label
29374  *     -------------------------------------------------------------
29375  *         false          false           false        |   No
29376  *         false          false           true         |   No
29377  *         false          true            false        |   Yes
29378  *         false          true            true         |   Yes
29379  *         true            x                x          |   Yes
29380  *     --------------------------------------------------------------
29381  *
29382  *
29383  * 4. Building default VTOC label
29384  *
29385  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
29386  *     If those devices have no valid VTOC label, sd(7d) will attempt to
29387  *     create default VTOC for them. Currently sd creates default VTOC label
29388  *     for all devices on x86 platform (VTOC_16), but only for removable
29389  *     media devices on SPARC (VTOC_8).
29390  *
29391  *     -----------------------------------------------------------
29392  *       removable media hotpluggable platform   |   Default Label
29393  *     -----------------------------------------------------------
29394  *             false          false    sparc     |     No
29395  *             false          true      x86      |     Yes
29396  *             false          true     sparc     |     Yes
29397  *             true             x        x       |     Yes
29398  *     ----------------------------------------------------------
29399  *
29400  *
29401  * 5. Supported blocksizes of target devices
29402  *
29403  *     Sd supports non-512-byte blocksize for removable media devices only.
29404  *     For other devices, only 512-byte blocksize is supported. This may be
29405  *     changed in near future because some RAID devices require non-512-byte
29406  *     blocksize
29407  *
29408  *     -----------------------------------------------------------
29409  *     removable media    hotpluggable    | non-512-byte blocksize
29410  *     -----------------------------------------------------------
29411  *           false          false         |   No
29412  *           false          true          |   No
29413  *           true             x           |   Yes
29414  *     -----------------------------------------------------------
29415  *
29416  *
29417  * 6. Automatic mount & unmount
29418  *
29419  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
29420  *     if a device is removable media device. It return 1 for removable media
29421  *     devices, and 0 for others.
29422  *
29423  *     The automatic mounting subsystem should distinguish between the types
29424  *     of devices and apply automounting policies to each.
29425  *
29426  *
29427  * 7. fdisk partition management
29428  *
29429  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
29430  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
29431  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
29432  *     fdisk partitions on both x86 and SPARC platform.
29433  *
29434  *     -----------------------------------------------------------
29435  *       platform   removable media  USB/1394  |  fdisk supported
29436  *     -----------------------------------------------------------
29437  *        x86         X               X        |       true
29438  *     ------------------------------------------------------------
29439  *        sparc       X               X        |       false
29440  *     ------------------------------------------------------------
29441  *
29442  *
29443  * 8. MBOOT/MBR
29444  *
29445  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
29446  *     read/write mboot for removable media devices on sparc platform.
29447  *
29448  *     -----------------------------------------------------------
29449  *       platform   removable media  USB/1394  |  mboot supported
29450  *     -----------------------------------------------------------
29451  *        x86         X               X        |       true
29452  *     ------------------------------------------------------------
29453  *        sparc      false           false     |       false
29454  *        sparc      false           true      |       true
29455  *        sparc      true            false     |       true
29456  *        sparc      true            true      |       true
29457  *     ------------------------------------------------------------
29458  *
29459  *
29460  * 9.  error handling during opening device
29461  *
29462  *     If failed to open a disk device, an errno is returned. For some kinds
29463  *     of errors, different errno is returned depending on if this device is
29464  *     a removable media device. This brings USB/1394 hard disks in line with
29465  *     expected hard disk behavior. It is not expected that this breaks any
29466  *     application.
29467  *
29468  *     ------------------------------------------------------
29469  *       removable media    hotpluggable   |  errno
29470  *     ------------------------------------------------------
29471  *             false          false        |   EIO
29472  *             false          true         |   EIO
29473  *             true             x          |   ENXIO
29474  *     ------------------------------------------------------
29475  *
29476  *
29477  * 11. ioctls: DKIOCEJECT, CDROMEJECT
29478  *
29479  *     These IOCTLs are applicable only to removable media devices.
29480  *
29481  *     -----------------------------------------------------------
29482  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
29483  *     -----------------------------------------------------------
29484  *             false          false        |     No
29485  *             false          true         |     No
29486  *             true            x           |     Yes
29487  *     -----------------------------------------------------------
29488  *
29489  *
29490  * 12. Kstats for partitions
29491  *
29492  *     sd creates partition kstat for non-removable media devices. USB and
29493  *     Firewire hard disks now have partition kstats
29494  *
29495  *      ------------------------------------------------------
29496  *       removable media    hotpluggable   |   kstat
29497  *      ------------------------------------------------------
29498  *             false          false        |    Yes
29499  *             false          true         |    Yes
29500  *             true             x          |    No
29501  *       ------------------------------------------------------
29502  *
29503  *
29504  * 13. Removable media & hotpluggable properties
29505  *
29506  *     Sd driver creates a "removable-media" property for removable media
29507  *     devices. Parent nexus drivers create a "hotpluggable" property if
29508  *     it supports hotplugging.
29509  *
29510  *     ---------------------------------------------------------------------
29511  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
29512  *     ---------------------------------------------------------------------
29513  *       false            false       |    No                   No
29514  *       false            true        |    No                   Yes
29515  *       true             false       |    Yes                  No
29516  *       true             true        |    Yes                  Yes
29517  *     ---------------------------------------------------------------------
29518  *
29519  *
29520  * 14. Power Management
29521  *
29522  *     sd only power manages removable media devices or devices that support
29523  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
29524  *
29525  *     A parent nexus that supports hotplugging can also set "pm-capable"
29526  *     if the disk can be power managed.
29527  *
29528  *     ------------------------------------------------------------
29529  *       removable media hotpluggable pm-capable  |   power manage
29530  *     ------------------------------------------------------------
29531  *             false          false     false     |     No
29532  *             false          false     true      |     Yes
29533  *             false          true      false     |     No
29534  *             false          true      true      |     Yes
29535  *             true             x        x        |     Yes
29536  *     ------------------------------------------------------------
29537  *
29538  *      USB and firewire hard disks can now be power managed independently
29539  *      of the framebuffer
29540  *
29541  *
29542  * 15. Support for USB disks with capacity larger than 1TB
29543  *
29544  *     Currently, sd doesn't permit a fixed disk device with capacity
29545  *     larger than 1TB to be used in a 32-bit operating system environment.
29546  *     However, sd doesn't do that for removable media devices. Instead, it
29547  *     assumes that removable media devices cannot have a capacity larger
29548  *     than 1TB. Therefore, using those devices on 32-bit system is partially
29549  *     supported, which can cause some unexpected results.
29550  *
29551  *     ---------------------------------------------------------------------
29552  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
29553  *     ---------------------------------------------------------------------
29554  *             false          false  |   true         |     no
29555  *             false          true   |   true         |     no
29556  *             true           false  |   true         |     Yes
29557  *             true           true   |   true         |     Yes
29558  *     ---------------------------------------------------------------------
29559  *
29560  *
29561  * 16. Check write-protection at open time
29562  *
29563  *     When a removable media device is being opened for writing without NDELAY
29564  *     flag, sd will check if this device is writable. If attempting to open
29565  *     without NDELAY flag a write-protected device, this operation will abort.
29566  *
29567  *     ------------------------------------------------------------
29568  *       removable media    USB/1394   |   WP Check
29569  *     ------------------------------------------------------------
29570  *             false          false    |     No
29571  *             false          true     |     No
29572  *             true           false    |     Yes
29573  *             true           true     |     Yes
29574  *     ------------------------------------------------------------
29575  *
29576  *
29577  * 17. syslog when corrupted VTOC is encountered
29578  *
29579  *      Currently, if an invalid VTOC is encountered, sd only print syslog
29580  *      for fixed SCSI disks.
29581  *     ------------------------------------------------------------
29582  *       removable media    USB/1394   |   print syslog
29583  *     ------------------------------------------------------------
29584  *             false          false    |     Yes
29585  *             false          true     |     No
29586  *             true           false    |     No
29587  *             true           true     |     No
29588  *     ------------------------------------------------------------
29589  */
29590 static void
29591 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
29592 {
29593 	int	pm_capable_prop;
29594 
29595 	ASSERT(un->un_sd);
29596 	ASSERT(un->un_sd->sd_inq);
29597 
29598 	/*
29599 	 * Enable SYNC CACHE support for all devices.
29600 	 */
29601 	un->un_f_sync_cache_supported = TRUE;
29602 
29603 	/*
29604 	 * Set the sync cache required flag to false.
29605 	 * This would ensure that there is no SYNC CACHE
29606 	 * sent when there are no writes
29607 	 */
29608 	un->un_f_sync_cache_required = FALSE;
29609 
29610 	if (un->un_sd->sd_inq->inq_rmb) {
29611 		/*
29612 		 * The media of this device is removable. And for this kind
29613 		 * of devices, it is possible to change medium after opening
29614 		 * devices. Thus we should support this operation.
29615 		 */
29616 		un->un_f_has_removable_media = TRUE;
29617 
29618 		/*
29619 		 * support non-512-byte blocksize of removable media devices
29620 		 */
29621 		un->un_f_non_devbsize_supported = TRUE;
29622 
29623 		/*
29624 		 * Assume that all removable media devices support DOOR_LOCK
29625 		 */
29626 		un->un_f_doorlock_supported = TRUE;
29627 
29628 		/*
29629 		 * For a removable media device, it is possible to be opened
29630 		 * with NDELAY flag when there is no media in drive, in this
29631 		 * case we don't care if device is writable. But if without
29632 		 * NDELAY flag, we need to check if media is write-protected.
29633 		 */
29634 		un->un_f_chk_wp_open = TRUE;
29635 
29636 		/*
29637 		 * need to start a SCSI watch thread to monitor media state,
29638 		 * when media is being inserted or ejected, notify syseventd.
29639 		 */
29640 		un->un_f_monitor_media_state = TRUE;
29641 
29642 		/*
29643 		 * Some devices don't support START_STOP_UNIT command.
29644 		 * Therefore, we'd better check if a device supports it
29645 		 * before sending it.
29646 		 */
29647 		un->un_f_check_start_stop = TRUE;
29648 
29649 		/*
29650 		 * support eject media ioctl:
29651 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
29652 		 */
29653 		un->un_f_eject_media_supported = TRUE;
29654 
29655 		/*
29656 		 * Because many removable-media devices don't support
29657 		 * LOG_SENSE, we couldn't use this command to check if
29658 		 * a removable media device support power-management.
29659 		 * We assume that they support power-management via
29660 		 * START_STOP_UNIT command and can be spun up and down
29661 		 * without limitations.
29662 		 */
29663 		un->un_f_pm_supported = TRUE;
29664 
29665 		/*
29666 		 * Need to create a zero length (Boolean) property
29667 		 * removable-media for the removable media devices.
29668 		 * Note that the return value of the property is not being
29669 		 * checked, since if unable to create the property
29670 		 * then do not want the attach to fail altogether. Consistent
29671 		 * with other property creation in attach.
29672 		 */
29673 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
29674 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
29675 
29676 	} else {
29677 		/*
29678 		 * create device ID for device
29679 		 */
29680 		un->un_f_devid_supported = TRUE;
29681 
29682 		/*
29683 		 * Spin up non-removable-media devices once it is attached
29684 		 */
29685 		un->un_f_attach_spinup = TRUE;
29686 
29687 		/*
29688 		 * According to SCSI specification, Sense data has two kinds of
29689 		 * format: fixed format, and descriptor format. At present, we
29690 		 * don't support descriptor format sense data for removable
29691 		 * media.
29692 		 */
29693 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
29694 			un->un_f_descr_format_supported = TRUE;
29695 		}
29696 
29697 		/*
29698 		 * kstats are created only for non-removable media devices.
29699 		 *
29700 		 * Set this in sd.conf to 0 in order to disable kstats.  The
29701 		 * default is 1, so they are enabled by default.
29702 		 */
29703 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
29704 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
29705 		    "enable-partition-kstats", 1));
29706 
29707 		/*
29708 		 * Check if HBA has set the "pm-capable" property.
29709 		 * If "pm-capable" exists and is non-zero then we can
29710 		 * power manage the device without checking the start/stop
29711 		 * cycle count log sense page.
29712 		 *
29713 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
29714 		 * then we should not power manage the device.
29715 		 *
29716 		 * If "pm-capable" doesn't exist then pm_capable_prop will
29717 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
29718 		 * sd will check the start/stop cycle count log sense page
29719 		 * and power manage the device if the cycle count limit has
29720 		 * not been exceeded.
29721 		 */
29722 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
29723 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
29724 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
29725 			un->un_f_log_sense_supported = TRUE;
29726 		} else {
29727 			/*
29728 			 * pm-capable property exists.
29729 			 *
29730 			 * Convert "TRUE" values for pm_capable_prop to
29731 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
29732 			 * later. "TRUE" values are any values except
29733 			 * SD_PM_CAPABLE_FALSE (0) and
29734 			 * SD_PM_CAPABLE_UNDEFINED (-1)
29735 			 */
29736 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
29737 				un->un_f_log_sense_supported = FALSE;
29738 			} else {
29739 				un->un_f_pm_supported = TRUE;
29740 			}
29741 
29742 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
29743 			    "sd_unit_attach: un:0x%p pm-capable "
29744 			    "property set to %d.\n", un, un->un_f_pm_supported);
29745 		}
29746 	}
29747 
29748 	if (un->un_f_is_hotpluggable) {
29749 
29750 		/*
29751 		 * Have to watch hotpluggable devices as well, since
29752 		 * that's the only way for userland applications to
29753 		 * detect hot removal while device is busy/mounted.
29754 		 */
29755 		un->un_f_monitor_media_state = TRUE;
29756 
29757 		un->un_f_check_start_stop = TRUE;
29758 
29759 	}
29760 }
29761 
29762 /*
29763  * sd_tg_rdwr:
29764  * Provides rdwr access for cmlb via sd_tgops. The start_block is
29765  * in sys block size, req_length in bytes.
29766  *
29767  */
29768 static int
29769 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
29770     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
29771 {
29772 	struct sd_lun *un;
29773 	int path_flag = (int)(uintptr_t)tg_cookie;
29774 	char *dkl = NULL;
29775 	diskaddr_t real_addr = start_block;
29776 	diskaddr_t first_byte, end_block;
29777 
29778 	size_t	buffer_size = reqlength;
29779 	int rval = 0;
29780 	diskaddr_t	cap;
29781 	uint32_t	lbasize;
29782 	sd_ssc_t	*ssc;
29783 
29784 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
29785 	if (un == NULL)
29786 		return (ENXIO);
29787 
29788 	if (cmd != TG_READ && cmd != TG_WRITE)
29789 		return (EINVAL);
29790 
29791 	ssc = sd_ssc_init(un);
29792 	mutex_enter(SD_MUTEX(un));
29793 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
29794 		mutex_exit(SD_MUTEX(un));
29795 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
29796 		    &lbasize, path_flag);
29797 		if (rval != 0)
29798 			goto done1;
29799 		mutex_enter(SD_MUTEX(un));
29800 		sd_update_block_info(un, lbasize, cap);
29801 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
29802 			mutex_exit(SD_MUTEX(un));
29803 			rval = EIO;
29804 			goto done;
29805 		}
29806 	}
29807 
29808 	if (NOT_DEVBSIZE(un)) {
29809 		/*
29810 		 * sys_blocksize != tgt_blocksize, need to re-adjust
29811 		 * blkno and save the index to beginning of dk_label
29812 		 */
29813 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
29814 		real_addr = first_byte / un->un_tgt_blocksize;
29815 
29816 		end_block = (first_byte + reqlength +
29817 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
29818 
29819 		/* round up buffer size to multiple of target block size */
29820 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
29821 
29822 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
29823 		    "label_addr: 0x%x allocation size: 0x%x\n",
29824 		    real_addr, buffer_size);
29825 
29826 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
29827 		    (reqlength % un->un_tgt_blocksize) != 0)
29828 			/* the request is not aligned */
29829 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
29830 	}
29831 
29832 	/*
29833 	 * The MMC standard allows READ CAPACITY to be
29834 	 * inaccurate by a bounded amount (in the interest of
29835 	 * response latency).  As a result, failed READs are
29836 	 * commonplace (due to the reading of metadata and not
29837 	 * data). Depending on the per-Vendor/drive Sense data,
29838 	 * the failed READ can cause many (unnecessary) retries.
29839 	 */
29840 
29841 	if (ISCD(un) && (cmd == TG_READ) &&
29842 	    (un->un_f_blockcount_is_valid == TRUE) &&
29843 	    ((start_block == (un->un_blockcount - 1))||
29844 	    (start_block == (un->un_blockcount - 2)))) {
29845 			path_flag = SD_PATH_DIRECT_PRIORITY;
29846 	}
29847 
29848 	mutex_exit(SD_MUTEX(un));
29849 	if (cmd == TG_READ) {
29850 		rval = sd_send_scsi_READ(ssc, (dkl != NULL)? dkl: bufaddr,
29851 		    buffer_size, real_addr, path_flag);
29852 		if (dkl != NULL)
29853 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
29854 			    real_addr), bufaddr, reqlength);
29855 	} else {
29856 		if (dkl) {
29857 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
29858 			    real_addr, path_flag);
29859 			if (rval) {
29860 				goto done1;
29861 			}
29862 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
29863 			    real_addr), reqlength);
29864 		}
29865 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL)? dkl: bufaddr,
29866 		    buffer_size, real_addr, path_flag);
29867 	}
29868 
29869 done1:
29870 	if (dkl != NULL)
29871 		kmem_free(dkl, buffer_size);
29872 
29873 	if (rval != 0) {
29874 		if (rval == EIO)
29875 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
29876 		else
29877 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
29878 	}
29879 done:
29880 	sd_ssc_fini(ssc);
29881 	return (rval);
29882 }
29883 
29884 
29885 static int
29886 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
29887 {
29888 
29889 	struct sd_lun *un;
29890 	diskaddr_t	cap;
29891 	uint32_t	lbasize;
29892 	int		path_flag = (int)(uintptr_t)tg_cookie;
29893 	int		ret = 0;
29894 
29895 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
29896 	if (un == NULL)
29897 		return (ENXIO);
29898 
29899 	switch (cmd) {
29900 	case TG_GETPHYGEOM:
29901 	case TG_GETVIRTGEOM:
29902 	case TG_GETCAPACITY:
29903 	case TG_GETBLOCKSIZE:
29904 		mutex_enter(SD_MUTEX(un));
29905 
29906 		if ((un->un_f_blockcount_is_valid == TRUE) &&
29907 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
29908 			cap = un->un_blockcount;
29909 			lbasize = un->un_tgt_blocksize;
29910 			mutex_exit(SD_MUTEX(un));
29911 		} else {
29912 			sd_ssc_t	*ssc;
29913 			mutex_exit(SD_MUTEX(un));
29914 			ssc = sd_ssc_init(un);
29915 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
29916 			    &lbasize, path_flag);
29917 			if (ret != 0) {
29918 				if (ret == EIO)
29919 					sd_ssc_assessment(ssc,
29920 					    SD_FMT_STATUS_CHECK);
29921 				else
29922 					sd_ssc_assessment(ssc,
29923 					    SD_FMT_IGNORE);
29924 				sd_ssc_fini(ssc);
29925 				return (ret);
29926 			}
29927 			sd_ssc_fini(ssc);
29928 			mutex_enter(SD_MUTEX(un));
29929 			sd_update_block_info(un, lbasize, cap);
29930 			if ((un->un_f_blockcount_is_valid == FALSE) ||
29931 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
29932 				mutex_exit(SD_MUTEX(un));
29933 				return (EIO);
29934 			}
29935 			mutex_exit(SD_MUTEX(un));
29936 		}
29937 
29938 		if (cmd == TG_GETCAPACITY) {
29939 			*(diskaddr_t *)arg = cap;
29940 			return (0);
29941 		}
29942 
29943 		if (cmd == TG_GETBLOCKSIZE) {
29944 			*(uint32_t *)arg = lbasize;
29945 			return (0);
29946 		}
29947 
29948 		if (cmd == TG_GETPHYGEOM)
29949 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
29950 			    cap, lbasize, path_flag);
29951 		else
29952 			/* TG_GETVIRTGEOM */
29953 			ret = sd_get_virtual_geometry(un,
29954 			    (cmlb_geom_t *)arg, cap, lbasize);
29955 
29956 		return (ret);
29957 
29958 	case TG_GETATTR:
29959 		mutex_enter(SD_MUTEX(un));
29960 		((tg_attribute_t *)arg)->media_is_writable =
29961 		    un->un_f_mmc_writable_media;
29962 		mutex_exit(SD_MUTEX(un));
29963 		return (0);
29964 	default:
29965 		return (ENOTTY);
29966 
29967 	}
29968 }
29969 
29970 /*
29971  *    Function: sd_ssc_ereport_post
29972  *
29973  * Description: Will be called when SD driver need to post an ereport.
29974  *
29975  *    Context: Kernel thread or interrupt context.
29976  */
29977 static void
29978 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
29979 {
29980 	int uscsi_path_instance = 0;
29981 	uchar_t	uscsi_pkt_reason;
29982 	uint32_t uscsi_pkt_state;
29983 	uint32_t uscsi_pkt_statistics;
29984 	uint64_t uscsi_ena;
29985 	uchar_t op_code;
29986 	uint8_t *sensep;
29987 	union scsi_cdb *cdbp;
29988 	uint_t cdblen = 0;
29989 	uint_t senlen = 0;
29990 	struct sd_lun *un;
29991 	dev_info_t *dip;
29992 	char *devid;
29993 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
29994 	    SSC_FLAGS_INVALID_STATUS |
29995 	    SSC_FLAGS_INVALID_SENSE |
29996 	    SSC_FLAGS_INVALID_DATA;
29997 	char assessment[16];
29998 
29999 	ASSERT(ssc != NULL);
30000 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
30001 	ASSERT(ssc->ssc_uscsi_info != NULL);
30002 
30003 	un = ssc->ssc_un;
30004 	ASSERT(un != NULL);
30005 
30006 	dip = un->un_sd->sd_dev;
30007 
30008 	/*
30009 	 * Get the devid:
30010 	 *	devid will only be passed to non-transport error reports.
30011 	 */
30012 	devid = DEVI(dip)->devi_devid_str;
30013 
30014 	/*
30015 	 * If we are syncing or dumping, the command will not be executed
30016 	 * so we bypass this situation.
30017 	 */
30018 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
30019 	    (un->un_state == SD_STATE_DUMPING))
30020 		return;
30021 
30022 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
30023 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
30024 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
30025 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
30026 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
30027 
30028 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
30029 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
30030 
30031 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
30032 	if (cdbp == NULL) {
30033 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30034 		    "sd_ssc_ereport_post meet empty cdb\n");
30035 		return;
30036 	}
30037 
30038 	op_code = cdbp->scc_cmd;
30039 
30040 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
30041 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
30042 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
30043 
30044 	if (senlen > 0)
30045 		ASSERT(sensep != NULL);
30046 
30047 	/*
30048 	 * Initialize drv_assess to corresponding values.
30049 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
30050 	 * on the sense-key returned back.
30051 	 */
30052 	switch (drv_assess) {
30053 		case SD_FM_DRV_RECOVERY:
30054 			(void) sprintf(assessment, "%s", "recovered");
30055 			break;
30056 		case SD_FM_DRV_RETRY:
30057 			(void) sprintf(assessment, "%s", "retry");
30058 			break;
30059 		case SD_FM_DRV_NOTICE:
30060 			(void) sprintf(assessment, "%s", "info");
30061 			break;
30062 		case SD_FM_DRV_FATAL:
30063 		default:
30064 			(void) sprintf(assessment, "%s", "unknown");
30065 	}
30066 	/*
30067 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
30068 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
30069 	 * driver-assessment will always be "recovered" here.
30070 	 */
30071 	if (drv_assess == SD_FM_DRV_RECOVERY) {
30072 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30073 		    "cmd.disk.recovered", uscsi_ena, devid, DDI_NOSLEEP,
30074 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30075 		    "driver-assessment", DATA_TYPE_STRING, assessment,
30076 		    "op-code", DATA_TYPE_UINT8, op_code,
30077 		    "cdb", DATA_TYPE_UINT8_ARRAY,
30078 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30079 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30080 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30081 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
30082 		    NULL);
30083 		return;
30084 	}
30085 
30086 	/*
30087 	 * If there is un-expected/un-decodable data, we should post
30088 	 * ereport.io.scsi.cmd.disk.dev.uderr.
30089 	 * driver-assessment will be set based on parameter drv_assess.
30090 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
30091 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
30092 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
30093 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
30094 	 */
30095 	if (ssc->ssc_flags & ssc_invalid_flags) {
30096 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
30097 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30098 			    "cmd.disk.dev.uderr", uscsi_ena, devid, DDI_NOSLEEP,
30099 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30100 			    "driver-assessment", DATA_TYPE_STRING,
30101 			    drv_assess == SD_FM_DRV_FATAL ?
30102 			    "fail" : assessment,
30103 			    "op-code", DATA_TYPE_UINT8, op_code,
30104 			    "cdb", DATA_TYPE_UINT8_ARRAY,
30105 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30106 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30107 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30108 			    "pkt-stats", DATA_TYPE_UINT32,
30109 			    uscsi_pkt_statistics,
30110 			    "stat-code", DATA_TYPE_UINT8,
30111 			    ssc->ssc_uscsi_cmd->uscsi_status,
30112 			    "un-decode-info", DATA_TYPE_STRING,
30113 			    ssc->ssc_info,
30114 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
30115 			    senlen, sensep,
30116 			    NULL);
30117 		} else {
30118 			/*
30119 			 * For other type of invalid data, the
30120 			 * un-decode-value field would be empty because the
30121 			 * un-decodable content could be seen from upper
30122 			 * level payload or inside un-decode-info.
30123 			 */
30124 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30125 			    "cmd.disk.dev.uderr", uscsi_ena, devid, DDI_NOSLEEP,
30126 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30127 			    "driver-assessment", DATA_TYPE_STRING,
30128 			    drv_assess == SD_FM_DRV_FATAL ?
30129 			    "fail" : assessment,
30130 			    "op-code", DATA_TYPE_UINT8, op_code,
30131 			    "cdb", DATA_TYPE_UINT8_ARRAY,
30132 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30133 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30134 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30135 			    "pkt-stats", DATA_TYPE_UINT32,
30136 			    uscsi_pkt_statistics,
30137 			    "stat-code", DATA_TYPE_UINT8,
30138 			    ssc->ssc_uscsi_cmd->uscsi_status,
30139 			    "un-decode-info", DATA_TYPE_STRING,
30140 			    ssc->ssc_info,
30141 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
30142 			    0, NULL,
30143 			    NULL);
30144 		}
30145 		ssc->ssc_flags &= ~ssc_invalid_flags;
30146 		return;
30147 	}
30148 
30149 	if (uscsi_pkt_reason != CMD_CMPLT ||
30150 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
30151 		/*
30152 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
30153 		 * set inside sd_start_cmds due to errors(bad packet or
30154 		 * fatal transport error), we should take it as a
30155 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
30156 		 * driver-assessment will be set based on drv_assess.
30157 		 * We will set devid to NULL because it is a transport
30158 		 * error.
30159 		 */
30160 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
30161 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
30162 
30163 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30164 		    "cmd.disk.tran", uscsi_ena, NULL, DDI_NOSLEEP, FM_VERSION,
30165 		    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30166 		    "driver-assessment", DATA_TYPE_STRING,
30167 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
30168 		    "op-code", DATA_TYPE_UINT8, op_code,
30169 		    "cdb", DATA_TYPE_UINT8_ARRAY,
30170 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30171 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30172 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
30173 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
30174 		    NULL);
30175 	} else {
30176 		/*
30177 		 * If we got here, we have a completed command, and we need
30178 		 * to further investigate the sense data to see what kind
30179 		 * of ereport we should post.
30180 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr
30181 		 * if sense-key == 0x3.
30182 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
30183 		 * driver-assessment will be set based on the parameter
30184 		 * drv_assess.
30185 		 */
30186 		if (senlen > 0) {
30187 			/*
30188 			 * Here we have sense data available.
30189 			 */
30190 			uint8_t sense_key;
30191 			sense_key = scsi_sense_key(sensep);
30192 			if (sense_key == 0x3) {
30193 				/*
30194 				 * sense-key == 0x3(medium error),
30195 				 * driver-assessment should be "fatal" if
30196 				 * drv_assess is SD_FM_DRV_FATAL.
30197 				 */
30198 				scsi_fm_ereport_post(un->un_sd,
30199 				    uscsi_path_instance,
30200 				    "cmd.disk.dev.rqs.merr",
30201 				    uscsi_ena, devid, DDI_NOSLEEP, FM_VERSION,
30202 				    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30203 				    "driver-assessment",
30204 				    DATA_TYPE_STRING,
30205 				    drv_assess == SD_FM_DRV_FATAL ?
30206 				    "fatal" : assessment,
30207 				    "op-code",
30208 				    DATA_TYPE_UINT8, op_code,
30209 				    "cdb",
30210 				    DATA_TYPE_UINT8_ARRAY, cdblen,
30211 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
30212 				    "pkt-reason",
30213 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
30214 				    "pkt-state",
30215 				    DATA_TYPE_UINT8, uscsi_pkt_state,
30216 				    "pkt-stats",
30217 				    DATA_TYPE_UINT32,
30218 				    uscsi_pkt_statistics,
30219 				    "stat-code",
30220 				    DATA_TYPE_UINT8,
30221 				    ssc->ssc_uscsi_cmd->uscsi_status,
30222 				    "key",
30223 				    DATA_TYPE_UINT8,
30224 				    scsi_sense_key(sensep),
30225 				    "asc",
30226 				    DATA_TYPE_UINT8,
30227 				    scsi_sense_asc(sensep),
30228 				    "ascq",
30229 				    DATA_TYPE_UINT8,
30230 				    scsi_sense_ascq(sensep),
30231 				    "sense-data",
30232 				    DATA_TYPE_UINT8_ARRAY,
30233 				    senlen, sensep,
30234 				    "lba",
30235 				    DATA_TYPE_UINT64,
30236 				    ssc->ssc_uscsi_info->ui_lba,
30237 				    NULL);
30238 				} else {
30239 					/*
30240 					 * if sense-key == 0x4(hardware
30241 					 * error), driver-assessment should
30242 					 * be "fatal" if drv_assess is
30243 					 * SD_FM_DRV_FATAL.
30244 					 */
30245 					scsi_fm_ereport_post(un->un_sd,
30246 					    uscsi_path_instance,
30247 					    "cmd.disk.dev.rqs.derr",
30248 					    uscsi_ena, devid, DDI_NOSLEEP,
30249 					    FM_VERSION,
30250 					    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30251 					    "driver-assessment",
30252 					    DATA_TYPE_STRING,
30253 					    drv_assess == SD_FM_DRV_FATAL ?
30254 					    (sense_key == 0x4 ?
30255 					    "fatal" : "fail") : assessment,
30256 					    "op-code",
30257 					    DATA_TYPE_UINT8, op_code,
30258 					    "cdb",
30259 					    DATA_TYPE_UINT8_ARRAY, cdblen,
30260 					    ssc->ssc_uscsi_cmd->uscsi_cdb,
30261 					    "pkt-reason",
30262 					    DATA_TYPE_UINT8, uscsi_pkt_reason,
30263 					    "pkt-state",
30264 					    DATA_TYPE_UINT8, uscsi_pkt_state,
30265 					    "pkt-stats",
30266 					    DATA_TYPE_UINT32,
30267 					    uscsi_pkt_statistics,
30268 					    "stat-code",
30269 					    DATA_TYPE_UINT8,
30270 					    ssc->ssc_uscsi_cmd->uscsi_status,
30271 					    "key",
30272 					    DATA_TYPE_UINT8,
30273 					    scsi_sense_key(sensep),
30274 					    "asc",
30275 					    DATA_TYPE_UINT8,
30276 					    scsi_sense_asc(sensep),
30277 					    "ascq",
30278 					    DATA_TYPE_UINT8,
30279 					    scsi_sense_ascq(sensep),
30280 					    "sense-data",
30281 					    DATA_TYPE_UINT8_ARRAY,
30282 					    senlen, sensep,
30283 					    NULL);
30284 				}
30285 		} else {
30286 			/*
30287 			 * For stat_code == STATUS_GOOD, this is not a
30288 			 * hardware error.
30289 			 */
30290 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
30291 				return;
30292 
30293 			/*
30294 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
30295 			 * stat-code but with sense data unavailable.
30296 			 * driver-assessment will be set based on parameter
30297 			 * drv_assess.
30298 			 */
30299 			scsi_fm_ereport_post(un->un_sd,
30300 			    uscsi_path_instance, "cmd.disk.dev.serr", uscsi_ena,
30301 			    devid, DDI_NOSLEEP, FM_VERSION, DATA_TYPE_UINT8,
30302 			    FM_EREPORT_VERS0,
30303 			    "driver-assessment", DATA_TYPE_STRING,
30304 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
30305 			    "op-code", DATA_TYPE_UINT8, op_code,
30306 			    "cdb",
30307 			    DATA_TYPE_UINT8_ARRAY,
30308 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30309 			    "pkt-reason",
30310 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
30311 			    "pkt-state",
30312 			    DATA_TYPE_UINT8, uscsi_pkt_state,
30313 			    "pkt-stats",
30314 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
30315 			    "stat-code",
30316 			    DATA_TYPE_UINT8,
30317 			    ssc->ssc_uscsi_cmd->uscsi_status,
30318 			    NULL);
30319 		}
30320 	}
30321 }
30322 
30323 /*
30324  *     Function: sd_ssc_extract_info
30325  *
30326  * Description: Extract information available to help generate ereport.
30327  *
30328  *     Context: Kernel thread or interrupt context.
30329  */
30330 static void
30331 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
30332     struct buf *bp, struct sd_xbuf *xp)
30333 {
30334 	size_t senlen = 0;
30335 	union scsi_cdb *cdbp;
30336 	int path_instance;
30337 	/*
30338 	 * Need scsi_cdb_size array to determine the cdb length.
30339 	 */
30340 	extern uchar_t	scsi_cdb_size[];
30341 
30342 	ASSERT(un != NULL);
30343 	ASSERT(pktp != NULL);
30344 	ASSERT(bp != NULL);
30345 	ASSERT(xp != NULL);
30346 	ASSERT(ssc != NULL);
30347 	ASSERT(mutex_owned(SD_MUTEX(un)));
30348 
30349 	/*
30350 	 * Transfer the cdb buffer pointer here.
30351 	 */
30352 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
30353 
30354 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
30355 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
30356 
30357 	/*
30358 	 * Transfer the sense data buffer pointer if sense data is available,
30359 	 * calculate the sense data length first.
30360 	 */
30361 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
30362 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
30363 		/*
30364 		 * For arq case, we will enter here.
30365 		 */
30366 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
30367 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
30368 		} else {
30369 			senlen = SENSE_LENGTH;
30370 		}
30371 	} else {
30372 		/*
30373 		 * For non-arq case, we will enter this branch.
30374 		 */
30375 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
30376 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
30377 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
30378 		}
30379 
30380 	}
30381 
30382 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
30383 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
30384 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
30385 
30386 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
30387 
30388 	/*
30389 	 * Only transfer path_instance when scsi_pkt was properly allocated.
30390 	 */
30391 	path_instance = pktp->pkt_path_instance;
30392 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
30393 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
30394 	else
30395 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
30396 
30397 	/*
30398 	 * Copy in the other fields we may need when posting ereport.
30399 	 */
30400 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
30401 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
30402 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
30403 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
30404 
30405 	/*
30406 	 * For partially read/write command, we will not create ena
30407 	 * in case of a successful command be reconized as recovered.
30408 	 */
30409 	if ((pktp->pkt_reason == CMD_CMPLT) &&
30410 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
30411 	    (senlen == 0)) {
30412 		return;
30413 	}
30414 
30415 	/*
30416 	 * To associate ereports of a single command execution flow, we
30417 	 * need a shared ena for a specific command.
30418 	 */
30419 	if (xp->xb_ena == 0)
30420 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
30421 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
30422 }
30423