xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 3b22643d)
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 			/* let cmlb handle it */
21310 			goto skip_ready_valid;
21311 
21312 		case CDROMPAUSE:
21313 		case CDROMRESUME:
21314 		case CDROMPLAYMSF:
21315 		case CDROMPLAYTRKIND:
21316 		case CDROMREADTOCHDR:
21317 		case CDROMREADTOCENTRY:
21318 		case CDROMSTOP:
21319 		case CDROMSTART:
21320 		case CDROMVOLCTRL:
21321 		case CDROMSUBCHNL:
21322 		case CDROMREADMODE2:
21323 		case CDROMREADMODE1:
21324 		case CDROMREADOFFSET:
21325 		case CDROMSBLKMODE:
21326 		case CDROMGBLKMODE:
21327 		case CDROMGDRVSPEED:
21328 		case CDROMSDRVSPEED:
21329 		case CDROMCDDA:
21330 		case CDROMCDXA:
21331 		case CDROMSUBCODE:
21332 			if (!ISCD(un)) {
21333 				un->un_ncmds_in_driver--;
21334 				ASSERT(un->un_ncmds_in_driver >= 0);
21335 				mutex_exit(SD_MUTEX(un));
21336 				err = ENOTTY;
21337 				goto done_without_assess;
21338 			}
21339 			break;
21340 		case FDEJECT:
21341 		case DKIOCEJECT:
21342 		case CDROMEJECT:
21343 			if (!un->un_f_eject_media_supported) {
21344 				un->un_ncmds_in_driver--;
21345 				ASSERT(un->un_ncmds_in_driver >= 0);
21346 				mutex_exit(SD_MUTEX(un));
21347 				err = ENOTTY;
21348 				goto done_without_assess;
21349 			}
21350 			break;
21351 		case DKIOCFLUSHWRITECACHE:
21352 			mutex_exit(SD_MUTEX(un));
21353 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
21354 			if (err != 0) {
21355 				mutex_enter(SD_MUTEX(un));
21356 				un->un_ncmds_in_driver--;
21357 				ASSERT(un->un_ncmds_in_driver >= 0);
21358 				mutex_exit(SD_MUTEX(un));
21359 				err = EIO;
21360 				goto done_quick_assess;
21361 			}
21362 			mutex_enter(SD_MUTEX(un));
21363 			/* FALLTHROUGH */
21364 		case DKIOCREMOVABLE:
21365 		case DKIOCHOTPLUGGABLE:
21366 		case DKIOCINFO:
21367 		case DKIOCGMEDIAINFO:
21368 		case MHIOCENFAILFAST:
21369 		case MHIOCSTATUS:
21370 		case MHIOCTKOWN:
21371 		case MHIOCRELEASE:
21372 		case MHIOCGRP_INKEYS:
21373 		case MHIOCGRP_INRESV:
21374 		case MHIOCGRP_REGISTER:
21375 		case MHIOCGRP_RESERVE:
21376 		case MHIOCGRP_PREEMPTANDABORT:
21377 		case MHIOCGRP_REGISTERANDIGNOREKEY:
21378 		case CDROMCLOSETRAY:
21379 		case USCSICMD:
21380 			goto skip_ready_valid;
21381 		default:
21382 			break;
21383 		}
21384 
21385 		mutex_exit(SD_MUTEX(un));
21386 		err = sd_ready_and_valid(ssc, SDPART(dev));
21387 		mutex_enter(SD_MUTEX(un));
21388 
21389 		if (err != SD_READY_VALID) {
21390 			switch (cmd) {
21391 			case DKIOCSTATE:
21392 			case CDROMGDRVSPEED:
21393 			case CDROMSDRVSPEED:
21394 			case FDEJECT:	/* for eject command */
21395 			case DKIOCEJECT:
21396 			case CDROMEJECT:
21397 			case DKIOCREMOVABLE:
21398 			case DKIOCHOTPLUGGABLE:
21399 				break;
21400 			default:
21401 				if (un->un_f_has_removable_media) {
21402 					err = ENXIO;
21403 				} else {
21404 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
21405 					if (err == SD_RESERVED_BY_OTHERS) {
21406 						err = EACCES;
21407 					} else {
21408 						err = EIO;
21409 					}
21410 				}
21411 				un->un_ncmds_in_driver--;
21412 				ASSERT(un->un_ncmds_in_driver >= 0);
21413 				mutex_exit(SD_MUTEX(un));
21414 
21415 				goto done_without_assess;
21416 			}
21417 		}
21418 	}
21419 
21420 skip_ready_valid:
21421 	mutex_exit(SD_MUTEX(un));
21422 
21423 	switch (cmd) {
21424 	case DKIOCINFO:
21425 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
21426 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
21427 		break;
21428 
21429 	case DKIOCGMEDIAINFO:
21430 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
21431 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
21432 		break;
21433 
21434 	case DKIOCGGEOM:
21435 	case DKIOCGVTOC:
21436 	case DKIOCGEXTVTOC:
21437 	case DKIOCGAPART:
21438 	case DKIOCPARTINFO:
21439 	case DKIOCEXTPARTINFO:
21440 	case DKIOCSGEOM:
21441 	case DKIOCSAPART:
21442 	case DKIOCGETEFI:
21443 	case DKIOCPARTITION:
21444 	case DKIOCSVTOC:
21445 	case DKIOCSEXTVTOC:
21446 	case DKIOCSETEFI:
21447 	case DKIOCGMBOOT:
21448 	case DKIOCSMBOOT:
21449 	case DKIOCG_PHYGEOM:
21450 	case DKIOCG_VIRTGEOM:
21451 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
21452 
21453 		/* TUR should spin up */
21454 
21455 		if (un->un_f_has_removable_media)
21456 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
21457 			    SD_CHECK_FOR_MEDIA);
21458 
21459 		else
21460 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
21461 
21462 		if (err != 0)
21463 			goto done_with_assess;
21464 
21465 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
21466 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
21467 
21468 		if ((err == 0) &&
21469 		    ((cmd == DKIOCSETEFI) ||
21470 		    (un->un_f_pkstats_enabled) &&
21471 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
21472 		    cmd == DKIOCSEXTVTOC))) {
21473 
21474 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
21475 			    (void *)SD_PATH_DIRECT);
21476 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
21477 				sd_set_pstats(un);
21478 				SD_TRACE(SD_LOG_IO_PARTITION, un,
21479 				    "sd_ioctl: un:0x%p pstats created and "
21480 				    "set\n", un);
21481 			}
21482 		}
21483 
21484 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
21485 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
21486 
21487 			mutex_enter(SD_MUTEX(un));
21488 			if (un->un_f_devid_supported &&
21489 			    (un->un_f_opt_fab_devid == TRUE)) {
21490 				if (un->un_devid == NULL) {
21491 					sd_register_devid(ssc, SD_DEVINFO(un),
21492 					    SD_TARGET_IS_UNRESERVED);
21493 				} else {
21494 					/*
21495 					 * The device id for this disk
21496 					 * has been fabricated. The
21497 					 * device id must be preserved
21498 					 * by writing it back out to
21499 					 * disk.
21500 					 */
21501 					if (sd_write_deviceid(ssc) != 0) {
21502 						ddi_devid_free(un->un_devid);
21503 						un->un_devid = NULL;
21504 					}
21505 				}
21506 			}
21507 			mutex_exit(SD_MUTEX(un));
21508 		}
21509 
21510 		break;
21511 
21512 	case DKIOCLOCK:
21513 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
21514 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
21515 		    SD_PATH_STANDARD);
21516 		goto done_with_assess;
21517 
21518 	case DKIOCUNLOCK:
21519 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
21520 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
21521 		    SD_PATH_STANDARD);
21522 		goto done_with_assess;
21523 
21524 	case DKIOCSTATE: {
21525 		enum dkio_state		state;
21526 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
21527 
21528 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
21529 			err = EFAULT;
21530 		} else {
21531 			err = sd_check_media(dev, state);
21532 			if (err == 0) {
21533 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
21534 				    sizeof (int), flag) != 0)
21535 					err = EFAULT;
21536 			}
21537 		}
21538 		break;
21539 	}
21540 
21541 	case DKIOCREMOVABLE:
21542 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
21543 		i = un->un_f_has_removable_media ? 1 : 0;
21544 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
21545 			err = EFAULT;
21546 		} else {
21547 			err = 0;
21548 		}
21549 		break;
21550 
21551 	case DKIOCHOTPLUGGABLE:
21552 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
21553 		i = un->un_f_is_hotpluggable ? 1 : 0;
21554 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
21555 			err = EFAULT;
21556 		} else {
21557 			err = 0;
21558 		}
21559 		break;
21560 
21561 	case DKIOCGTEMPERATURE:
21562 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
21563 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
21564 		break;
21565 
21566 	case MHIOCENFAILFAST:
21567 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
21568 		if ((err = drv_priv(cred_p)) == 0) {
21569 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
21570 		}
21571 		break;
21572 
21573 	case MHIOCTKOWN:
21574 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
21575 		if ((err = drv_priv(cred_p)) == 0) {
21576 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
21577 		}
21578 		break;
21579 
21580 	case MHIOCRELEASE:
21581 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
21582 		if ((err = drv_priv(cred_p)) == 0) {
21583 			err = sd_mhdioc_release(dev);
21584 		}
21585 		break;
21586 
21587 	case MHIOCSTATUS:
21588 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
21589 		if ((err = drv_priv(cred_p)) == 0) {
21590 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
21591 			case 0:
21592 				err = 0;
21593 				break;
21594 			case EACCES:
21595 				*rval_p = 1;
21596 				err = 0;
21597 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
21598 				break;
21599 			default:
21600 				err = EIO;
21601 				goto done_with_assess;
21602 			}
21603 		}
21604 		break;
21605 
21606 	case MHIOCQRESERVE:
21607 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
21608 		if ((err = drv_priv(cred_p)) == 0) {
21609 			err = sd_reserve_release(dev, SD_RESERVE);
21610 		}
21611 		break;
21612 
21613 	case MHIOCREREGISTERDEVID:
21614 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
21615 		if (drv_priv(cred_p) == EPERM) {
21616 			err = EPERM;
21617 		} else if (!un->un_f_devid_supported) {
21618 			err = ENOTTY;
21619 		} else {
21620 			err = sd_mhdioc_register_devid(dev);
21621 		}
21622 		break;
21623 
21624 	case MHIOCGRP_INKEYS:
21625 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
21626 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
21627 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21628 				err = ENOTSUP;
21629 			} else {
21630 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
21631 				    flag);
21632 			}
21633 		}
21634 		break;
21635 
21636 	case MHIOCGRP_INRESV:
21637 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
21638 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
21639 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21640 				err = ENOTSUP;
21641 			} else {
21642 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
21643 			}
21644 		}
21645 		break;
21646 
21647 	case MHIOCGRP_REGISTER:
21648 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
21649 		if ((err = drv_priv(cred_p)) != EPERM) {
21650 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21651 				err = ENOTSUP;
21652 			} else if (arg != NULL) {
21653 				mhioc_register_t reg;
21654 				if (ddi_copyin((void *)arg, &reg,
21655 				    sizeof (mhioc_register_t), flag) != 0) {
21656 					err = EFAULT;
21657 				} else {
21658 					err =
21659 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21660 					    ssc, SD_SCSI3_REGISTER,
21661 					    (uchar_t *)&reg);
21662 					if (err != 0)
21663 						goto done_with_assess;
21664 				}
21665 			}
21666 		}
21667 		break;
21668 
21669 	case MHIOCGRP_RESERVE:
21670 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
21671 		if ((err = drv_priv(cred_p)) != EPERM) {
21672 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21673 				err = ENOTSUP;
21674 			} else if (arg != NULL) {
21675 				mhioc_resv_desc_t resv_desc;
21676 				if (ddi_copyin((void *)arg, &resv_desc,
21677 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
21678 					err = EFAULT;
21679 				} else {
21680 					err =
21681 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21682 					    ssc, SD_SCSI3_RESERVE,
21683 					    (uchar_t *)&resv_desc);
21684 					if (err != 0)
21685 						goto done_with_assess;
21686 				}
21687 			}
21688 		}
21689 		break;
21690 
21691 	case MHIOCGRP_PREEMPTANDABORT:
21692 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
21693 		if ((err = drv_priv(cred_p)) != EPERM) {
21694 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21695 				err = ENOTSUP;
21696 			} else if (arg != NULL) {
21697 				mhioc_preemptandabort_t preempt_abort;
21698 				if (ddi_copyin((void *)arg, &preempt_abort,
21699 				    sizeof (mhioc_preemptandabort_t),
21700 				    flag) != 0) {
21701 					err = EFAULT;
21702 				} else {
21703 					err =
21704 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21705 					    ssc, SD_SCSI3_PREEMPTANDABORT,
21706 					    (uchar_t *)&preempt_abort);
21707 					if (err != 0)
21708 						goto done_with_assess;
21709 				}
21710 			}
21711 		}
21712 		break;
21713 
21714 	case MHIOCGRP_REGISTERANDIGNOREKEY:
21715 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
21716 		if ((err = drv_priv(cred_p)) != EPERM) {
21717 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
21718 				err = ENOTSUP;
21719 			} else if (arg != NULL) {
21720 				mhioc_registerandignorekey_t r_and_i;
21721 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
21722 				    sizeof (mhioc_registerandignorekey_t),
21723 				    flag) != 0) {
21724 					err = EFAULT;
21725 				} else {
21726 					err =
21727 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
21728 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
21729 					    (uchar_t *)&r_and_i);
21730 					if (err != 0)
21731 						goto done_with_assess;
21732 				}
21733 			}
21734 		}
21735 		break;
21736 
21737 	case USCSICMD:
21738 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
21739 		cr = ddi_get_cred();
21740 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
21741 			err = EPERM;
21742 		} else {
21743 			enum uio_seg	uioseg;
21744 
21745 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
21746 			    UIO_USERSPACE;
21747 			if (un->un_f_format_in_progress == TRUE) {
21748 				err = EAGAIN;
21749 				break;
21750 			}
21751 
21752 			err = sd_ssc_send(ssc,
21753 			    (struct uscsi_cmd *)arg,
21754 			    flag, uioseg, SD_PATH_STANDARD);
21755 			if (err != 0)
21756 				goto done_with_assess;
21757 			else
21758 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21759 		}
21760 		break;
21761 
21762 	case CDROMPAUSE:
21763 	case CDROMRESUME:
21764 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
21765 		if (!ISCD(un)) {
21766 			err = ENOTTY;
21767 		} else {
21768 			err = sr_pause_resume(dev, cmd);
21769 		}
21770 		break;
21771 
21772 	case CDROMPLAYMSF:
21773 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
21774 		if (!ISCD(un)) {
21775 			err = ENOTTY;
21776 		} else {
21777 			err = sr_play_msf(dev, (caddr_t)arg, flag);
21778 		}
21779 		break;
21780 
21781 	case CDROMPLAYTRKIND:
21782 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
21783 #if defined(__i386) || defined(__amd64)
21784 		/*
21785 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
21786 		 */
21787 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
21788 #else
21789 		if (!ISCD(un)) {
21790 #endif
21791 			err = ENOTTY;
21792 		} else {
21793 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
21794 		}
21795 		break;
21796 
21797 	case CDROMREADTOCHDR:
21798 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
21799 		if (!ISCD(un)) {
21800 			err = ENOTTY;
21801 		} else {
21802 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
21803 		}
21804 		break;
21805 
21806 	case CDROMREADTOCENTRY:
21807 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
21808 		if (!ISCD(un)) {
21809 			err = ENOTTY;
21810 		} else {
21811 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
21812 		}
21813 		break;
21814 
21815 	case CDROMSTOP:
21816 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
21817 		if (!ISCD(un)) {
21818 			err = ENOTTY;
21819 		} else {
21820 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_STOP,
21821 			    SD_PATH_STANDARD);
21822 			goto done_with_assess;
21823 		}
21824 		break;
21825 
21826 	case CDROMSTART:
21827 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
21828 		if (!ISCD(un)) {
21829 			err = ENOTTY;
21830 		} else {
21831 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_START,
21832 			    SD_PATH_STANDARD);
21833 			goto done_with_assess;
21834 		}
21835 		break;
21836 
21837 	case CDROMCLOSETRAY:
21838 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
21839 		if (!ISCD(un)) {
21840 			err = ENOTTY;
21841 		} else {
21842 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_CLOSE,
21843 			    SD_PATH_STANDARD);
21844 			goto done_with_assess;
21845 		}
21846 		break;
21847 
21848 	case FDEJECT:	/* for eject command */
21849 	case DKIOCEJECT:
21850 	case CDROMEJECT:
21851 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
21852 		if (!un->un_f_eject_media_supported) {
21853 			err = ENOTTY;
21854 		} else {
21855 			err = sr_eject(dev);
21856 		}
21857 		break;
21858 
21859 	case CDROMVOLCTRL:
21860 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
21861 		if (!ISCD(un)) {
21862 			err = ENOTTY;
21863 		} else {
21864 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
21865 		}
21866 		break;
21867 
21868 	case CDROMSUBCHNL:
21869 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
21870 		if (!ISCD(un)) {
21871 			err = ENOTTY;
21872 		} else {
21873 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
21874 		}
21875 		break;
21876 
21877 	case CDROMREADMODE2:
21878 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
21879 		if (!ISCD(un)) {
21880 			err = ENOTTY;
21881 		} else if (un->un_f_cfg_is_atapi == TRUE) {
21882 			/*
21883 			 * If the drive supports READ CD, use that instead of
21884 			 * switching the LBA size via a MODE SELECT
21885 			 * Block Descriptor
21886 			 */
21887 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
21888 		} else {
21889 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
21890 		}
21891 		break;
21892 
21893 	case CDROMREADMODE1:
21894 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
21895 		if (!ISCD(un)) {
21896 			err = ENOTTY;
21897 		} else {
21898 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
21899 		}
21900 		break;
21901 
21902 	case CDROMREADOFFSET:
21903 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
21904 		if (!ISCD(un)) {
21905 			err = ENOTTY;
21906 		} else {
21907 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
21908 			    flag);
21909 		}
21910 		break;
21911 
21912 	case CDROMSBLKMODE:
21913 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
21914 		/*
21915 		 * There is no means of changing block size in case of atapi
21916 		 * drives, thus return ENOTTY if drive type is atapi
21917 		 */
21918 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
21919 			err = ENOTTY;
21920 		} else if (un->un_f_mmc_cap == TRUE) {
21921 
21922 			/*
21923 			 * MMC Devices do not support changing the
21924 			 * logical block size
21925 			 *
21926 			 * Note: EINVAL is being returned instead of ENOTTY to
21927 			 * maintain consistancy with the original mmc
21928 			 * driver update.
21929 			 */
21930 			err = EINVAL;
21931 		} else {
21932 			mutex_enter(SD_MUTEX(un));
21933 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
21934 			    (un->un_ncmds_in_transport > 0)) {
21935 				mutex_exit(SD_MUTEX(un));
21936 				err = EINVAL;
21937 			} else {
21938 				mutex_exit(SD_MUTEX(un));
21939 				err = sr_change_blkmode(dev, cmd, arg, flag);
21940 			}
21941 		}
21942 		break;
21943 
21944 	case CDROMGBLKMODE:
21945 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
21946 		if (!ISCD(un)) {
21947 			err = ENOTTY;
21948 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
21949 		    (un->un_f_blockcount_is_valid != FALSE)) {
21950 			/*
21951 			 * Drive is an ATAPI drive so return target block
21952 			 * size for ATAPI drives since we cannot change the
21953 			 * blocksize on ATAPI drives. Used primarily to detect
21954 			 * if an ATAPI cdrom is present.
21955 			 */
21956 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
21957 			    sizeof (int), flag) != 0) {
21958 				err = EFAULT;
21959 			} else {
21960 				err = 0;
21961 			}
21962 
21963 		} else {
21964 			/*
21965 			 * Drive supports changing block sizes via a Mode
21966 			 * Select.
21967 			 */
21968 			err = sr_change_blkmode(dev, cmd, arg, flag);
21969 		}
21970 		break;
21971 
21972 	case CDROMGDRVSPEED:
21973 	case CDROMSDRVSPEED:
21974 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
21975 		if (!ISCD(un)) {
21976 			err = ENOTTY;
21977 		} else if (un->un_f_mmc_cap == TRUE) {
21978 			/*
21979 			 * Note: In the future the driver implementation
21980 			 * for getting and
21981 			 * setting cd speed should entail:
21982 			 * 1) If non-mmc try the Toshiba mode page
21983 			 *    (sr_change_speed)
21984 			 * 2) If mmc but no support for Real Time Streaming try
21985 			 *    the SET CD SPEED (0xBB) command
21986 			 *   (sr_atapi_change_speed)
21987 			 * 3) If mmc and support for Real Time Streaming
21988 			 *    try the GET PERFORMANCE and SET STREAMING
21989 			 *    commands (not yet implemented, 4380808)
21990 			 */
21991 			/*
21992 			 * As per recent MMC spec, CD-ROM speed is variable
21993 			 * and changes with LBA. Since there is no such
21994 			 * things as drive speed now, fail this ioctl.
21995 			 *
21996 			 * Note: EINVAL is returned for consistancy of original
21997 			 * implementation which included support for getting
21998 			 * the drive speed of mmc devices but not setting
21999 			 * the drive speed. Thus EINVAL would be returned
22000 			 * if a set request was made for an mmc device.
22001 			 * We no longer support get or set speed for
22002 			 * mmc but need to remain consistent with regard
22003 			 * to the error code returned.
22004 			 */
22005 			err = EINVAL;
22006 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22007 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
22008 		} else {
22009 			err = sr_change_speed(dev, cmd, arg, flag);
22010 		}
22011 		break;
22012 
22013 	case CDROMCDDA:
22014 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
22015 		if (!ISCD(un)) {
22016 			err = ENOTTY;
22017 		} else {
22018 			err = sr_read_cdda(dev, (void *)arg, flag);
22019 		}
22020 		break;
22021 
22022 	case CDROMCDXA:
22023 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
22024 		if (!ISCD(un)) {
22025 			err = ENOTTY;
22026 		} else {
22027 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
22028 		}
22029 		break;
22030 
22031 	case CDROMSUBCODE:
22032 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
22033 		if (!ISCD(un)) {
22034 			err = ENOTTY;
22035 		} else {
22036 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
22037 		}
22038 		break;
22039 
22040 
22041 #ifdef SDDEBUG
22042 /* RESET/ABORTS testing ioctls */
22043 	case DKIOCRESET: {
22044 		int	reset_level;
22045 
22046 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
22047 			err = EFAULT;
22048 		} else {
22049 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
22050 			    "reset_level = 0x%lx\n", reset_level);
22051 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
22052 				err = 0;
22053 			} else {
22054 				err = EIO;
22055 			}
22056 		}
22057 		break;
22058 	}
22059 
22060 	case DKIOCABORT:
22061 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
22062 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
22063 			err = 0;
22064 		} else {
22065 			err = EIO;
22066 		}
22067 		break;
22068 #endif
22069 
22070 #ifdef SD_FAULT_INJECTION
22071 /* SDIOC FaultInjection testing ioctls */
22072 	case SDIOCSTART:
22073 	case SDIOCSTOP:
22074 	case SDIOCINSERTPKT:
22075 	case SDIOCINSERTXB:
22076 	case SDIOCINSERTUN:
22077 	case SDIOCINSERTARQ:
22078 	case SDIOCPUSH:
22079 	case SDIOCRETRIEVE:
22080 	case SDIOCRUN:
22081 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
22082 		    "SDIOC detected cmd:0x%X:\n", cmd);
22083 		/* call error generator */
22084 		sd_faultinjection_ioctl(cmd, arg, un);
22085 		err = 0;
22086 		break;
22087 
22088 #endif /* SD_FAULT_INJECTION */
22089 
22090 	case DKIOCFLUSHWRITECACHE:
22091 		{
22092 			struct dk_callback *dkc = (struct dk_callback *)arg;
22093 
22094 			mutex_enter(SD_MUTEX(un));
22095 			if (!un->un_f_sync_cache_supported ||
22096 			    !un->un_f_write_cache_enabled) {
22097 				err = un->un_f_sync_cache_supported ?
22098 				    0 : ENOTSUP;
22099 				mutex_exit(SD_MUTEX(un));
22100 				if ((flag & FKIOCTL) && dkc != NULL &&
22101 				    dkc->dkc_callback != NULL) {
22102 					(*dkc->dkc_callback)(dkc->dkc_cookie,
22103 					    err);
22104 					/*
22105 					 * Did callback and reported error.
22106 					 * Since we did a callback, ioctl
22107 					 * should return 0.
22108 					 */
22109 					err = 0;
22110 				}
22111 				break;
22112 			}
22113 			mutex_exit(SD_MUTEX(un));
22114 
22115 			if ((flag & FKIOCTL) && dkc != NULL &&
22116 			    dkc->dkc_callback != NULL) {
22117 				/* async SYNC CACHE request */
22118 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
22119 			} else {
22120 				/* synchronous SYNC CACHE request */
22121 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
22122 			}
22123 		}
22124 		break;
22125 
22126 	case DKIOCGETWCE: {
22127 
22128 		int wce;
22129 
22130 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
22131 			break;
22132 		}
22133 
22134 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
22135 			err = EFAULT;
22136 		}
22137 		break;
22138 	}
22139 
22140 	case DKIOCSETWCE: {
22141 
22142 		int wce, sync_supported;
22143 
22144 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
22145 			err = EFAULT;
22146 			break;
22147 		}
22148 
22149 		/*
22150 		 * Synchronize multiple threads trying to enable
22151 		 * or disable the cache via the un_f_wcc_cv
22152 		 * condition variable.
22153 		 */
22154 		mutex_enter(SD_MUTEX(un));
22155 
22156 		/*
22157 		 * Don't allow the cache to be enabled if the
22158 		 * config file has it disabled.
22159 		 */
22160 		if (un->un_f_opt_disable_cache && wce) {
22161 			mutex_exit(SD_MUTEX(un));
22162 			err = EINVAL;
22163 			break;
22164 		}
22165 
22166 		/*
22167 		 * Wait for write cache change in progress
22168 		 * bit to be clear before proceeding.
22169 		 */
22170 		while (un->un_f_wcc_inprog)
22171 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
22172 
22173 		un->un_f_wcc_inprog = 1;
22174 
22175 		if (un->un_f_write_cache_enabled && wce == 0) {
22176 			/*
22177 			 * Disable the write cache.  Don't clear
22178 			 * un_f_write_cache_enabled until after
22179 			 * the mode select and flush are complete.
22180 			 */
22181 			sync_supported = un->un_f_sync_cache_supported;
22182 
22183 			/*
22184 			 * If cache flush is suppressed, we assume that the
22185 			 * controller firmware will take care of managing the
22186 			 * write cache for us: no need to explicitly
22187 			 * disable it.
22188 			 */
22189 			if (!un->un_f_suppress_cache_flush) {
22190 				mutex_exit(SD_MUTEX(un));
22191 				if ((err = sd_cache_control(ssc,
22192 				    SD_CACHE_NOCHANGE,
22193 				    SD_CACHE_DISABLE)) == 0 &&
22194 				    sync_supported) {
22195 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
22196 					    NULL);
22197 				}
22198 			} else {
22199 				mutex_exit(SD_MUTEX(un));
22200 			}
22201 
22202 			mutex_enter(SD_MUTEX(un));
22203 			if (err == 0) {
22204 				un->un_f_write_cache_enabled = 0;
22205 			}
22206 
22207 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
22208 			/*
22209 			 * Set un_f_write_cache_enabled first, so there is
22210 			 * no window where the cache is enabled, but the
22211 			 * bit says it isn't.
22212 			 */
22213 			un->un_f_write_cache_enabled = 1;
22214 
22215 			/*
22216 			 * If cache flush is suppressed, we assume that the
22217 			 * controller firmware will take care of managing the
22218 			 * write cache for us: no need to explicitly
22219 			 * enable it.
22220 			 */
22221 			if (!un->un_f_suppress_cache_flush) {
22222 				mutex_exit(SD_MUTEX(un));
22223 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
22224 				    SD_CACHE_ENABLE);
22225 			} else {
22226 				mutex_exit(SD_MUTEX(un));
22227 			}
22228 
22229 			mutex_enter(SD_MUTEX(un));
22230 
22231 			if (err) {
22232 				un->un_f_write_cache_enabled = 0;
22233 			}
22234 		}
22235 
22236 		un->un_f_wcc_inprog = 0;
22237 		cv_broadcast(&un->un_wcc_cv);
22238 		mutex_exit(SD_MUTEX(un));
22239 		break;
22240 	}
22241 
22242 	default:
22243 		err = ENOTTY;
22244 		break;
22245 	}
22246 	mutex_enter(SD_MUTEX(un));
22247 	un->un_ncmds_in_driver--;
22248 	ASSERT(un->un_ncmds_in_driver >= 0);
22249 	mutex_exit(SD_MUTEX(un));
22250 
22251 
22252 done_without_assess:
22253 	sd_ssc_fini(ssc);
22254 
22255 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
22256 	return (err);
22257 
22258 done_with_assess:
22259 	mutex_enter(SD_MUTEX(un));
22260 	un->un_ncmds_in_driver--;
22261 	ASSERT(un->un_ncmds_in_driver >= 0);
22262 	mutex_exit(SD_MUTEX(un));
22263 
22264 done_quick_assess:
22265 	if (err != 0)
22266 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22267 	/* Uninitialize sd_ssc_t pointer */
22268 	sd_ssc_fini(ssc);
22269 
22270 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
22271 	return (err);
22272 }
22273 
22274 
22275 /*
22276  *    Function: sd_dkio_ctrl_info
22277  *
22278  * Description: This routine is the driver entry point for handling controller
22279  *		information ioctl requests (DKIOCINFO).
22280  *
22281  *   Arguments: dev  - the device number
22282  *		arg  - pointer to user provided dk_cinfo structure
22283  *		       specifying the controller type and attributes.
22284  *		flag - this argument is a pass through to ddi_copyxxx()
22285  *		       directly from the mode argument of ioctl().
22286  *
22287  * Return Code: 0
22288  *		EFAULT
22289  *		ENXIO
22290  */
22291 
22292 static int
22293 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
22294 {
22295 	struct sd_lun	*un = NULL;
22296 	struct dk_cinfo	*info;
22297 	dev_info_t	*pdip;
22298 	int		lun, tgt;
22299 
22300 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22301 		return (ENXIO);
22302 	}
22303 
22304 	info = (struct dk_cinfo *)
22305 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
22306 
22307 	switch (un->un_ctype) {
22308 	case CTYPE_CDROM:
22309 		info->dki_ctype = DKC_CDROM;
22310 		break;
22311 	default:
22312 		info->dki_ctype = DKC_SCSI_CCS;
22313 		break;
22314 	}
22315 	pdip = ddi_get_parent(SD_DEVINFO(un));
22316 	info->dki_cnum = ddi_get_instance(pdip);
22317 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
22318 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
22319 	} else {
22320 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
22321 		    DK_DEVLEN - 1);
22322 	}
22323 
22324 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22325 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
22326 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
22327 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
22328 
22329 	/* Unit Information */
22330 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
22331 	info->dki_slave = ((tgt << 3) | lun);
22332 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
22333 	    DK_DEVLEN - 1);
22334 	info->dki_flags = DKI_FMTVOL;
22335 	info->dki_partition = SDPART(dev);
22336 
22337 	/* Max Transfer size of this device in blocks */
22338 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
22339 	info->dki_addr = 0;
22340 	info->dki_space = 0;
22341 	info->dki_prio = 0;
22342 	info->dki_vec = 0;
22343 
22344 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
22345 		kmem_free(info, sizeof (struct dk_cinfo));
22346 		return (EFAULT);
22347 	} else {
22348 		kmem_free(info, sizeof (struct dk_cinfo));
22349 		return (0);
22350 	}
22351 }
22352 
22353 
22354 /*
22355  *    Function: sd_get_media_info
22356  *
22357  * Description: This routine is the driver entry point for handling ioctl
22358  *		requests for the media type or command set profile used by the
22359  *		drive to operate on the media (DKIOCGMEDIAINFO).
22360  *
22361  *   Arguments: dev	- the device number
22362  *		arg	- pointer to user provided dk_minfo structure
22363  *			  specifying the media type, logical block size and
22364  *			  drive capacity.
22365  *		flag	- this argument is a pass through to ddi_copyxxx()
22366  *			  directly from the mode argument of ioctl().
22367  *
22368  * Return Code: 0
22369  *		EACCESS
22370  *		EFAULT
22371  *		ENXIO
22372  *		EIO
22373  */
22374 
22375 static int
22376 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
22377 {
22378 	struct sd_lun		*un = NULL;
22379 	struct uscsi_cmd	com;
22380 	struct scsi_inquiry	*sinq;
22381 	struct dk_minfo		media_info;
22382 	u_longlong_t		media_capacity;
22383 	uint64_t		capacity;
22384 	uint_t			lbasize;
22385 	uchar_t			*out_data;
22386 	uchar_t			*rqbuf;
22387 	int			rval = 0;
22388 	int			rtn;
22389 	sd_ssc_t		*ssc;
22390 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
22391 	    (un->un_state == SD_STATE_OFFLINE)) {
22392 		return (ENXIO);
22393 	}
22394 
22395 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
22396 
22397 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
22398 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
22399 
22400 	/* Issue a TUR to determine if the drive is ready with media present */
22401 	ssc = sd_ssc_init(un);
22402 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
22403 	if (rval == ENXIO) {
22404 		goto done;
22405 	} else if (rval != 0) {
22406 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22407 	}
22408 
22409 	/* Now get configuration data */
22410 	if (ISCD(un)) {
22411 		media_info.dki_media_type = DK_CDROM;
22412 
22413 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
22414 		if (un->un_f_mmc_cap == TRUE) {
22415 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
22416 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
22417 			    SD_PATH_STANDARD);
22418 
22419 			if (rtn) {
22420 				/*
22421 				 * We ignore all failures for CD and need to
22422 				 * put the assessment before processing code
22423 				 * to avoid missing assessment for FMA.
22424 				 */
22425 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22426 				/*
22427 				 * Failed for other than an illegal request
22428 				 * or command not supported
22429 				 */
22430 				if ((com.uscsi_status == STATUS_CHECK) &&
22431 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
22432 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
22433 					    (rqbuf[12] != 0x20)) {
22434 						rval = EIO;
22435 						goto no_assessment;
22436 					}
22437 				}
22438 			} else {
22439 				/*
22440 				 * The GET CONFIGURATION command succeeded
22441 				 * so set the media type according to the
22442 				 * returned data
22443 				 */
22444 				media_info.dki_media_type = out_data[6];
22445 				media_info.dki_media_type <<= 8;
22446 				media_info.dki_media_type |= out_data[7];
22447 			}
22448 		}
22449 	} else {
22450 		/*
22451 		 * The profile list is not available, so we attempt to identify
22452 		 * the media type based on the inquiry data
22453 		 */
22454 		sinq = un->un_sd->sd_inq;
22455 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
22456 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
22457 			/* This is a direct access device  or optical disk */
22458 			media_info.dki_media_type = DK_FIXED_DISK;
22459 
22460 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
22461 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
22462 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
22463 					media_info.dki_media_type = DK_ZIP;
22464 				} else if (
22465 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
22466 					media_info.dki_media_type = DK_JAZ;
22467 				}
22468 			}
22469 		} else {
22470 			/*
22471 			 * Not a CD, direct access or optical disk so return
22472 			 * unknown media
22473 			 */
22474 			media_info.dki_media_type = DK_UNKNOWN;
22475 		}
22476 	}
22477 
22478 	/* Now read the capacity so we can provide the lbasize and capacity */
22479 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
22480 	    SD_PATH_DIRECT);
22481 	switch (rval) {
22482 	case 0:
22483 		break;
22484 	case EACCES:
22485 		rval = EACCES;
22486 		goto done;
22487 	default:
22488 		rval = EIO;
22489 		goto done;
22490 	}
22491 
22492 	/*
22493 	 * If lun is expanded dynamically, update the un structure.
22494 	 */
22495 	mutex_enter(SD_MUTEX(un));
22496 	if ((un->un_f_blockcount_is_valid == TRUE) &&
22497 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
22498 	    (capacity > un->un_blockcount)) {
22499 		sd_update_block_info(un, lbasize, capacity);
22500 	}
22501 	mutex_exit(SD_MUTEX(un));
22502 
22503 	media_info.dki_lbsize = lbasize;
22504 	media_capacity = capacity;
22505 
22506 	/*
22507 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
22508 	 * un->un_sys_blocksize chunks. So we need to convert it into
22509 	 * cap.lbasize chunks.
22510 	 */
22511 	media_capacity *= un->un_sys_blocksize;
22512 	media_capacity /= lbasize;
22513 	media_info.dki_capacity = media_capacity;
22514 
22515 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
22516 		rval = EFAULT;
22517 		/* Put goto. Anybody might add some code below in future */
22518 		goto no_assessment;
22519 	}
22520 done:
22521 	if (rval != 0) {
22522 		if (rval == EIO)
22523 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
22524 		else
22525 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22526 	}
22527 no_assessment:
22528 	sd_ssc_fini(ssc);
22529 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
22530 	kmem_free(rqbuf, SENSE_LENGTH);
22531 	return (rval);
22532 }
22533 
22534 
22535 /*
22536  *    Function: sd_check_media
22537  *
22538  * Description: This utility routine implements the functionality for the
22539  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
22540  *		driver state changes from that specified by the user
22541  *		(inserted or ejected). For example, if the user specifies
22542  *		DKIO_EJECTED and the current media state is inserted this
22543  *		routine will immediately return DKIO_INSERTED. However, if the
22544  *		current media state is not inserted the user thread will be
22545  *		blocked until the drive state changes. If DKIO_NONE is specified
22546  *		the user thread will block until a drive state change occurs.
22547  *
22548  *   Arguments: dev  - the device number
22549  *		state  - user pointer to a dkio_state, updated with the current
22550  *			drive state at return.
22551  *
22552  * Return Code: ENXIO
22553  *		EIO
22554  *		EAGAIN
22555  *		EINTR
22556  */
22557 
22558 static int
22559 sd_check_media(dev_t dev, enum dkio_state state)
22560 {
22561 	struct sd_lun		*un = NULL;
22562 	enum dkio_state		prev_state;
22563 	opaque_t		token = NULL;
22564 	int			rval = 0;
22565 	sd_ssc_t		*ssc;
22566 
22567 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22568 		return (ENXIO);
22569 	}
22570 
22571 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
22572 
22573 	ssc = sd_ssc_init(un);
22574 
22575 	mutex_enter(SD_MUTEX(un));
22576 
22577 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
22578 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
22579 
22580 	prev_state = un->un_mediastate;
22581 
22582 	/* is there anything to do? */
22583 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
22584 		/*
22585 		 * submit the request to the scsi_watch service;
22586 		 * scsi_media_watch_cb() does the real work
22587 		 */
22588 		mutex_exit(SD_MUTEX(un));
22589 
22590 		/*
22591 		 * This change handles the case where a scsi watch request is
22592 		 * added to a device that is powered down. To accomplish this
22593 		 * we power up the device before adding the scsi watch request,
22594 		 * since the scsi watch sends a TUR directly to the device
22595 		 * which the device cannot handle if it is powered down.
22596 		 */
22597 		if (sd_pm_entry(un) != DDI_SUCCESS) {
22598 			mutex_enter(SD_MUTEX(un));
22599 			goto done;
22600 		}
22601 
22602 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
22603 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
22604 		    (caddr_t)dev);
22605 
22606 		sd_pm_exit(un);
22607 
22608 		mutex_enter(SD_MUTEX(un));
22609 		if (token == NULL) {
22610 			rval = EAGAIN;
22611 			goto done;
22612 		}
22613 
22614 		/*
22615 		 * This is a special case IOCTL that doesn't return
22616 		 * until the media state changes. Routine sdpower
22617 		 * knows about and handles this so don't count it
22618 		 * as an active cmd in the driver, which would
22619 		 * keep the device busy to the pm framework.
22620 		 * If the count isn't decremented the device can't
22621 		 * be powered down.
22622 		 */
22623 		un->un_ncmds_in_driver--;
22624 		ASSERT(un->un_ncmds_in_driver >= 0);
22625 
22626 		/*
22627 		 * if a prior request had been made, this will be the same
22628 		 * token, as scsi_watch was designed that way.
22629 		 */
22630 		un->un_swr_token = token;
22631 		un->un_specified_mediastate = state;
22632 
22633 		/*
22634 		 * now wait for media change
22635 		 * we will not be signalled unless mediastate == state but it is
22636 		 * still better to test for this condition, since there is a
22637 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
22638 		 */
22639 		SD_TRACE(SD_LOG_COMMON, un,
22640 		    "sd_check_media: waiting for media state change\n");
22641 		while (un->un_mediastate == state) {
22642 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
22643 				SD_TRACE(SD_LOG_COMMON, un,
22644 				    "sd_check_media: waiting for media state "
22645 				    "was interrupted\n");
22646 				un->un_ncmds_in_driver++;
22647 				rval = EINTR;
22648 				goto done;
22649 			}
22650 			SD_TRACE(SD_LOG_COMMON, un,
22651 			    "sd_check_media: received signal, state=%x\n",
22652 			    un->un_mediastate);
22653 		}
22654 		/*
22655 		 * Inc the counter to indicate the device once again
22656 		 * has an active outstanding cmd.
22657 		 */
22658 		un->un_ncmds_in_driver++;
22659 	}
22660 
22661 	/* invalidate geometry */
22662 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
22663 		sr_ejected(un);
22664 	}
22665 
22666 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
22667 		uint64_t	capacity;
22668 		uint_t		lbasize;
22669 
22670 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
22671 		mutex_exit(SD_MUTEX(un));
22672 		/*
22673 		 * Since the following routines use SD_PATH_DIRECT, we must
22674 		 * call PM directly before the upcoming disk accesses. This
22675 		 * may cause the disk to be power/spin up.
22676 		 */
22677 
22678 		if (sd_pm_entry(un) == DDI_SUCCESS) {
22679 			rval = sd_send_scsi_READ_CAPACITY(ssc,
22680 			    &capacity, &lbasize, SD_PATH_DIRECT);
22681 			if (rval != 0) {
22682 				sd_pm_exit(un);
22683 				if (rval == EIO)
22684 					sd_ssc_assessment(ssc,
22685 					    SD_FMT_STATUS_CHECK);
22686 				else
22687 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22688 				mutex_enter(SD_MUTEX(un));
22689 				goto done;
22690 			}
22691 		} else {
22692 			rval = EIO;
22693 			mutex_enter(SD_MUTEX(un));
22694 			goto done;
22695 		}
22696 		mutex_enter(SD_MUTEX(un));
22697 
22698 		sd_update_block_info(un, lbasize, capacity);
22699 
22700 		/*
22701 		 *  Check if the media in the device is writable or not
22702 		 */
22703 		if (ISCD(un)) {
22704 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
22705 		}
22706 
22707 		mutex_exit(SD_MUTEX(un));
22708 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
22709 		if ((cmlb_validate(un->un_cmlbhandle, 0,
22710 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
22711 			sd_set_pstats(un);
22712 			SD_TRACE(SD_LOG_IO_PARTITION, un,
22713 			    "sd_check_media: un:0x%p pstats created and "
22714 			    "set\n", un);
22715 		}
22716 
22717 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22718 		    SD_PATH_DIRECT);
22719 
22720 		sd_pm_exit(un);
22721 
22722 		if (rval != 0) {
22723 			if (rval == EIO)
22724 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
22725 			else
22726 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22727 		}
22728 
22729 		mutex_enter(SD_MUTEX(un));
22730 	}
22731 done:
22732 	sd_ssc_fini(ssc);
22733 	un->un_f_watcht_stopped = FALSE;
22734 		/*
22735 		 * Use of this local token and the mutex ensures that we avoid
22736 		 * some race conditions associated with terminating the
22737 		 * scsi watch.
22738 		 */
22739 	if (token) {
22740 		un->un_swr_token = (opaque_t)NULL;
22741 		mutex_exit(SD_MUTEX(un));
22742 		(void) scsi_watch_request_terminate(token,
22743 		    SCSI_WATCH_TERMINATE_WAIT);
22744 		mutex_enter(SD_MUTEX(un));
22745 	}
22746 
22747 	/*
22748 	 * Update the capacity kstat value, if no media previously
22749 	 * (capacity kstat is 0) and a media has been inserted
22750 	 * (un_f_blockcount_is_valid == TRUE)
22751 	 */
22752 	if (un->un_errstats) {
22753 		struct sd_errstats	*stp = NULL;
22754 
22755 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
22756 		if ((stp->sd_capacity.value.ui64 == 0) &&
22757 		    (un->un_f_blockcount_is_valid == TRUE)) {
22758 			stp->sd_capacity.value.ui64 =
22759 			    (uint64_t)((uint64_t)un->un_blockcount *
22760 			    un->un_sys_blocksize);
22761 		}
22762 	}
22763 	mutex_exit(SD_MUTEX(un));
22764 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
22765 	return (rval);
22766 }
22767 
22768 
22769 /*
22770  *    Function: sd_delayed_cv_broadcast
22771  *
22772  * Description: Delayed cv_broadcast to allow for target to recover from media
22773  *		insertion.
22774  *
22775  *   Arguments: arg - driver soft state (unit) structure
22776  */
22777 
22778 static void
22779 sd_delayed_cv_broadcast(void *arg)
22780 {
22781 	struct sd_lun *un = arg;
22782 
22783 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
22784 
22785 	mutex_enter(SD_MUTEX(un));
22786 	un->un_dcvb_timeid = NULL;
22787 	cv_broadcast(&un->un_state_cv);
22788 	mutex_exit(SD_MUTEX(un));
22789 }
22790 
22791 
22792 /*
22793  *    Function: sd_media_watch_cb
22794  *
22795  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
22796  *		routine processes the TUR sense data and updates the driver
22797  *		state if a transition has occurred. The user thread
22798  *		(sd_check_media) is then signalled.
22799  *
22800  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22801  *			among multiple watches that share this callback function
22802  *		resultp - scsi watch facility result packet containing scsi
22803  *			  packet, status byte and sense data
22804  *
22805  * Return Code: 0 for success, -1 for failure
22806  */
22807 
22808 static int
22809 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
22810 {
22811 	struct sd_lun			*un;
22812 	struct scsi_status		*statusp = resultp->statusp;
22813 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
22814 	enum dkio_state			state = DKIO_NONE;
22815 	dev_t				dev = (dev_t)arg;
22816 	uchar_t				actual_sense_length;
22817 	uint8_t				skey, asc, ascq;
22818 
22819 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22820 		return (-1);
22821 	}
22822 	actual_sense_length = resultp->actual_sense_length;
22823 
22824 	mutex_enter(SD_MUTEX(un));
22825 	SD_TRACE(SD_LOG_COMMON, un,
22826 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
22827 	    *((char *)statusp), (void *)sensep, actual_sense_length);
22828 
22829 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
22830 		un->un_mediastate = DKIO_DEV_GONE;
22831 		cv_broadcast(&un->un_state_cv);
22832 		mutex_exit(SD_MUTEX(un));
22833 
22834 		return (0);
22835 	}
22836 
22837 	/*
22838 	 * If there was a check condition then sensep points to valid sense data
22839 	 * If status was not a check condition but a reservation or busy status
22840 	 * then the new state is DKIO_NONE
22841 	 */
22842 	if (sensep != NULL) {
22843 		skey = scsi_sense_key(sensep);
22844 		asc = scsi_sense_asc(sensep);
22845 		ascq = scsi_sense_ascq(sensep);
22846 
22847 		SD_INFO(SD_LOG_COMMON, un,
22848 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
22849 		    skey, asc, ascq);
22850 		/* This routine only uses up to 13 bytes of sense data. */
22851 		if (actual_sense_length >= 13) {
22852 			if (skey == KEY_UNIT_ATTENTION) {
22853 				if (asc == 0x28) {
22854 					state = DKIO_INSERTED;
22855 				}
22856 			} else if (skey == KEY_NOT_READY) {
22857 				/*
22858 				 * Sense data of 02/06/00 means that the
22859 				 * drive could not read the media (No
22860 				 * reference position found). In this case
22861 				 * to prevent a hang on the DKIOCSTATE IOCTL
22862 				 * we set the media state to DKIO_INSERTED.
22863 				 */
22864 				if (asc == 0x06 && ascq == 0x00)
22865 					state = DKIO_INSERTED;
22866 
22867 				/*
22868 				 * if 02/04/02  means that the host
22869 				 * should send start command. Explicitly
22870 				 * leave the media state as is
22871 				 * (inserted) as the media is inserted
22872 				 * and host has stopped device for PM
22873 				 * reasons. Upon next true read/write
22874 				 * to this media will bring the
22875 				 * device to the right state good for
22876 				 * media access.
22877 				 */
22878 				if (asc == 0x3a) {
22879 					state = DKIO_EJECTED;
22880 				} else {
22881 					/*
22882 					 * If the drive is busy with an
22883 					 * operation or long write, keep the
22884 					 * media in an inserted state.
22885 					 */
22886 
22887 					if ((asc == 0x04) &&
22888 					    ((ascq == 0x02) ||
22889 					    (ascq == 0x07) ||
22890 					    (ascq == 0x08))) {
22891 						state = DKIO_INSERTED;
22892 					}
22893 				}
22894 			} else if (skey == KEY_NO_SENSE) {
22895 				if ((asc == 0x00) && (ascq == 0x00)) {
22896 					/*
22897 					 * Sense Data 00/00/00 does not provide
22898 					 * any information about the state of
22899 					 * the media. Ignore it.
22900 					 */
22901 					mutex_exit(SD_MUTEX(un));
22902 					return (0);
22903 				}
22904 			}
22905 		}
22906 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
22907 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
22908 		state = DKIO_INSERTED;
22909 	}
22910 
22911 	SD_TRACE(SD_LOG_COMMON, un,
22912 	    "sd_media_watch_cb: state=%x, specified=%x\n",
22913 	    state, un->un_specified_mediastate);
22914 
22915 	/*
22916 	 * now signal the waiting thread if this is *not* the specified state;
22917 	 * delay the signal if the state is DKIO_INSERTED to allow the target
22918 	 * to recover
22919 	 */
22920 	if (state != un->un_specified_mediastate) {
22921 		un->un_mediastate = state;
22922 		if (state == DKIO_INSERTED) {
22923 			/*
22924 			 * delay the signal to give the drive a chance
22925 			 * to do what it apparently needs to do
22926 			 */
22927 			SD_TRACE(SD_LOG_COMMON, un,
22928 			    "sd_media_watch_cb: delayed cv_broadcast\n");
22929 			if (un->un_dcvb_timeid == NULL) {
22930 				un->un_dcvb_timeid =
22931 				    timeout(sd_delayed_cv_broadcast, un,
22932 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
22933 			}
22934 		} else {
22935 			SD_TRACE(SD_LOG_COMMON, un,
22936 			    "sd_media_watch_cb: immediate cv_broadcast\n");
22937 			cv_broadcast(&un->un_state_cv);
22938 		}
22939 	}
22940 	mutex_exit(SD_MUTEX(un));
22941 	return (0);
22942 }
22943 
22944 
22945 /*
22946  *    Function: sd_dkio_get_temp
22947  *
22948  * Description: This routine is the driver entry point for handling ioctl
22949  *		requests to get the disk temperature.
22950  *
22951  *   Arguments: dev  - the device number
22952  *		arg  - pointer to user provided dk_temperature structure.
22953  *		flag - this argument is a pass through to ddi_copyxxx()
22954  *		       directly from the mode argument of ioctl().
22955  *
22956  * Return Code: 0
22957  *		EFAULT
22958  *		ENXIO
22959  *		EAGAIN
22960  */
22961 
22962 static int
22963 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
22964 {
22965 	struct sd_lun		*un = NULL;
22966 	struct dk_temperature	*dktemp = NULL;
22967 	uchar_t			*temperature_page;
22968 	int			rval = 0;
22969 	int			path_flag = SD_PATH_STANDARD;
22970 	sd_ssc_t		*ssc;
22971 
22972 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22973 		return (ENXIO);
22974 	}
22975 
22976 	ssc = sd_ssc_init(un);
22977 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
22978 
22979 	/* copyin the disk temp argument to get the user flags */
22980 	if (ddi_copyin((void *)arg, dktemp,
22981 	    sizeof (struct dk_temperature), flag) != 0) {
22982 		rval = EFAULT;
22983 		goto done;
22984 	}
22985 
22986 	/* Initialize the temperature to invalid. */
22987 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
22988 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
22989 
22990 	/*
22991 	 * Note: Investigate removing the "bypass pm" semantic.
22992 	 * Can we just bypass PM always?
22993 	 */
22994 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
22995 		path_flag = SD_PATH_DIRECT;
22996 		ASSERT(!mutex_owned(&un->un_pm_mutex));
22997 		mutex_enter(&un->un_pm_mutex);
22998 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
22999 			/*
23000 			 * If DKT_BYPASS_PM is set, and the drive happens to be
23001 			 * in low power mode, we can not wake it up, Need to
23002 			 * return EAGAIN.
23003 			 */
23004 			mutex_exit(&un->un_pm_mutex);
23005 			rval = EAGAIN;
23006 			goto done;
23007 		} else {
23008 			/*
23009 			 * Indicate to PM the device is busy. This is required
23010 			 * to avoid a race - i.e. the ioctl is issuing a
23011 			 * command and the pm framework brings down the device
23012 			 * to low power mode (possible power cut-off on some
23013 			 * platforms).
23014 			 */
23015 			mutex_exit(&un->un_pm_mutex);
23016 			if (sd_pm_entry(un) != DDI_SUCCESS) {
23017 				rval = EAGAIN;
23018 				goto done;
23019 			}
23020 		}
23021 	}
23022 
23023 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
23024 
23025 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
23026 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
23027 	if (rval != 0)
23028 		goto done2;
23029 
23030 	/*
23031 	 * For the current temperature verify that the parameter length is 0x02
23032 	 * and the parameter code is 0x00
23033 	 */
23034 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
23035 	    (temperature_page[5] == 0x00)) {
23036 		if (temperature_page[9] == 0xFF) {
23037 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
23038 		} else {
23039 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
23040 		}
23041 	}
23042 
23043 	/*
23044 	 * For the reference temperature verify that the parameter
23045 	 * length is 0x02 and the parameter code is 0x01
23046 	 */
23047 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
23048 	    (temperature_page[11] == 0x01)) {
23049 		if (temperature_page[15] == 0xFF) {
23050 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
23051 		} else {
23052 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
23053 		}
23054 	}
23055 
23056 	/* Do the copyout regardless of the temperature commands status. */
23057 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
23058 	    flag) != 0) {
23059 		rval = EFAULT;
23060 		goto done1;
23061 	}
23062 
23063 done2:
23064 	if (rval != 0) {
23065 		if (rval == EIO)
23066 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23067 		else
23068 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23069 	}
23070 done1:
23071 	if (path_flag == SD_PATH_DIRECT) {
23072 		sd_pm_exit(un);
23073 	}
23074 
23075 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
23076 done:
23077 	sd_ssc_fini(ssc);
23078 	if (dktemp != NULL) {
23079 		kmem_free(dktemp, sizeof (struct dk_temperature));
23080 	}
23081 
23082 	return (rval);
23083 }
23084 
23085 
23086 /*
23087  *    Function: sd_log_page_supported
23088  *
23089  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
23090  *		supported log pages.
23091  *
23092  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
23093  *                      structure for this target.
23094  *		log_page -
23095  *
23096  * Return Code: -1 - on error (log sense is optional and may not be supported).
23097  *		0  - log page not found.
23098  *  		1  - log page found.
23099  */
23100 
23101 static int
23102 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
23103 {
23104 	uchar_t *log_page_data;
23105 	int	i;
23106 	int	match = 0;
23107 	int	log_size;
23108 	int	status = 0;
23109 	struct sd_lun	*un;
23110 
23111 	ASSERT(ssc != NULL);
23112 	un = ssc->ssc_un;
23113 	ASSERT(un != NULL);
23114 
23115 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
23116 
23117 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
23118 	    SD_PATH_DIRECT);
23119 
23120 	if (status != 0) {
23121 		if (status == EIO) {
23122 			/*
23123 			 * Some disks do not support log sense, we
23124 			 * should ignore this kind of error(sense key is
23125 			 * 0x5 - illegal request).
23126 			 */
23127 			uint8_t *sensep;
23128 			int senlen;
23129 
23130 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
23131 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
23132 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
23133 
23134 			if (senlen > 0 &&
23135 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
23136 				sd_ssc_assessment(ssc,
23137 				    SD_FMT_IGNORE_COMPROMISE);
23138 			} else {
23139 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23140 			}
23141 		} else {
23142 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23143 		}
23144 
23145 		SD_ERROR(SD_LOG_COMMON, un,
23146 		    "sd_log_page_supported: failed log page retrieval\n");
23147 		kmem_free(log_page_data, 0xFF);
23148 		return (-1);
23149 	}
23150 
23151 	log_size = log_page_data[3];
23152 
23153 	/*
23154 	 * The list of supported log pages start from the fourth byte. Check
23155 	 * until we run out of log pages or a match is found.
23156 	 */
23157 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
23158 		if (log_page_data[i] == log_page) {
23159 			match++;
23160 		}
23161 	}
23162 	kmem_free(log_page_data, 0xFF);
23163 	return (match);
23164 }
23165 
23166 
23167 /*
23168  *    Function: sd_mhdioc_failfast
23169  *
23170  * Description: This routine is the driver entry point for handling ioctl
23171  *		requests to enable/disable the multihost failfast option.
23172  *		(MHIOCENFAILFAST)
23173  *
23174  *   Arguments: dev	- the device number
23175  *		arg	- user specified probing interval.
23176  *		flag	- this argument is a pass through to ddi_copyxxx()
23177  *			  directly from the mode argument of ioctl().
23178  *
23179  * Return Code: 0
23180  *		EFAULT
23181  *		ENXIO
23182  */
23183 
23184 static int
23185 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
23186 {
23187 	struct sd_lun	*un = NULL;
23188 	int		mh_time;
23189 	int		rval = 0;
23190 
23191 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23192 		return (ENXIO);
23193 	}
23194 
23195 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
23196 		return (EFAULT);
23197 
23198 	if (mh_time) {
23199 		mutex_enter(SD_MUTEX(un));
23200 		un->un_resvd_status |= SD_FAILFAST;
23201 		mutex_exit(SD_MUTEX(un));
23202 		/*
23203 		 * If mh_time is INT_MAX, then this ioctl is being used for
23204 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
23205 		 */
23206 		if (mh_time != INT_MAX) {
23207 			rval = sd_check_mhd(dev, mh_time);
23208 		}
23209 	} else {
23210 		(void) sd_check_mhd(dev, 0);
23211 		mutex_enter(SD_MUTEX(un));
23212 		un->un_resvd_status &= ~SD_FAILFAST;
23213 		mutex_exit(SD_MUTEX(un));
23214 	}
23215 	return (rval);
23216 }
23217 
23218 
23219 /*
23220  *    Function: sd_mhdioc_takeown
23221  *
23222  * Description: This routine is the driver entry point for handling ioctl
23223  *		requests to forcefully acquire exclusive access rights to the
23224  *		multihost disk (MHIOCTKOWN).
23225  *
23226  *   Arguments: dev	- the device number
23227  *		arg	- user provided structure specifying the delay
23228  *			  parameters in milliseconds
23229  *		flag	- this argument is a pass through to ddi_copyxxx()
23230  *			  directly from the mode argument of ioctl().
23231  *
23232  * Return Code: 0
23233  *		EFAULT
23234  *		ENXIO
23235  */
23236 
23237 static int
23238 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
23239 {
23240 	struct sd_lun		*un = NULL;
23241 	struct mhioctkown	*tkown = NULL;
23242 	int			rval = 0;
23243 
23244 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23245 		return (ENXIO);
23246 	}
23247 
23248 	if (arg != NULL) {
23249 		tkown = (struct mhioctkown *)
23250 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
23251 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
23252 		if (rval != 0) {
23253 			rval = EFAULT;
23254 			goto error;
23255 		}
23256 	}
23257 
23258 	rval = sd_take_ownership(dev, tkown);
23259 	mutex_enter(SD_MUTEX(un));
23260 	if (rval == 0) {
23261 		un->un_resvd_status |= SD_RESERVE;
23262 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
23263 			sd_reinstate_resv_delay =
23264 			    tkown->reinstate_resv_delay * 1000;
23265 		} else {
23266 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
23267 		}
23268 		/*
23269 		 * Give the scsi_watch routine interval set by
23270 		 * the MHIOCENFAILFAST ioctl precedence here.
23271 		 */
23272 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
23273 			mutex_exit(SD_MUTEX(un));
23274 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
23275 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
23276 			    "sd_mhdioc_takeown : %d\n",
23277 			    sd_reinstate_resv_delay);
23278 		} else {
23279 			mutex_exit(SD_MUTEX(un));
23280 		}
23281 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
23282 		    sd_mhd_reset_notify_cb, (caddr_t)un);
23283 	} else {
23284 		un->un_resvd_status &= ~SD_RESERVE;
23285 		mutex_exit(SD_MUTEX(un));
23286 	}
23287 
23288 error:
23289 	if (tkown != NULL) {
23290 		kmem_free(tkown, sizeof (struct mhioctkown));
23291 	}
23292 	return (rval);
23293 }
23294 
23295 
23296 /*
23297  *    Function: sd_mhdioc_release
23298  *
23299  * Description: This routine is the driver entry point for handling ioctl
23300  *		requests to release exclusive access rights to the multihost
23301  *		disk (MHIOCRELEASE).
23302  *
23303  *   Arguments: dev	- the device number
23304  *
23305  * Return Code: 0
23306  *		ENXIO
23307  */
23308 
23309 static int
23310 sd_mhdioc_release(dev_t dev)
23311 {
23312 	struct sd_lun		*un = NULL;
23313 	timeout_id_t		resvd_timeid_save;
23314 	int			resvd_status_save;
23315 	int			rval = 0;
23316 
23317 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23318 		return (ENXIO);
23319 	}
23320 
23321 	mutex_enter(SD_MUTEX(un));
23322 	resvd_status_save = un->un_resvd_status;
23323 	un->un_resvd_status &=
23324 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
23325 	if (un->un_resvd_timeid) {
23326 		resvd_timeid_save = un->un_resvd_timeid;
23327 		un->un_resvd_timeid = NULL;
23328 		mutex_exit(SD_MUTEX(un));
23329 		(void) untimeout(resvd_timeid_save);
23330 	} else {
23331 		mutex_exit(SD_MUTEX(un));
23332 	}
23333 
23334 	/*
23335 	 * destroy any pending timeout thread that may be attempting to
23336 	 * reinstate reservation on this device.
23337 	 */
23338 	sd_rmv_resv_reclaim_req(dev);
23339 
23340 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
23341 		mutex_enter(SD_MUTEX(un));
23342 		if ((un->un_mhd_token) &&
23343 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
23344 			mutex_exit(SD_MUTEX(un));
23345 			(void) sd_check_mhd(dev, 0);
23346 		} else {
23347 			mutex_exit(SD_MUTEX(un));
23348 		}
23349 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
23350 		    sd_mhd_reset_notify_cb, (caddr_t)un);
23351 	} else {
23352 		/*
23353 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
23354 		 */
23355 		mutex_enter(SD_MUTEX(un));
23356 		un->un_resvd_status = resvd_status_save;
23357 		mutex_exit(SD_MUTEX(un));
23358 	}
23359 	return (rval);
23360 }
23361 
23362 
23363 /*
23364  *    Function: sd_mhdioc_register_devid
23365  *
23366  * Description: This routine is the driver entry point for handling ioctl
23367  *		requests to register the device id (MHIOCREREGISTERDEVID).
23368  *
23369  *		Note: The implementation for this ioctl has been updated to
23370  *		be consistent with the original PSARC case (1999/357)
23371  *		(4375899, 4241671, 4220005)
23372  *
23373  *   Arguments: dev	- the device number
23374  *
23375  * Return Code: 0
23376  *		ENXIO
23377  */
23378 
23379 static int
23380 sd_mhdioc_register_devid(dev_t dev)
23381 {
23382 	struct sd_lun	*un = NULL;
23383 	int		rval = 0;
23384 	sd_ssc_t	*ssc;
23385 
23386 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23387 		return (ENXIO);
23388 	}
23389 
23390 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23391 
23392 	mutex_enter(SD_MUTEX(un));
23393 
23394 	/* If a devid already exists, de-register it */
23395 	if (un->un_devid != NULL) {
23396 		ddi_devid_unregister(SD_DEVINFO(un));
23397 		/*
23398 		 * After unregister devid, needs to free devid memory
23399 		 */
23400 		ddi_devid_free(un->un_devid);
23401 		un->un_devid = NULL;
23402 	}
23403 
23404 	/* Check for reservation conflict */
23405 	mutex_exit(SD_MUTEX(un));
23406 	ssc = sd_ssc_init(un);
23407 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
23408 	mutex_enter(SD_MUTEX(un));
23409 
23410 	switch (rval) {
23411 	case 0:
23412 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
23413 		break;
23414 	case EACCES:
23415 		break;
23416 	default:
23417 		rval = EIO;
23418 	}
23419 
23420 	mutex_exit(SD_MUTEX(un));
23421 	if (rval != 0) {
23422 		if (rval == EIO)
23423 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23424 		else
23425 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23426 	}
23427 	sd_ssc_fini(ssc);
23428 	return (rval);
23429 }
23430 
23431 
23432 /*
23433  *    Function: sd_mhdioc_inkeys
23434  *
23435  * Description: This routine is the driver entry point for handling ioctl
23436  *		requests to issue the SCSI-3 Persistent In Read Keys command
23437  *		to the device (MHIOCGRP_INKEYS).
23438  *
23439  *   Arguments: dev	- the device number
23440  *		arg	- user provided in_keys structure
23441  *		flag	- this argument is a pass through to ddi_copyxxx()
23442  *			  directly from the mode argument of ioctl().
23443  *
23444  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
23445  *		ENXIO
23446  *		EFAULT
23447  */
23448 
23449 static int
23450 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
23451 {
23452 	struct sd_lun		*un;
23453 	mhioc_inkeys_t		inkeys;
23454 	int			rval = 0;
23455 
23456 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23457 		return (ENXIO);
23458 	}
23459 
23460 #ifdef _MULTI_DATAMODEL
23461 	switch (ddi_model_convert_from(flag & FMODELS)) {
23462 	case DDI_MODEL_ILP32: {
23463 		struct mhioc_inkeys32	inkeys32;
23464 
23465 		if (ddi_copyin(arg, &inkeys32,
23466 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
23467 			return (EFAULT);
23468 		}
23469 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
23470 		if ((rval = sd_persistent_reservation_in_read_keys(un,
23471 		    &inkeys, flag)) != 0) {
23472 			return (rval);
23473 		}
23474 		inkeys32.generation = inkeys.generation;
23475 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
23476 		    flag) != 0) {
23477 			return (EFAULT);
23478 		}
23479 		break;
23480 	}
23481 	case DDI_MODEL_NONE:
23482 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
23483 		    flag) != 0) {
23484 			return (EFAULT);
23485 		}
23486 		if ((rval = sd_persistent_reservation_in_read_keys(un,
23487 		    &inkeys, flag)) != 0) {
23488 			return (rval);
23489 		}
23490 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
23491 		    flag) != 0) {
23492 			return (EFAULT);
23493 		}
23494 		break;
23495 	}
23496 
23497 #else /* ! _MULTI_DATAMODEL */
23498 
23499 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
23500 		return (EFAULT);
23501 	}
23502 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
23503 	if (rval != 0) {
23504 		return (rval);
23505 	}
23506 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
23507 		return (EFAULT);
23508 	}
23509 
23510 #endif /* _MULTI_DATAMODEL */
23511 
23512 	return (rval);
23513 }
23514 
23515 
23516 /*
23517  *    Function: sd_mhdioc_inresv
23518  *
23519  * Description: This routine is the driver entry point for handling ioctl
23520  *		requests to issue the SCSI-3 Persistent In Read Reservations
23521  *		command to the device (MHIOCGRP_INKEYS).
23522  *
23523  *   Arguments: dev	- the device number
23524  *		arg	- user provided in_resv structure
23525  *		flag	- this argument is a pass through to ddi_copyxxx()
23526  *			  directly from the mode argument of ioctl().
23527  *
23528  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
23529  *		ENXIO
23530  *		EFAULT
23531  */
23532 
23533 static int
23534 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
23535 {
23536 	struct sd_lun		*un;
23537 	mhioc_inresvs_t		inresvs;
23538 	int			rval = 0;
23539 
23540 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23541 		return (ENXIO);
23542 	}
23543 
23544 #ifdef _MULTI_DATAMODEL
23545 
23546 	switch (ddi_model_convert_from(flag & FMODELS)) {
23547 	case DDI_MODEL_ILP32: {
23548 		struct mhioc_inresvs32	inresvs32;
23549 
23550 		if (ddi_copyin(arg, &inresvs32,
23551 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
23552 			return (EFAULT);
23553 		}
23554 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
23555 		if ((rval = sd_persistent_reservation_in_read_resv(un,
23556 		    &inresvs, flag)) != 0) {
23557 			return (rval);
23558 		}
23559 		inresvs32.generation = inresvs.generation;
23560 		if (ddi_copyout(&inresvs32, arg,
23561 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
23562 			return (EFAULT);
23563 		}
23564 		break;
23565 	}
23566 	case DDI_MODEL_NONE:
23567 		if (ddi_copyin(arg, &inresvs,
23568 		    sizeof (mhioc_inresvs_t), flag) != 0) {
23569 			return (EFAULT);
23570 		}
23571 		if ((rval = sd_persistent_reservation_in_read_resv(un,
23572 		    &inresvs, flag)) != 0) {
23573 			return (rval);
23574 		}
23575 		if (ddi_copyout(&inresvs, arg,
23576 		    sizeof (mhioc_inresvs_t), flag) != 0) {
23577 			return (EFAULT);
23578 		}
23579 		break;
23580 	}
23581 
23582 #else /* ! _MULTI_DATAMODEL */
23583 
23584 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
23585 		return (EFAULT);
23586 	}
23587 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
23588 	if (rval != 0) {
23589 		return (rval);
23590 	}
23591 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
23592 		return (EFAULT);
23593 	}
23594 
23595 #endif /* ! _MULTI_DATAMODEL */
23596 
23597 	return (rval);
23598 }
23599 
23600 
23601 /*
23602  * The following routines support the clustering functionality described below
23603  * and implement lost reservation reclaim functionality.
23604  *
23605  * Clustering
23606  * ----------
23607  * The clustering code uses two different, independent forms of SCSI
23608  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
23609  * Persistent Group Reservations. For any particular disk, it will use either
23610  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
23611  *
23612  * SCSI-2
23613  * The cluster software takes ownership of a multi-hosted disk by issuing the
23614  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
23615  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
23616  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
23617  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
23618  * driver. The meaning of failfast is that if the driver (on this host) ever
23619  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
23620  * it should immediately panic the host. The motivation for this ioctl is that
23621  * if this host does encounter reservation conflict, the underlying cause is
23622  * that some other host of the cluster has decided that this host is no longer
23623  * in the cluster and has seized control of the disks for itself. Since this
23624  * host is no longer in the cluster, it ought to panic itself. The
23625  * MHIOCENFAILFAST ioctl does two things:
23626  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
23627  *      error to panic the host
23628  *      (b) it sets up a periodic timer to test whether this host still has
23629  *      "access" (in that no other host has reserved the device):  if the
23630  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
23631  *      purpose of that periodic timer is to handle scenarios where the host is
23632  *      otherwise temporarily quiescent, temporarily doing no real i/o.
23633  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
23634  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
23635  * the device itself.
23636  *
23637  * SCSI-3 PGR
23638  * A direct semantic implementation of the SCSI-3 Persistent Reservation
23639  * facility is supported through the shared multihost disk ioctls
23640  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
23641  * MHIOCGRP_PREEMPTANDABORT)
23642  *
23643  * Reservation Reclaim:
23644  * --------------------
23645  * To support the lost reservation reclaim operations this driver creates a
23646  * single thread to handle reinstating reservations on all devices that have
23647  * lost reservations sd_resv_reclaim_requests are logged for all devices that
23648  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
23649  * and the reservation reclaim thread loops through the requests to regain the
23650  * lost reservations.
23651  */
23652 
23653 /*
23654  *    Function: sd_check_mhd()
23655  *
23656  * Description: This function sets up and submits a scsi watch request or
23657  *		terminates an existing watch request. This routine is used in
23658  *		support of reservation reclaim.
23659  *
23660  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
23661  *			 among multiple watches that share the callback function
23662  *		interval - the number of microseconds specifying the watch
23663  *			   interval for issuing TEST UNIT READY commands. If
23664  *			   set to 0 the watch should be terminated. If the
23665  *			   interval is set to 0 and if the device is required
23666  *			   to hold reservation while disabling failfast, the
23667  *			   watch is restarted with an interval of
23668  *			   reinstate_resv_delay.
23669  *
23670  * Return Code: 0	   - Successful submit/terminate of scsi watch request
23671  *		ENXIO      - Indicates an invalid device was specified
23672  *		EAGAIN     - Unable to submit the scsi watch request
23673  */
23674 
23675 static int
23676 sd_check_mhd(dev_t dev, int interval)
23677 {
23678 	struct sd_lun	*un;
23679 	opaque_t	token;
23680 
23681 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23682 		return (ENXIO);
23683 	}
23684 
23685 	/* is this a watch termination request? */
23686 	if (interval == 0) {
23687 		mutex_enter(SD_MUTEX(un));
23688 		/* if there is an existing watch task then terminate it */
23689 		if (un->un_mhd_token) {
23690 			token = un->un_mhd_token;
23691 			un->un_mhd_token = NULL;
23692 			mutex_exit(SD_MUTEX(un));
23693 			(void) scsi_watch_request_terminate(token,
23694 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
23695 			mutex_enter(SD_MUTEX(un));
23696 		} else {
23697 			mutex_exit(SD_MUTEX(un));
23698 			/*
23699 			 * Note: If we return here we don't check for the
23700 			 * failfast case. This is the original legacy
23701 			 * implementation but perhaps we should be checking
23702 			 * the failfast case.
23703 			 */
23704 			return (0);
23705 		}
23706 		/*
23707 		 * If the device is required to hold reservation while
23708 		 * disabling failfast, we need to restart the scsi_watch
23709 		 * routine with an interval of reinstate_resv_delay.
23710 		 */
23711 		if (un->un_resvd_status & SD_RESERVE) {
23712 			interval = sd_reinstate_resv_delay/1000;
23713 		} else {
23714 			/* no failfast so bail */
23715 			mutex_exit(SD_MUTEX(un));
23716 			return (0);
23717 		}
23718 		mutex_exit(SD_MUTEX(un));
23719 	}
23720 
23721 	/*
23722 	 * adjust minimum time interval to 1 second,
23723 	 * and convert from msecs to usecs
23724 	 */
23725 	if (interval > 0 && interval < 1000) {
23726 		interval = 1000;
23727 	}
23728 	interval *= 1000;
23729 
23730 	/*
23731 	 * submit the request to the scsi_watch service
23732 	 */
23733 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
23734 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
23735 	if (token == NULL) {
23736 		return (EAGAIN);
23737 	}
23738 
23739 	/*
23740 	 * save token for termination later on
23741 	 */
23742 	mutex_enter(SD_MUTEX(un));
23743 	un->un_mhd_token = token;
23744 	mutex_exit(SD_MUTEX(un));
23745 	return (0);
23746 }
23747 
23748 
23749 /*
23750  *    Function: sd_mhd_watch_cb()
23751  *
23752  * Description: This function is the call back function used by the scsi watch
23753  *		facility. The scsi watch facility sends the "Test Unit Ready"
23754  *		and processes the status. If applicable (i.e. a "Unit Attention"
23755  *		status and automatic "Request Sense" not used) the scsi watch
23756  *		facility will send a "Request Sense" and retrieve the sense data
23757  *		to be passed to this callback function. In either case the
23758  *		automatic "Request Sense" or the facility submitting one, this
23759  *		callback is passed the status and sense data.
23760  *
23761  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
23762  *			among multiple watches that share this callback function
23763  *		resultp - scsi watch facility result packet containing scsi
23764  *			  packet, status byte and sense data
23765  *
23766  * Return Code: 0 - continue the watch task
23767  *		non-zero - terminate the watch task
23768  */
23769 
23770 static int
23771 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
23772 {
23773 	struct sd_lun			*un;
23774 	struct scsi_status		*statusp;
23775 	uint8_t				*sensep;
23776 	struct scsi_pkt			*pkt;
23777 	uchar_t				actual_sense_length;
23778 	dev_t  				dev = (dev_t)arg;
23779 
23780 	ASSERT(resultp != NULL);
23781 	statusp			= resultp->statusp;
23782 	sensep			= (uint8_t *)resultp->sensep;
23783 	pkt			= resultp->pkt;
23784 	actual_sense_length	= resultp->actual_sense_length;
23785 
23786 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23787 		return (ENXIO);
23788 	}
23789 
23790 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
23791 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
23792 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
23793 
23794 	/* Begin processing of the status and/or sense data */
23795 	if (pkt->pkt_reason != CMD_CMPLT) {
23796 		/* Handle the incomplete packet */
23797 		sd_mhd_watch_incomplete(un, pkt);
23798 		return (0);
23799 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
23800 		if (*((unsigned char *)statusp)
23801 		    == STATUS_RESERVATION_CONFLICT) {
23802 			/*
23803 			 * Handle a reservation conflict by panicking if
23804 			 * configured for failfast or by logging the conflict
23805 			 * and updating the reservation status
23806 			 */
23807 			mutex_enter(SD_MUTEX(un));
23808 			if ((un->un_resvd_status & SD_FAILFAST) &&
23809 			    (sd_failfast_enable)) {
23810 				sd_panic_for_res_conflict(un);
23811 				/*NOTREACHED*/
23812 			}
23813 			SD_INFO(SD_LOG_IOCTL_MHD, un,
23814 			    "sd_mhd_watch_cb: Reservation Conflict\n");
23815 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
23816 			mutex_exit(SD_MUTEX(un));
23817 		}
23818 	}
23819 
23820 	if (sensep != NULL) {
23821 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
23822 			mutex_enter(SD_MUTEX(un));
23823 			if ((scsi_sense_asc(sensep) ==
23824 			    SD_SCSI_RESET_SENSE_CODE) &&
23825 			    (un->un_resvd_status & SD_RESERVE)) {
23826 				/*
23827 				 * The additional sense code indicates a power
23828 				 * on or bus device reset has occurred; update
23829 				 * the reservation status.
23830 				 */
23831 				un->un_resvd_status |=
23832 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
23833 				SD_INFO(SD_LOG_IOCTL_MHD, un,
23834 				    "sd_mhd_watch_cb: Lost Reservation\n");
23835 			}
23836 		} else {
23837 			return (0);
23838 		}
23839 	} else {
23840 		mutex_enter(SD_MUTEX(un));
23841 	}
23842 
23843 	if ((un->un_resvd_status & SD_RESERVE) &&
23844 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
23845 		if (un->un_resvd_status & SD_WANT_RESERVE) {
23846 			/*
23847 			 * A reset occurred in between the last probe and this
23848 			 * one so if a timeout is pending cancel it.
23849 			 */
23850 			if (un->un_resvd_timeid) {
23851 				timeout_id_t temp_id = un->un_resvd_timeid;
23852 				un->un_resvd_timeid = NULL;
23853 				mutex_exit(SD_MUTEX(un));
23854 				(void) untimeout(temp_id);
23855 				mutex_enter(SD_MUTEX(un));
23856 			}
23857 			un->un_resvd_status &= ~SD_WANT_RESERVE;
23858 		}
23859 		if (un->un_resvd_timeid == 0) {
23860 			/* Schedule a timeout to handle the lost reservation */
23861 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
23862 			    (void *)dev,
23863 			    drv_usectohz(sd_reinstate_resv_delay));
23864 		}
23865 	}
23866 	mutex_exit(SD_MUTEX(un));
23867 	return (0);
23868 }
23869 
23870 
23871 /*
23872  *    Function: sd_mhd_watch_incomplete()
23873  *
23874  * Description: This function is used to find out why a scsi pkt sent by the
23875  *		scsi watch facility was not completed. Under some scenarios this
23876  *		routine will return. Otherwise it will send a bus reset to see
23877  *		if the drive is still online.
23878  *
23879  *   Arguments: un  - driver soft state (unit) structure
23880  *		pkt - incomplete scsi pkt
23881  */
23882 
23883 static void
23884 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
23885 {
23886 	int	be_chatty;
23887 	int	perr;
23888 
23889 	ASSERT(pkt != NULL);
23890 	ASSERT(un != NULL);
23891 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
23892 	perr		= (pkt->pkt_statistics & STAT_PERR);
23893 
23894 	mutex_enter(SD_MUTEX(un));
23895 	if (un->un_state == SD_STATE_DUMPING) {
23896 		mutex_exit(SD_MUTEX(un));
23897 		return;
23898 	}
23899 
23900 	switch (pkt->pkt_reason) {
23901 	case CMD_UNX_BUS_FREE:
23902 		/*
23903 		 * If we had a parity error that caused the target to drop BSY*,
23904 		 * don't be chatty about it.
23905 		 */
23906 		if (perr && be_chatty) {
23907 			be_chatty = 0;
23908 		}
23909 		break;
23910 	case CMD_TAG_REJECT:
23911 		/*
23912 		 * The SCSI-2 spec states that a tag reject will be sent by the
23913 		 * target if tagged queuing is not supported. A tag reject may
23914 		 * also be sent during certain initialization periods or to
23915 		 * control internal resources. For the latter case the target
23916 		 * may also return Queue Full.
23917 		 *
23918 		 * If this driver receives a tag reject from a target that is
23919 		 * going through an init period or controlling internal
23920 		 * resources tagged queuing will be disabled. This is a less
23921 		 * than optimal behavior but the driver is unable to determine
23922 		 * the target state and assumes tagged queueing is not supported
23923 		 */
23924 		pkt->pkt_flags = 0;
23925 		un->un_tagflags = 0;
23926 
23927 		if (un->un_f_opt_queueing == TRUE) {
23928 			un->un_throttle = min(un->un_throttle, 3);
23929 		} else {
23930 			un->un_throttle = 1;
23931 		}
23932 		mutex_exit(SD_MUTEX(un));
23933 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
23934 		mutex_enter(SD_MUTEX(un));
23935 		break;
23936 	case CMD_INCOMPLETE:
23937 		/*
23938 		 * The transport stopped with an abnormal state, fallthrough and
23939 		 * reset the target and/or bus unless selection did not complete
23940 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
23941 		 * go through a target/bus reset
23942 		 */
23943 		if (pkt->pkt_state == STATE_GOT_BUS) {
23944 			break;
23945 		}
23946 		/*FALLTHROUGH*/
23947 
23948 	case CMD_TIMEOUT:
23949 	default:
23950 		/*
23951 		 * The lun may still be running the command, so a lun reset
23952 		 * should be attempted. If the lun reset fails or cannot be
23953 		 * issued, than try a target reset. Lastly try a bus reset.
23954 		 */
23955 		if ((pkt->pkt_statistics &
23956 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
23957 			int reset_retval = 0;
23958 			mutex_exit(SD_MUTEX(un));
23959 			if (un->un_f_allow_bus_device_reset == TRUE) {
23960 				if (un->un_f_lun_reset_enabled == TRUE) {
23961 					reset_retval =
23962 					    scsi_reset(SD_ADDRESS(un),
23963 					    RESET_LUN);
23964 				}
23965 				if (reset_retval == 0) {
23966 					reset_retval =
23967 					    scsi_reset(SD_ADDRESS(un),
23968 					    RESET_TARGET);
23969 				}
23970 			}
23971 			if (reset_retval == 0) {
23972 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
23973 			}
23974 			mutex_enter(SD_MUTEX(un));
23975 		}
23976 		break;
23977 	}
23978 
23979 	/* A device/bus reset has occurred; update the reservation status. */
23980 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
23981 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
23982 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
23983 			un->un_resvd_status |=
23984 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
23985 			SD_INFO(SD_LOG_IOCTL_MHD, un,
23986 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
23987 		}
23988 	}
23989 
23990 	/*
23991 	 * The disk has been turned off; Update the device state.
23992 	 *
23993 	 * Note: Should we be offlining the disk here?
23994 	 */
23995 	if (pkt->pkt_state == STATE_GOT_BUS) {
23996 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
23997 		    "Disk not responding to selection\n");
23998 		if (un->un_state != SD_STATE_OFFLINE) {
23999 			New_state(un, SD_STATE_OFFLINE);
24000 		}
24001 	} else if (be_chatty) {
24002 		/*
24003 		 * suppress messages if they are all the same pkt reason;
24004 		 * with TQ, many (up to 256) are returned with the same
24005 		 * pkt_reason
24006 		 */
24007 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
24008 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
24009 			    "sd_mhd_watch_incomplete: "
24010 			    "SCSI transport failed: reason '%s'\n",
24011 			    scsi_rname(pkt->pkt_reason));
24012 		}
24013 	}
24014 	un->un_last_pkt_reason = pkt->pkt_reason;
24015 	mutex_exit(SD_MUTEX(un));
24016 }
24017 
24018 
24019 /*
24020  *    Function: sd_sname()
24021  *
24022  * Description: This is a simple little routine to return a string containing
24023  *		a printable description of command status byte for use in
24024  *		logging.
24025  *
24026  *   Arguments: status - pointer to a status byte
24027  *
24028  * Return Code: char * - string containing status description.
24029  */
24030 
24031 static char *
24032 sd_sname(uchar_t status)
24033 {
24034 	switch (status & STATUS_MASK) {
24035 	case STATUS_GOOD:
24036 		return ("good status");
24037 	case STATUS_CHECK:
24038 		return ("check condition");
24039 	case STATUS_MET:
24040 		return ("condition met");
24041 	case STATUS_BUSY:
24042 		return ("busy");
24043 	case STATUS_INTERMEDIATE:
24044 		return ("intermediate");
24045 	case STATUS_INTERMEDIATE_MET:
24046 		return ("intermediate - condition met");
24047 	case STATUS_RESERVATION_CONFLICT:
24048 		return ("reservation_conflict");
24049 	case STATUS_TERMINATED:
24050 		return ("command terminated");
24051 	case STATUS_QFULL:
24052 		return ("queue full");
24053 	default:
24054 		return ("<unknown status>");
24055 	}
24056 }
24057 
24058 
24059 /*
24060  *    Function: sd_mhd_resvd_recover()
24061  *
24062  * Description: This function adds a reservation entry to the
24063  *		sd_resv_reclaim_request list and signals the reservation
24064  *		reclaim thread that there is work pending. If the reservation
24065  *		reclaim thread has not been previously created this function
24066  *		will kick it off.
24067  *
24068  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24069  *			among multiple watches that share this callback function
24070  *
24071  *     Context: This routine is called by timeout() and is run in interrupt
24072  *		context. It must not sleep or call other functions which may
24073  *		sleep.
24074  */
24075 
24076 static void
24077 sd_mhd_resvd_recover(void *arg)
24078 {
24079 	dev_t			dev = (dev_t)arg;
24080 	struct sd_lun		*un;
24081 	struct sd_thr_request	*sd_treq = NULL;
24082 	struct sd_thr_request	*sd_cur = NULL;
24083 	struct sd_thr_request	*sd_prev = NULL;
24084 	int			already_there = 0;
24085 
24086 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24087 		return;
24088 	}
24089 
24090 	mutex_enter(SD_MUTEX(un));
24091 	un->un_resvd_timeid = NULL;
24092 	if (un->un_resvd_status & SD_WANT_RESERVE) {
24093 		/*
24094 		 * There was a reset so don't issue the reserve, allow the
24095 		 * sd_mhd_watch_cb callback function to notice this and
24096 		 * reschedule the timeout for reservation.
24097 		 */
24098 		mutex_exit(SD_MUTEX(un));
24099 		return;
24100 	}
24101 	mutex_exit(SD_MUTEX(un));
24102 
24103 	/*
24104 	 * Add this device to the sd_resv_reclaim_request list and the
24105 	 * sd_resv_reclaim_thread should take care of the rest.
24106 	 *
24107 	 * Note: We can't sleep in this context so if the memory allocation
24108 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
24109 	 * reschedule the timeout for reservation.  (4378460)
24110 	 */
24111 	sd_treq = (struct sd_thr_request *)
24112 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
24113 	if (sd_treq == NULL) {
24114 		return;
24115 	}
24116 
24117 	sd_treq->sd_thr_req_next = NULL;
24118 	sd_treq->dev = dev;
24119 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24120 	if (sd_tr.srq_thr_req_head == NULL) {
24121 		sd_tr.srq_thr_req_head = sd_treq;
24122 	} else {
24123 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
24124 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
24125 			if (sd_cur->dev == dev) {
24126 				/*
24127 				 * already in Queue so don't log
24128 				 * another request for the device
24129 				 */
24130 				already_there = 1;
24131 				break;
24132 			}
24133 			sd_prev = sd_cur;
24134 		}
24135 		if (!already_there) {
24136 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
24137 			    "logging request for %lx\n", dev);
24138 			sd_prev->sd_thr_req_next = sd_treq;
24139 		} else {
24140 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
24141 		}
24142 	}
24143 
24144 	/*
24145 	 * Create a kernel thread to do the reservation reclaim and free up this
24146 	 * thread. We cannot block this thread while we go away to do the
24147 	 * reservation reclaim
24148 	 */
24149 	if (sd_tr.srq_resv_reclaim_thread == NULL)
24150 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
24151 		    sd_resv_reclaim_thread, NULL,
24152 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
24153 
24154 	/* Tell the reservation reclaim thread that it has work to do */
24155 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
24156 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24157 }
24158 
24159 /*
24160  *    Function: sd_resv_reclaim_thread()
24161  *
24162  * Description: This function implements the reservation reclaim operations
24163  *
24164  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
24165  *		      among multiple watches that share this callback function
24166  */
24167 
24168 static void
24169 sd_resv_reclaim_thread()
24170 {
24171 	struct sd_lun		*un;
24172 	struct sd_thr_request	*sd_mhreq;
24173 
24174 	/* Wait for work */
24175 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24176 	if (sd_tr.srq_thr_req_head == NULL) {
24177 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
24178 		    &sd_tr.srq_resv_reclaim_mutex);
24179 	}
24180 
24181 	/* Loop while we have work */
24182 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
24183 		un = ddi_get_soft_state(sd_state,
24184 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
24185 		if (un == NULL) {
24186 			/*
24187 			 * softstate structure is NULL so just
24188 			 * dequeue the request and continue
24189 			 */
24190 			sd_tr.srq_thr_req_head =
24191 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
24192 			kmem_free(sd_tr.srq_thr_cur_req,
24193 			    sizeof (struct sd_thr_request));
24194 			continue;
24195 		}
24196 
24197 		/* dequeue the request */
24198 		sd_mhreq = sd_tr.srq_thr_cur_req;
24199 		sd_tr.srq_thr_req_head =
24200 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
24201 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24202 
24203 		/*
24204 		 * Reclaim reservation only if SD_RESERVE is still set. There
24205 		 * may have been a call to MHIOCRELEASE before we got here.
24206 		 */
24207 		mutex_enter(SD_MUTEX(un));
24208 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
24209 			/*
24210 			 * Note: The SD_LOST_RESERVE flag is cleared before
24211 			 * reclaiming the reservation. If this is done after the
24212 			 * call to sd_reserve_release a reservation loss in the
24213 			 * window between pkt completion of reserve cmd and
24214 			 * mutex_enter below may not be recognized
24215 			 */
24216 			un->un_resvd_status &= ~SD_LOST_RESERVE;
24217 			mutex_exit(SD_MUTEX(un));
24218 
24219 			if (sd_reserve_release(sd_mhreq->dev,
24220 			    SD_RESERVE) == 0) {
24221 				mutex_enter(SD_MUTEX(un));
24222 				un->un_resvd_status |= SD_RESERVE;
24223 				mutex_exit(SD_MUTEX(un));
24224 				SD_INFO(SD_LOG_IOCTL_MHD, un,
24225 				    "sd_resv_reclaim_thread: "
24226 				    "Reservation Recovered\n");
24227 			} else {
24228 				mutex_enter(SD_MUTEX(un));
24229 				un->un_resvd_status |= SD_LOST_RESERVE;
24230 				mutex_exit(SD_MUTEX(un));
24231 				SD_INFO(SD_LOG_IOCTL_MHD, un,
24232 				    "sd_resv_reclaim_thread: Failed "
24233 				    "Reservation Recovery\n");
24234 			}
24235 		} else {
24236 			mutex_exit(SD_MUTEX(un));
24237 		}
24238 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24239 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
24240 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
24241 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
24242 		/*
24243 		 * wakeup the destroy thread if anyone is waiting on
24244 		 * us to complete.
24245 		 */
24246 		cv_signal(&sd_tr.srq_inprocess_cv);
24247 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
24248 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
24249 	}
24250 
24251 	/*
24252 	 * cleanup the sd_tr structure now that this thread will not exist
24253 	 */
24254 	ASSERT(sd_tr.srq_thr_req_head == NULL);
24255 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
24256 	sd_tr.srq_resv_reclaim_thread = NULL;
24257 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24258 	thread_exit();
24259 }
24260 
24261 
24262 /*
24263  *    Function: sd_rmv_resv_reclaim_req()
24264  *
24265  * Description: This function removes any pending reservation reclaim requests
24266  *		for the specified device.
24267  *
24268  *   Arguments: dev - the device 'dev_t'
24269  */
24270 
24271 static void
24272 sd_rmv_resv_reclaim_req(dev_t dev)
24273 {
24274 	struct sd_thr_request *sd_mhreq;
24275 	struct sd_thr_request *sd_prev;
24276 
24277 	/* Remove a reservation reclaim request from the list */
24278 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
24279 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
24280 		/*
24281 		 * We are attempting to reinstate reservation for
24282 		 * this device. We wait for sd_reserve_release()
24283 		 * to return before we return.
24284 		 */
24285 		cv_wait(&sd_tr.srq_inprocess_cv,
24286 		    &sd_tr.srq_resv_reclaim_mutex);
24287 	} else {
24288 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
24289 		if (sd_mhreq && sd_mhreq->dev == dev) {
24290 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
24291 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
24292 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24293 			return;
24294 		}
24295 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
24296 			if (sd_mhreq && sd_mhreq->dev == dev) {
24297 				break;
24298 			}
24299 			sd_prev = sd_mhreq;
24300 		}
24301 		if (sd_mhreq != NULL) {
24302 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
24303 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
24304 		}
24305 	}
24306 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
24307 }
24308 
24309 
24310 /*
24311  *    Function: sd_mhd_reset_notify_cb()
24312  *
24313  * Description: This is a call back function for scsi_reset_notify. This
24314  *		function updates the softstate reserved status and logs the
24315  *		reset. The driver scsi watch facility callback function
24316  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
24317  *		will reclaim the reservation.
24318  *
24319  *   Arguments: arg  - driver soft state (unit) structure
24320  */
24321 
24322 static void
24323 sd_mhd_reset_notify_cb(caddr_t arg)
24324 {
24325 	struct sd_lun *un = (struct sd_lun *)arg;
24326 
24327 	mutex_enter(SD_MUTEX(un));
24328 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
24329 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
24330 		SD_INFO(SD_LOG_IOCTL_MHD, un,
24331 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
24332 	}
24333 	mutex_exit(SD_MUTEX(un));
24334 }
24335 
24336 
24337 /*
24338  *    Function: sd_take_ownership()
24339  *
24340  * Description: This routine implements an algorithm to achieve a stable
24341  *		reservation on disks which don't implement priority reserve,
24342  *		and makes sure that other host lose re-reservation attempts.
24343  *		This algorithm contains of a loop that keeps issuing the RESERVE
24344  *		for some period of time (min_ownership_delay, default 6 seconds)
24345  *		During that loop, it looks to see if there has been a bus device
24346  *		reset or bus reset (both of which cause an existing reservation
24347  *		to be lost). If the reservation is lost issue RESERVE until a
24348  *		period of min_ownership_delay with no resets has gone by, or
24349  *		until max_ownership_delay has expired. This loop ensures that
24350  *		the host really did manage to reserve the device, in spite of
24351  *		resets. The looping for min_ownership_delay (default six
24352  *		seconds) is important to early generation clustering products,
24353  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
24354  *		MHIOCENFAILFAST periodic timer of two seconds. By having
24355  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
24356  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
24357  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
24358  *		have already noticed, via the MHIOCENFAILFAST polling, that it
24359  *		no longer "owns" the disk and will have panicked itself.  Thus,
24360  *		the host issuing the MHIOCTKOWN is assured (with timing
24361  *		dependencies) that by the time it actually starts to use the
24362  *		disk for real work, the old owner is no longer accessing it.
24363  *
24364  *		min_ownership_delay is the minimum amount of time for which the
24365  *		disk must be reserved continuously devoid of resets before the
24366  *		MHIOCTKOWN ioctl will return success.
24367  *
24368  *		max_ownership_delay indicates the amount of time by which the
24369  *		take ownership should succeed or timeout with an error.
24370  *
24371  *   Arguments: dev - the device 'dev_t'
24372  *		*p  - struct containing timing info.
24373  *
24374  * Return Code: 0 for success or error code
24375  */
24376 
24377 static int
24378 sd_take_ownership(dev_t dev, struct mhioctkown *p)
24379 {
24380 	struct sd_lun	*un;
24381 	int		rval;
24382 	int		err;
24383 	int		reservation_count   = 0;
24384 	int		min_ownership_delay =  6000000; /* in usec */
24385 	int		max_ownership_delay = 30000000; /* in usec */
24386 	clock_t		start_time;	/* starting time of this algorithm */
24387 	clock_t		end_time;	/* time limit for giving up */
24388 	clock_t		ownership_time;	/* time limit for stable ownership */
24389 	clock_t		current_time;
24390 	clock_t		previous_current_time;
24391 
24392 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24393 		return (ENXIO);
24394 	}
24395 
24396 	/*
24397 	 * Attempt a device reservation. A priority reservation is requested.
24398 	 */
24399 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
24400 	    != SD_SUCCESS) {
24401 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
24402 		    "sd_take_ownership: return(1)=%d\n", rval);
24403 		return (rval);
24404 	}
24405 
24406 	/* Update the softstate reserved status to indicate the reservation */
24407 	mutex_enter(SD_MUTEX(un));
24408 	un->un_resvd_status |= SD_RESERVE;
24409 	un->un_resvd_status &=
24410 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
24411 	mutex_exit(SD_MUTEX(un));
24412 
24413 	if (p != NULL) {
24414 		if (p->min_ownership_delay != 0) {
24415 			min_ownership_delay = p->min_ownership_delay * 1000;
24416 		}
24417 		if (p->max_ownership_delay != 0) {
24418 			max_ownership_delay = p->max_ownership_delay * 1000;
24419 		}
24420 	}
24421 	SD_INFO(SD_LOG_IOCTL_MHD, un,
24422 	    "sd_take_ownership: min, max delays: %d, %d\n",
24423 	    min_ownership_delay, max_ownership_delay);
24424 
24425 	start_time = ddi_get_lbolt();
24426 	current_time	= start_time;
24427 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
24428 	end_time	= start_time + drv_usectohz(max_ownership_delay);
24429 
24430 	while (current_time - end_time < 0) {
24431 		delay(drv_usectohz(500000));
24432 
24433 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
24434 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
24435 				mutex_enter(SD_MUTEX(un));
24436 				rval = (un->un_resvd_status &
24437 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
24438 				mutex_exit(SD_MUTEX(un));
24439 				break;
24440 			}
24441 		}
24442 		previous_current_time = current_time;
24443 		current_time = ddi_get_lbolt();
24444 		mutex_enter(SD_MUTEX(un));
24445 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
24446 			ownership_time = ddi_get_lbolt() +
24447 			    drv_usectohz(min_ownership_delay);
24448 			reservation_count = 0;
24449 		} else {
24450 			reservation_count++;
24451 		}
24452 		un->un_resvd_status |= SD_RESERVE;
24453 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
24454 		mutex_exit(SD_MUTEX(un));
24455 
24456 		SD_INFO(SD_LOG_IOCTL_MHD, un,
24457 		    "sd_take_ownership: ticks for loop iteration=%ld, "
24458 		    "reservation=%s\n", (current_time - previous_current_time),
24459 		    reservation_count ? "ok" : "reclaimed");
24460 
24461 		if (current_time - ownership_time >= 0 &&
24462 		    reservation_count >= 4) {
24463 			rval = 0; /* Achieved a stable ownership */
24464 			break;
24465 		}
24466 		if (current_time - end_time >= 0) {
24467 			rval = EACCES; /* No ownership in max possible time */
24468 			break;
24469 		}
24470 	}
24471 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
24472 	    "sd_take_ownership: return(2)=%d\n", rval);
24473 	return (rval);
24474 }
24475 
24476 
24477 /*
24478  *    Function: sd_reserve_release()
24479  *
24480  * Description: This function builds and sends scsi RESERVE, RELEASE, and
24481  *		PRIORITY RESERVE commands based on a user specified command type
24482  *
24483  *   Arguments: dev - the device 'dev_t'
24484  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
24485  *		      SD_RESERVE, SD_RELEASE
24486  *
24487  * Return Code: 0 or Error Code
24488  */
24489 
24490 static int
24491 sd_reserve_release(dev_t dev, int cmd)
24492 {
24493 	struct uscsi_cmd	*com = NULL;
24494 	struct sd_lun		*un = NULL;
24495 	char			cdb[CDB_GROUP0];
24496 	int			rval;
24497 
24498 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
24499 	    (cmd == SD_PRIORITY_RESERVE));
24500 
24501 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24502 		return (ENXIO);
24503 	}
24504 
24505 	/* instantiate and initialize the command and cdb */
24506 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24507 	bzero(cdb, CDB_GROUP0);
24508 	com->uscsi_flags   = USCSI_SILENT;
24509 	com->uscsi_timeout = un->un_reserve_release_time;
24510 	com->uscsi_cdblen  = CDB_GROUP0;
24511 	com->uscsi_cdb	   = cdb;
24512 	if (cmd == SD_RELEASE) {
24513 		cdb[0] = SCMD_RELEASE;
24514 	} else {
24515 		cdb[0] = SCMD_RESERVE;
24516 	}
24517 
24518 	/* Send the command. */
24519 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24520 	    SD_PATH_STANDARD);
24521 
24522 	/*
24523 	 * "break" a reservation that is held by another host, by issuing a
24524 	 * reset if priority reserve is desired, and we could not get the
24525 	 * device.
24526 	 */
24527 	if ((cmd == SD_PRIORITY_RESERVE) &&
24528 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
24529 		/*
24530 		 * First try to reset the LUN. If we cannot, then try a target
24531 		 * reset, followed by a bus reset if the target reset fails.
24532 		 */
24533 		int reset_retval = 0;
24534 		if (un->un_f_lun_reset_enabled == TRUE) {
24535 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
24536 		}
24537 		if (reset_retval == 0) {
24538 			/* The LUN reset either failed or was not issued */
24539 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
24540 		}
24541 		if ((reset_retval == 0) &&
24542 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
24543 			rval = EIO;
24544 			kmem_free(com, sizeof (*com));
24545 			return (rval);
24546 		}
24547 
24548 		bzero(com, sizeof (struct uscsi_cmd));
24549 		com->uscsi_flags   = USCSI_SILENT;
24550 		com->uscsi_cdb	   = cdb;
24551 		com->uscsi_cdblen  = CDB_GROUP0;
24552 		com->uscsi_timeout = 5;
24553 
24554 		/*
24555 		 * Reissue the last reserve command, this time without request
24556 		 * sense.  Assume that it is just a regular reserve command.
24557 		 */
24558 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24559 		    SD_PATH_STANDARD);
24560 	}
24561 
24562 	/* Return an error if still getting a reservation conflict. */
24563 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
24564 		rval = EACCES;
24565 	}
24566 
24567 	kmem_free(com, sizeof (*com));
24568 	return (rval);
24569 }
24570 
24571 
24572 #define	SD_NDUMP_RETRIES	12
24573 /*
24574  *	System Crash Dump routine
24575  */
24576 
24577 static int
24578 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
24579 {
24580 	int		instance;
24581 	int		partition;
24582 	int		i;
24583 	int		err;
24584 	struct sd_lun	*un;
24585 	struct scsi_pkt *wr_pktp;
24586 	struct buf	*wr_bp;
24587 	struct buf	wr_buf;
24588 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
24589 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
24590 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
24591 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
24592 	size_t		io_start_offset;
24593 	int		doing_rmw = FALSE;
24594 	int		rval;
24595 	ssize_t		dma_resid;
24596 	daddr_t		oblkno;
24597 	diskaddr_t	nblks = 0;
24598 	diskaddr_t	start_block;
24599 
24600 	instance = SDUNIT(dev);
24601 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
24602 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
24603 		return (ENXIO);
24604 	}
24605 
24606 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
24607 
24608 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
24609 
24610 	partition = SDPART(dev);
24611 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
24612 
24613 	/* Validate blocks to dump at against partition size. */
24614 
24615 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
24616 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
24617 
24618 	if ((blkno + nblk) > nblks) {
24619 		SD_TRACE(SD_LOG_DUMP, un,
24620 		    "sddump: dump range larger than partition: "
24621 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
24622 		    blkno, nblk, nblks);
24623 		return (EINVAL);
24624 	}
24625 
24626 	mutex_enter(&un->un_pm_mutex);
24627 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24628 		struct scsi_pkt *start_pktp;
24629 
24630 		mutex_exit(&un->un_pm_mutex);
24631 
24632 		/*
24633 		 * use pm framework to power on HBA 1st
24634 		 */
24635 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
24636 
24637 		/*
24638 		 * Dump no long uses sdpower to power on a device, it's
24639 		 * in-line here so it can be done in polled mode.
24640 		 */
24641 
24642 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
24643 
24644 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
24645 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
24646 
24647 		if (start_pktp == NULL) {
24648 			/* We were not given a SCSI packet, fail. */
24649 			return (EIO);
24650 		}
24651 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
24652 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
24653 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
24654 		start_pktp->pkt_flags = FLAG_NOINTR;
24655 
24656 		mutex_enter(SD_MUTEX(un));
24657 		SD_FILL_SCSI1_LUN(un, start_pktp);
24658 		mutex_exit(SD_MUTEX(un));
24659 		/*
24660 		 * Scsi_poll returns 0 (success) if the command completes and
24661 		 * the status block is STATUS_GOOD.
24662 		 */
24663 		if (sd_scsi_poll(un, start_pktp) != 0) {
24664 			scsi_destroy_pkt(start_pktp);
24665 			return (EIO);
24666 		}
24667 		scsi_destroy_pkt(start_pktp);
24668 		(void) sd_ddi_pm_resume(un);
24669 	} else {
24670 		mutex_exit(&un->un_pm_mutex);
24671 	}
24672 
24673 	mutex_enter(SD_MUTEX(un));
24674 	un->un_throttle = 0;
24675 
24676 	/*
24677 	 * The first time through, reset the specific target device.
24678 	 * However, when cpr calls sddump we know that sd is in a
24679 	 * a good state so no bus reset is required.
24680 	 * Clear sense data via Request Sense cmd.
24681 	 * In sddump we don't care about allow_bus_device_reset anymore
24682 	 */
24683 
24684 	if ((un->un_state != SD_STATE_SUSPENDED) &&
24685 	    (un->un_state != SD_STATE_DUMPING)) {
24686 
24687 		New_state(un, SD_STATE_DUMPING);
24688 
24689 		if (un->un_f_is_fibre == FALSE) {
24690 			mutex_exit(SD_MUTEX(un));
24691 			/*
24692 			 * Attempt a bus reset for parallel scsi.
24693 			 *
24694 			 * Note: A bus reset is required because on some host
24695 			 * systems (i.e. E420R) a bus device reset is
24696 			 * insufficient to reset the state of the target.
24697 			 *
24698 			 * Note: Don't issue the reset for fibre-channel,
24699 			 * because this tends to hang the bus (loop) for
24700 			 * too long while everyone is logging out and in
24701 			 * and the deadman timer for dumping will fire
24702 			 * before the dump is complete.
24703 			 */
24704 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
24705 				mutex_enter(SD_MUTEX(un));
24706 				Restore_state(un);
24707 				mutex_exit(SD_MUTEX(un));
24708 				return (EIO);
24709 			}
24710 
24711 			/* Delay to give the device some recovery time. */
24712 			drv_usecwait(10000);
24713 
24714 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
24715 				SD_INFO(SD_LOG_DUMP, un,
24716 				    "sddump: sd_send_polled_RQS failed\n");
24717 			}
24718 			mutex_enter(SD_MUTEX(un));
24719 		}
24720 	}
24721 
24722 	/*
24723 	 * Convert the partition-relative block number to a
24724 	 * disk physical block number.
24725 	 */
24726 	blkno += start_block;
24727 
24728 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
24729 
24730 
24731 	/*
24732 	 * Check if the device has a non-512 block size.
24733 	 */
24734 	wr_bp = NULL;
24735 	if (NOT_DEVBSIZE(un)) {
24736 		tgt_byte_offset = blkno * un->un_sys_blocksize;
24737 		tgt_byte_count = nblk * un->un_sys_blocksize;
24738 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
24739 		    (tgt_byte_count % un->un_tgt_blocksize)) {
24740 			doing_rmw = TRUE;
24741 			/*
24742 			 * Calculate the block number and number of block
24743 			 * in terms of the media block size.
24744 			 */
24745 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
24746 			tgt_nblk =
24747 			    ((tgt_byte_offset + tgt_byte_count +
24748 			    (un->un_tgt_blocksize - 1)) /
24749 			    un->un_tgt_blocksize) - tgt_blkno;
24750 
24751 			/*
24752 			 * Invoke the routine which is going to do read part
24753 			 * of read-modify-write.
24754 			 * Note that this routine returns a pointer to
24755 			 * a valid bp in wr_bp.
24756 			 */
24757 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
24758 			    &wr_bp);
24759 			if (err) {
24760 				mutex_exit(SD_MUTEX(un));
24761 				return (err);
24762 			}
24763 			/*
24764 			 * Offset is being calculated as -
24765 			 * (original block # * system block size) -
24766 			 * (new block # * target block size)
24767 			 */
24768 			io_start_offset =
24769 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
24770 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
24771 
24772 			ASSERT((io_start_offset >= 0) &&
24773 			    (io_start_offset < un->un_tgt_blocksize));
24774 			/*
24775 			 * Do the modify portion of read modify write.
24776 			 */
24777 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
24778 			    (size_t)nblk * un->un_sys_blocksize);
24779 		} else {
24780 			doing_rmw = FALSE;
24781 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
24782 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
24783 		}
24784 
24785 		/* Convert blkno and nblk to target blocks */
24786 		blkno = tgt_blkno;
24787 		nblk = tgt_nblk;
24788 	} else {
24789 		wr_bp = &wr_buf;
24790 		bzero(wr_bp, sizeof (struct buf));
24791 		wr_bp->b_flags		= B_BUSY;
24792 		wr_bp->b_un.b_addr	= addr;
24793 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
24794 		wr_bp->b_resid		= 0;
24795 	}
24796 
24797 	mutex_exit(SD_MUTEX(un));
24798 
24799 	/*
24800 	 * Obtain a SCSI packet for the write command.
24801 	 * It should be safe to call the allocator here without
24802 	 * worrying about being locked for DVMA mapping because
24803 	 * the address we're passed is already a DVMA mapping
24804 	 *
24805 	 * We are also not going to worry about semaphore ownership
24806 	 * in the dump buffer. Dumping is single threaded at present.
24807 	 */
24808 
24809 	wr_pktp = NULL;
24810 
24811 	dma_resid = wr_bp->b_bcount;
24812 	oblkno = blkno;
24813 
24814 	while (dma_resid != 0) {
24815 
24816 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
24817 		wr_bp->b_flags &= ~B_ERROR;
24818 
24819 		if (un->un_partial_dma_supported == 1) {
24820 			blkno = oblkno +
24821 			    ((wr_bp->b_bcount - dma_resid) /
24822 			    un->un_tgt_blocksize);
24823 			nblk = dma_resid / un->un_tgt_blocksize;
24824 
24825 			if (wr_pktp) {
24826 				/*
24827 				 * Partial DMA transfers after initial transfer
24828 				 */
24829 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
24830 				    blkno, nblk);
24831 			} else {
24832 				/* Initial transfer */
24833 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
24834 				    un->un_pkt_flags, NULL_FUNC, NULL,
24835 				    blkno, nblk);
24836 			}
24837 		} else {
24838 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
24839 			    0, NULL_FUNC, NULL, blkno, nblk);
24840 		}
24841 
24842 		if (rval == 0) {
24843 			/* We were given a SCSI packet, continue. */
24844 			break;
24845 		}
24846 
24847 		if (i == 0) {
24848 			if (wr_bp->b_flags & B_ERROR) {
24849 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24850 				    "no resources for dumping; "
24851 				    "error code: 0x%x, retrying",
24852 				    geterror(wr_bp));
24853 			} else {
24854 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24855 				    "no resources for dumping; retrying");
24856 			}
24857 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
24858 			if (wr_bp->b_flags & B_ERROR) {
24859 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
24860 				    "no resources for dumping; error code: "
24861 				    "0x%x, retrying\n", geterror(wr_bp));
24862 			}
24863 		} else {
24864 			if (wr_bp->b_flags & B_ERROR) {
24865 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
24866 				    "no resources for dumping; "
24867 				    "error code: 0x%x, retries failed, "
24868 				    "giving up.\n", geterror(wr_bp));
24869 			} else {
24870 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
24871 				    "no resources for dumping; "
24872 				    "retries failed, giving up.\n");
24873 			}
24874 			mutex_enter(SD_MUTEX(un));
24875 			Restore_state(un);
24876 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
24877 				mutex_exit(SD_MUTEX(un));
24878 				scsi_free_consistent_buf(wr_bp);
24879 			} else {
24880 				mutex_exit(SD_MUTEX(un));
24881 			}
24882 			return (EIO);
24883 		}
24884 		drv_usecwait(10000);
24885 	}
24886 
24887 	if (un->un_partial_dma_supported == 1) {
24888 		/*
24889 		 * save the resid from PARTIAL_DMA
24890 		 */
24891 		dma_resid = wr_pktp->pkt_resid;
24892 		if (dma_resid != 0)
24893 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
24894 		wr_pktp->pkt_resid = 0;
24895 	} else {
24896 		dma_resid = 0;
24897 	}
24898 
24899 	/* SunBug 1222170 */
24900 	wr_pktp->pkt_flags = FLAG_NOINTR;
24901 
24902 	err = EIO;
24903 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
24904 
24905 		/*
24906 		 * Scsi_poll returns 0 (success) if the command completes and
24907 		 * the status block is STATUS_GOOD.  We should only check
24908 		 * errors if this condition is not true.  Even then we should
24909 		 * send our own request sense packet only if we have a check
24910 		 * condition and auto request sense has not been performed by
24911 		 * the hba.
24912 		 */
24913 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
24914 
24915 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
24916 		    (wr_pktp->pkt_resid == 0)) {
24917 			err = SD_SUCCESS;
24918 			break;
24919 		}
24920 
24921 		/*
24922 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
24923 		 */
24924 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
24925 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24926 			    "Error while dumping state...Device is gone\n");
24927 			break;
24928 		}
24929 
24930 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
24931 			SD_INFO(SD_LOG_DUMP, un,
24932 			    "sddump: write failed with CHECK, try # %d\n", i);
24933 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
24934 				(void) sd_send_polled_RQS(un);
24935 			}
24936 
24937 			continue;
24938 		}
24939 
24940 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
24941 			int reset_retval = 0;
24942 
24943 			SD_INFO(SD_LOG_DUMP, un,
24944 			    "sddump: write failed with BUSY, try # %d\n", i);
24945 
24946 			if (un->un_f_lun_reset_enabled == TRUE) {
24947 				reset_retval = scsi_reset(SD_ADDRESS(un),
24948 				    RESET_LUN);
24949 			}
24950 			if (reset_retval == 0) {
24951 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
24952 			}
24953 			(void) sd_send_polled_RQS(un);
24954 
24955 		} else {
24956 			SD_INFO(SD_LOG_DUMP, un,
24957 			    "sddump: write failed with 0x%x, try # %d\n",
24958 			    SD_GET_PKT_STATUS(wr_pktp), i);
24959 			mutex_enter(SD_MUTEX(un));
24960 			sd_reset_target(un, wr_pktp);
24961 			mutex_exit(SD_MUTEX(un));
24962 		}
24963 
24964 		/*
24965 		 * If we are not getting anywhere with lun/target resets,
24966 		 * let's reset the bus.
24967 		 */
24968 		if (i == SD_NDUMP_RETRIES/2) {
24969 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
24970 			(void) sd_send_polled_RQS(un);
24971 		}
24972 	}
24973 	}
24974 
24975 	scsi_destroy_pkt(wr_pktp);
24976 	mutex_enter(SD_MUTEX(un));
24977 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
24978 		mutex_exit(SD_MUTEX(un));
24979 		scsi_free_consistent_buf(wr_bp);
24980 	} else {
24981 		mutex_exit(SD_MUTEX(un));
24982 	}
24983 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
24984 	return (err);
24985 }
24986 
24987 /*
24988  *    Function: sd_scsi_poll()
24989  *
24990  * Description: This is a wrapper for the scsi_poll call.
24991  *
24992  *   Arguments: sd_lun - The unit structure
24993  *              scsi_pkt - The scsi packet being sent to the device.
24994  *
24995  * Return Code: 0 - Command completed successfully with good status
24996  *             -1 - Command failed.  This could indicate a check condition
24997  *                  or other status value requiring recovery action.
24998  *
24999  * NOTE: This code is only called off sddump().
25000  */
25001 
25002 static int
25003 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
25004 {
25005 	int status;
25006 
25007 	ASSERT(un != NULL);
25008 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25009 	ASSERT(pktp != NULL);
25010 
25011 	status = SD_SUCCESS;
25012 
25013 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
25014 		pktp->pkt_flags |= un->un_tagflags;
25015 		pktp->pkt_flags &= ~FLAG_NODISCON;
25016 	}
25017 
25018 	status = sd_ddi_scsi_poll(pktp);
25019 	/*
25020 	 * Scsi_poll returns 0 (success) if the command completes and the
25021 	 * status block is STATUS_GOOD.  We should only check errors if this
25022 	 * condition is not true.  Even then we should send our own request
25023 	 * sense packet only if we have a check condition and auto
25024 	 * request sense has not been performed by the hba.
25025 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
25026 	 */
25027 	if ((status != SD_SUCCESS) &&
25028 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
25029 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
25030 	    (pktp->pkt_reason != CMD_DEV_GONE))
25031 		(void) sd_send_polled_RQS(un);
25032 
25033 	return (status);
25034 }
25035 
25036 /*
25037  *    Function: sd_send_polled_RQS()
25038  *
25039  * Description: This sends the request sense command to a device.
25040  *
25041  *   Arguments: sd_lun - The unit structure
25042  *
25043  * Return Code: 0 - Command completed successfully with good status
25044  *             -1 - Command failed.
25045  *
25046  */
25047 
25048 static int
25049 sd_send_polled_RQS(struct sd_lun *un)
25050 {
25051 	int	ret_val;
25052 	struct	scsi_pkt	*rqs_pktp;
25053 	struct	buf		*rqs_bp;
25054 
25055 	ASSERT(un != NULL);
25056 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25057 
25058 	ret_val = SD_SUCCESS;
25059 
25060 	rqs_pktp = un->un_rqs_pktp;
25061 	rqs_bp	 = un->un_rqs_bp;
25062 
25063 	mutex_enter(SD_MUTEX(un));
25064 
25065 	if (un->un_sense_isbusy) {
25066 		ret_val = SD_FAILURE;
25067 		mutex_exit(SD_MUTEX(un));
25068 		return (ret_val);
25069 	}
25070 
25071 	/*
25072 	 * If the request sense buffer (and packet) is not in use,
25073 	 * let's set the un_sense_isbusy and send our packet
25074 	 */
25075 	un->un_sense_isbusy 	= 1;
25076 	rqs_pktp->pkt_resid  	= 0;
25077 	rqs_pktp->pkt_reason 	= 0;
25078 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
25079 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
25080 
25081 	mutex_exit(SD_MUTEX(un));
25082 
25083 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
25084 	    " 0x%p\n", rqs_bp->b_un.b_addr);
25085 
25086 	/*
25087 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
25088 	 * axle - it has a call into us!
25089 	 */
25090 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
25091 		SD_INFO(SD_LOG_COMMON, un,
25092 		    "sd_send_polled_RQS: RQS failed\n");
25093 	}
25094 
25095 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
25096 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
25097 
25098 	mutex_enter(SD_MUTEX(un));
25099 	un->un_sense_isbusy = 0;
25100 	mutex_exit(SD_MUTEX(un));
25101 
25102 	return (ret_val);
25103 }
25104 
25105 /*
25106  * Defines needed for localized version of the scsi_poll routine.
25107  */
25108 #define	CSEC		10000			/* usecs */
25109 #define	SEC_TO_CSEC	(1000000/CSEC)
25110 
25111 /*
25112  *    Function: sd_ddi_scsi_poll()
25113  *
25114  * Description: Localized version of the scsi_poll routine.  The purpose is to
25115  *		send a scsi_pkt to a device as a polled command.  This version
25116  *		is to ensure more robust handling of transport errors.
25117  *		Specifically this routine cures not ready, coming ready
25118  *		transition for power up and reset of sonoma's.  This can take
25119  *		up to 45 seconds for power-on and 20 seconds for reset of a
25120  * 		sonoma lun.
25121  *
25122  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
25123  *
25124  * Return Code: 0 - Command completed successfully with good status
25125  *             -1 - Command failed.
25126  *
25127  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
25128  * be fixed (removing this code), we need to determine how to handle the
25129  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
25130  *
25131  * NOTE: This code is only called off sddump().
25132  */
25133 static int
25134 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
25135 {
25136 	int			rval = -1;
25137 	int			savef;
25138 	long			savet;
25139 	void			(*savec)();
25140 	int			timeout;
25141 	int			busy_count;
25142 	int			poll_delay;
25143 	int			rc;
25144 	uint8_t			*sensep;
25145 	struct scsi_arq_status	*arqstat;
25146 	extern int		do_polled_io;
25147 
25148 	ASSERT(pkt->pkt_scbp);
25149 
25150 	/*
25151 	 * save old flags..
25152 	 */
25153 	savef = pkt->pkt_flags;
25154 	savec = pkt->pkt_comp;
25155 	savet = pkt->pkt_time;
25156 
25157 	pkt->pkt_flags |= FLAG_NOINTR;
25158 
25159 	/*
25160 	 * XXX there is nothing in the SCSA spec that states that we should not
25161 	 * do a callback for polled cmds; however, removing this will break sd
25162 	 * and probably other target drivers
25163 	 */
25164 	pkt->pkt_comp = NULL;
25165 
25166 	/*
25167 	 * we don't like a polled command without timeout.
25168 	 * 60 seconds seems long enough.
25169 	 */
25170 	if (pkt->pkt_time == 0)
25171 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
25172 
25173 	/*
25174 	 * Send polled cmd.
25175 	 *
25176 	 * We do some error recovery for various errors.  Tran_busy,
25177 	 * queue full, and non-dispatched commands are retried every 10 msec.
25178 	 * as they are typically transient failures.  Busy status and Not
25179 	 * Ready are retried every second as this status takes a while to
25180 	 * change.
25181 	 */
25182 	timeout = pkt->pkt_time * SEC_TO_CSEC;
25183 
25184 	for (busy_count = 0; busy_count < timeout; busy_count++) {
25185 		/*
25186 		 * Initialize pkt status variables.
25187 		 */
25188 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
25189 
25190 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
25191 			if (rc != TRAN_BUSY) {
25192 				/* Transport failed - give up. */
25193 				break;
25194 			} else {
25195 				/* Transport busy - try again. */
25196 				poll_delay = 1 * CSEC;		/* 10 msec. */
25197 			}
25198 		} else {
25199 			/*
25200 			 * Transport accepted - check pkt status.
25201 			 */
25202 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
25203 			if ((pkt->pkt_reason == CMD_CMPLT) &&
25204 			    (rc == STATUS_CHECK) &&
25205 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
25206 				arqstat =
25207 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
25208 				sensep = (uint8_t *)&arqstat->sts_sensedata;
25209 			} else {
25210 				sensep = NULL;
25211 			}
25212 
25213 			if ((pkt->pkt_reason == CMD_CMPLT) &&
25214 			    (rc == STATUS_GOOD)) {
25215 				/* No error - we're done */
25216 				rval = 0;
25217 				break;
25218 
25219 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
25220 				/* Lost connection - give up */
25221 				break;
25222 
25223 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
25224 			    (pkt->pkt_state == 0)) {
25225 				/* Pkt not dispatched - try again. */
25226 				poll_delay = 1 * CSEC;		/* 10 msec. */
25227 
25228 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
25229 			    (rc == STATUS_QFULL)) {
25230 				/* Queue full - try again. */
25231 				poll_delay = 1 * CSEC;		/* 10 msec. */
25232 
25233 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
25234 			    (rc == STATUS_BUSY)) {
25235 				/* Busy - try again. */
25236 				poll_delay = 100 * CSEC;	/* 1 sec. */
25237 				busy_count += (SEC_TO_CSEC - 1);
25238 
25239 			} else if ((sensep != NULL) &&
25240 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
25241 				/*
25242 				 * Unit Attention - try again.
25243 				 * Pretend it took 1 sec.
25244 				 * NOTE: 'continue' avoids poll_delay
25245 				 */
25246 				busy_count += (SEC_TO_CSEC - 1);
25247 				continue;
25248 
25249 			} else if ((sensep != NULL) &&
25250 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
25251 			    (scsi_sense_asc(sensep) == 0x04) &&
25252 			    (scsi_sense_ascq(sensep) == 0x01)) {
25253 				/*
25254 				 * Not ready -> ready - try again.
25255 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
25256 				 * ...same as STATUS_BUSY
25257 				 */
25258 				poll_delay = 100 * CSEC;	/* 1 sec. */
25259 				busy_count += (SEC_TO_CSEC - 1);
25260 
25261 			} else {
25262 				/* BAD status - give up. */
25263 				break;
25264 			}
25265 		}
25266 
25267 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
25268 		    !do_polled_io) {
25269 			delay(drv_usectohz(poll_delay));
25270 		} else {
25271 			/* we busy wait during cpr_dump or interrupt threads */
25272 			drv_usecwait(poll_delay);
25273 		}
25274 	}
25275 
25276 	pkt->pkt_flags = savef;
25277 	pkt->pkt_comp = savec;
25278 	pkt->pkt_time = savet;
25279 
25280 	/* return on error */
25281 	if (rval)
25282 		return (rval);
25283 
25284 	/*
25285 	 * This is not a performance critical code path.
25286 	 *
25287 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
25288 	 * issues associated with looking at DMA memory prior to
25289 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
25290 	 */
25291 	scsi_sync_pkt(pkt);
25292 	return (0);
25293 }
25294 
25295 
25296 
25297 /*
25298  *    Function: sd_persistent_reservation_in_read_keys
25299  *
25300  * Description: This routine is the driver entry point for handling CD-ROM
25301  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
25302  *		by sending the SCSI-3 PRIN commands to the device.
25303  *		Processes the read keys command response by copying the
25304  *		reservation key information into the user provided buffer.
25305  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
25306  *
25307  *   Arguments: un   -  Pointer to soft state struct for the target.
25308  *		usrp -	user provided pointer to multihost Persistent In Read
25309  *			Keys structure (mhioc_inkeys_t)
25310  *		flag -	this argument is a pass through to ddi_copyxxx()
25311  *			directly from the mode argument of ioctl().
25312  *
25313  * Return Code: 0   - Success
25314  *		EACCES
25315  *		ENOTSUP
25316  *		errno return code from sd_send_scsi_cmd()
25317  *
25318  *     Context: Can sleep. Does not return until command is completed.
25319  */
25320 
25321 static int
25322 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
25323     mhioc_inkeys_t *usrp, int flag)
25324 {
25325 #ifdef _MULTI_DATAMODEL
25326 	struct mhioc_key_list32	li32;
25327 #endif
25328 	sd_prin_readkeys_t	*in;
25329 	mhioc_inkeys_t		*ptr;
25330 	mhioc_key_list_t	li;
25331 	uchar_t			*data_bufp;
25332 	int 			data_len;
25333 	int			rval = 0;
25334 	size_t			copysz;
25335 	sd_ssc_t		*ssc;
25336 
25337 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
25338 		return (EINVAL);
25339 	}
25340 	bzero(&li, sizeof (mhioc_key_list_t));
25341 
25342 	ssc = sd_ssc_init(un);
25343 
25344 	/*
25345 	 * Get the listsize from user
25346 	 */
25347 #ifdef _MULTI_DATAMODEL
25348 
25349 	switch (ddi_model_convert_from(flag & FMODELS)) {
25350 	case DDI_MODEL_ILP32:
25351 		copysz = sizeof (struct mhioc_key_list32);
25352 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
25353 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25354 			    "sd_persistent_reservation_in_read_keys: "
25355 			    "failed ddi_copyin: mhioc_key_list32_t\n");
25356 			rval = EFAULT;
25357 			goto done;
25358 		}
25359 		li.listsize = li32.listsize;
25360 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
25361 		break;
25362 
25363 	case DDI_MODEL_NONE:
25364 		copysz = sizeof (mhioc_key_list_t);
25365 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
25366 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25367 			    "sd_persistent_reservation_in_read_keys: "
25368 			    "failed ddi_copyin: mhioc_key_list_t\n");
25369 			rval = EFAULT;
25370 			goto done;
25371 		}
25372 		break;
25373 	}
25374 
25375 #else /* ! _MULTI_DATAMODEL */
25376 	copysz = sizeof (mhioc_key_list_t);
25377 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
25378 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25379 		    "sd_persistent_reservation_in_read_keys: "
25380 		    "failed ddi_copyin: mhioc_key_list_t\n");
25381 		rval = EFAULT;
25382 		goto done;
25383 	}
25384 #endif
25385 
25386 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
25387 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
25388 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
25389 
25390 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
25391 	    data_len, data_bufp);
25392 	if (rval != 0) {
25393 		if (rval == EIO)
25394 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
25395 		else
25396 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
25397 		goto done;
25398 	}
25399 	in = (sd_prin_readkeys_t *)data_bufp;
25400 	ptr->generation = BE_32(in->generation);
25401 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
25402 
25403 	/*
25404 	 * Return the min(listsize, listlen) keys
25405 	 */
25406 #ifdef _MULTI_DATAMODEL
25407 
25408 	switch (ddi_model_convert_from(flag & FMODELS)) {
25409 	case DDI_MODEL_ILP32:
25410 		li32.listlen = li.listlen;
25411 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
25412 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25413 			    "sd_persistent_reservation_in_read_keys: "
25414 			    "failed ddi_copyout: mhioc_key_list32_t\n");
25415 			rval = EFAULT;
25416 			goto done;
25417 		}
25418 		break;
25419 
25420 	case DDI_MODEL_NONE:
25421 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
25422 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25423 			    "sd_persistent_reservation_in_read_keys: "
25424 			    "failed ddi_copyout: mhioc_key_list_t\n");
25425 			rval = EFAULT;
25426 			goto done;
25427 		}
25428 		break;
25429 	}
25430 
25431 #else /* ! _MULTI_DATAMODEL */
25432 
25433 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
25434 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25435 		    "sd_persistent_reservation_in_read_keys: "
25436 		    "failed ddi_copyout: mhioc_key_list_t\n");
25437 		rval = EFAULT;
25438 		goto done;
25439 	}
25440 
25441 #endif /* _MULTI_DATAMODEL */
25442 
25443 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
25444 	    li.listsize * MHIOC_RESV_KEY_SIZE);
25445 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
25446 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25447 		    "sd_persistent_reservation_in_read_keys: "
25448 		    "failed ddi_copyout: keylist\n");
25449 		rval = EFAULT;
25450 	}
25451 done:
25452 	sd_ssc_fini(ssc);
25453 	kmem_free(data_bufp, data_len);
25454 	return (rval);
25455 }
25456 
25457 
25458 /*
25459  *    Function: sd_persistent_reservation_in_read_resv
25460  *
25461  * Description: This routine is the driver entry point for handling CD-ROM
25462  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
25463  *		by sending the SCSI-3 PRIN commands to the device.
25464  *		Process the read persistent reservations command response by
25465  *		copying the reservation information into the user provided
25466  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
25467  *
25468  *   Arguments: un   -  Pointer to soft state struct for the target.
25469  *		usrp -	user provided pointer to multihost Persistent In Read
25470  *			Keys structure (mhioc_inkeys_t)
25471  *		flag -	this argument is a pass through to ddi_copyxxx()
25472  *			directly from the mode argument of ioctl().
25473  *
25474  * Return Code: 0   - Success
25475  *		EACCES
25476  *		ENOTSUP
25477  *		errno return code from sd_send_scsi_cmd()
25478  *
25479  *     Context: Can sleep. Does not return until command is completed.
25480  */
25481 
25482 static int
25483 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
25484     mhioc_inresvs_t *usrp, int flag)
25485 {
25486 #ifdef _MULTI_DATAMODEL
25487 	struct mhioc_resv_desc_list32 resvlist32;
25488 #endif
25489 	sd_prin_readresv_t	*in;
25490 	mhioc_inresvs_t		*ptr;
25491 	sd_readresv_desc_t	*readresv_ptr;
25492 	mhioc_resv_desc_list_t	resvlist;
25493 	mhioc_resv_desc_t 	resvdesc;
25494 	uchar_t			*data_bufp = NULL;
25495 	int 			data_len;
25496 	int			rval = 0;
25497 	int			i;
25498 	size_t			copysz;
25499 	mhioc_resv_desc_t	*bufp;
25500 	sd_ssc_t		*ssc;
25501 
25502 	if ((ptr = usrp) == NULL) {
25503 		return (EINVAL);
25504 	}
25505 
25506 	ssc = sd_ssc_init(un);
25507 
25508 	/*
25509 	 * Get the listsize from user
25510 	 */
25511 #ifdef _MULTI_DATAMODEL
25512 	switch (ddi_model_convert_from(flag & FMODELS)) {
25513 	case DDI_MODEL_ILP32:
25514 		copysz = sizeof (struct mhioc_resv_desc_list32);
25515 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
25516 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25517 			    "sd_persistent_reservation_in_read_resv: "
25518 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
25519 			rval = EFAULT;
25520 			goto done;
25521 		}
25522 		resvlist.listsize = resvlist32.listsize;
25523 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
25524 		break;
25525 
25526 	case DDI_MODEL_NONE:
25527 		copysz = sizeof (mhioc_resv_desc_list_t);
25528 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
25529 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25530 			    "sd_persistent_reservation_in_read_resv: "
25531 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
25532 			rval = EFAULT;
25533 			goto done;
25534 		}
25535 		break;
25536 	}
25537 #else /* ! _MULTI_DATAMODEL */
25538 	copysz = sizeof (mhioc_resv_desc_list_t);
25539 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
25540 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25541 		    "sd_persistent_reservation_in_read_resv: "
25542 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
25543 		rval = EFAULT;
25544 		goto done;
25545 	}
25546 #endif /* ! _MULTI_DATAMODEL */
25547 
25548 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
25549 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
25550 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
25551 
25552 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
25553 	    data_len, data_bufp);
25554 	if (rval != 0) {
25555 		if (rval == EIO)
25556 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
25557 		else
25558 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
25559 		goto done;
25560 	}
25561 	in = (sd_prin_readresv_t *)data_bufp;
25562 	ptr->generation = BE_32(in->generation);
25563 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
25564 
25565 	/*
25566 	 * Return the min(listsize, listlen( keys
25567 	 */
25568 #ifdef _MULTI_DATAMODEL
25569 
25570 	switch (ddi_model_convert_from(flag & FMODELS)) {
25571 	case DDI_MODEL_ILP32:
25572 		resvlist32.listlen = resvlist.listlen;
25573 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
25574 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25575 			    "sd_persistent_reservation_in_read_resv: "
25576 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
25577 			rval = EFAULT;
25578 			goto done;
25579 		}
25580 		break;
25581 
25582 	case DDI_MODEL_NONE:
25583 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
25584 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25585 			    "sd_persistent_reservation_in_read_resv: "
25586 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
25587 			rval = EFAULT;
25588 			goto done;
25589 		}
25590 		break;
25591 	}
25592 
25593 #else /* ! _MULTI_DATAMODEL */
25594 
25595 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
25596 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25597 		    "sd_persistent_reservation_in_read_resv: "
25598 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
25599 		rval = EFAULT;
25600 		goto done;
25601 	}
25602 
25603 #endif /* ! _MULTI_DATAMODEL */
25604 
25605 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
25606 	bufp = resvlist.list;
25607 	copysz = sizeof (mhioc_resv_desc_t);
25608 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
25609 	    i++, readresv_ptr++, bufp++) {
25610 
25611 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
25612 		    MHIOC_RESV_KEY_SIZE);
25613 		resvdesc.type  = readresv_ptr->type;
25614 		resvdesc.scope = readresv_ptr->scope;
25615 		resvdesc.scope_specific_addr =
25616 		    BE_32(readresv_ptr->scope_specific_addr);
25617 
25618 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
25619 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25620 			    "sd_persistent_reservation_in_read_resv: "
25621 			    "failed ddi_copyout: resvlist\n");
25622 			rval = EFAULT;
25623 			goto done;
25624 		}
25625 	}
25626 done:
25627 	sd_ssc_fini(ssc);
25628 	/* only if data_bufp is allocated, we need to free it */
25629 	if (data_bufp) {
25630 		kmem_free(data_bufp, data_len);
25631 	}
25632 	return (rval);
25633 }
25634 
25635 
25636 /*
25637  *    Function: sr_change_blkmode()
25638  *
25639  * Description: This routine is the driver entry point for handling CD-ROM
25640  *		block mode ioctl requests. Support for returning and changing
25641  *		the current block size in use by the device is implemented. The
25642  *		LBA size is changed via a MODE SELECT Block Descriptor.
25643  *
25644  *		This routine issues a mode sense with an allocation length of
25645  *		12 bytes for the mode page header and a single block descriptor.
25646  *
25647  *   Arguments: dev - the device 'dev_t'
25648  *		cmd - the request type; one of CDROMGBLKMODE (get) or
25649  *		      CDROMSBLKMODE (set)
25650  *		data - current block size or requested block size
25651  *		flag - this argument is a pass through to ddi_copyxxx() directly
25652  *		       from the mode argument of ioctl().
25653  *
25654  * Return Code: the code returned by sd_send_scsi_cmd()
25655  *		EINVAL if invalid arguments are provided
25656  *		EFAULT if ddi_copyxxx() fails
25657  *		ENXIO if fail ddi_get_soft_state
25658  *		EIO if invalid mode sense block descriptor length
25659  *
25660  */
25661 
25662 static int
25663 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
25664 {
25665 	struct sd_lun			*un = NULL;
25666 	struct mode_header		*sense_mhp, *select_mhp;
25667 	struct block_descriptor		*sense_desc, *select_desc;
25668 	int				current_bsize;
25669 	int				rval = EINVAL;
25670 	uchar_t				*sense = NULL;
25671 	uchar_t				*select = NULL;
25672 	sd_ssc_t			*ssc;
25673 
25674 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
25675 
25676 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25677 		return (ENXIO);
25678 	}
25679 
25680 	/*
25681 	 * The block length is changed via the Mode Select block descriptor, the
25682 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
25683 	 * required as part of this routine. Therefore the mode sense allocation
25684 	 * length is specified to be the length of a mode page header and a
25685 	 * block descriptor.
25686 	 */
25687 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
25688 
25689 	ssc = sd_ssc_init(un);
25690 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
25691 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
25692 	sd_ssc_fini(ssc);
25693 	if (rval != 0) {
25694 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25695 		    "sr_change_blkmode: Mode Sense Failed\n");
25696 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25697 		return (rval);
25698 	}
25699 
25700 	/* Check the block descriptor len to handle only 1 block descriptor */
25701 	sense_mhp = (struct mode_header *)sense;
25702 	if ((sense_mhp->bdesc_length == 0) ||
25703 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
25704 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25705 		    "sr_change_blkmode: Mode Sense returned invalid block"
25706 		    " descriptor length\n");
25707 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25708 		return (EIO);
25709 	}
25710 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
25711 	current_bsize = ((sense_desc->blksize_hi << 16) |
25712 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
25713 
25714 	/* Process command */
25715 	switch (cmd) {
25716 	case CDROMGBLKMODE:
25717 		/* Return the block size obtained during the mode sense */
25718 		if (ddi_copyout(&current_bsize, (void *)data,
25719 		    sizeof (int), flag) != 0)
25720 			rval = EFAULT;
25721 		break;
25722 	case CDROMSBLKMODE:
25723 		/* Validate the requested block size */
25724 		switch (data) {
25725 		case CDROM_BLK_512:
25726 		case CDROM_BLK_1024:
25727 		case CDROM_BLK_2048:
25728 		case CDROM_BLK_2056:
25729 		case CDROM_BLK_2336:
25730 		case CDROM_BLK_2340:
25731 		case CDROM_BLK_2352:
25732 		case CDROM_BLK_2368:
25733 		case CDROM_BLK_2448:
25734 		case CDROM_BLK_2646:
25735 		case CDROM_BLK_2647:
25736 			break;
25737 		default:
25738 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25739 			    "sr_change_blkmode: "
25740 			    "Block Size '%ld' Not Supported\n", data);
25741 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25742 			return (EINVAL);
25743 		}
25744 
25745 		/*
25746 		 * The current block size matches the requested block size so
25747 		 * there is no need to send the mode select to change the size
25748 		 */
25749 		if (current_bsize == data) {
25750 			break;
25751 		}
25752 
25753 		/* Build the select data for the requested block size */
25754 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
25755 		select_mhp = (struct mode_header *)select;
25756 		select_desc =
25757 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
25758 		/*
25759 		 * The LBA size is changed via the block descriptor, so the
25760 		 * descriptor is built according to the user data
25761 		 */
25762 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
25763 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
25764 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
25765 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
25766 
25767 		/* Send the mode select for the requested block size */
25768 		ssc = sd_ssc_init(un);
25769 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
25770 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
25771 		    SD_PATH_STANDARD);
25772 		sd_ssc_fini(ssc);
25773 		if (rval != 0) {
25774 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25775 			    "sr_change_blkmode: Mode Select Failed\n");
25776 			/*
25777 			 * The mode select failed for the requested block size,
25778 			 * so reset the data for the original block size and
25779 			 * send it to the target. The error is indicated by the
25780 			 * return value for the failed mode select.
25781 			 */
25782 			select_desc->blksize_hi  = sense_desc->blksize_hi;
25783 			select_desc->blksize_mid = sense_desc->blksize_mid;
25784 			select_desc->blksize_lo  = sense_desc->blksize_lo;
25785 			ssc = sd_ssc_init(un);
25786 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
25787 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
25788 			    SD_PATH_STANDARD);
25789 			sd_ssc_fini(ssc);
25790 		} else {
25791 			ASSERT(!mutex_owned(SD_MUTEX(un)));
25792 			mutex_enter(SD_MUTEX(un));
25793 			sd_update_block_info(un, (uint32_t)data, 0);
25794 			mutex_exit(SD_MUTEX(un));
25795 		}
25796 		break;
25797 	default:
25798 		/* should not reach here, but check anyway */
25799 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25800 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
25801 		rval = EINVAL;
25802 		break;
25803 	}
25804 
25805 	if (select) {
25806 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
25807 	}
25808 	if (sense) {
25809 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
25810 	}
25811 	return (rval);
25812 }
25813 
25814 
25815 /*
25816  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
25817  * implement driver support for getting and setting the CD speed. The command
25818  * set used will be based on the device type. If the device has not been
25819  * identified as MMC the Toshiba vendor specific mode page will be used. If
25820  * the device is MMC but does not support the Real Time Streaming feature
25821  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
25822  * be used to read the speed.
25823  */
25824 
25825 /*
25826  *    Function: sr_change_speed()
25827  *
25828  * Description: This routine is the driver entry point for handling CD-ROM
25829  *		drive speed ioctl requests for devices supporting the Toshiba
25830  *		vendor specific drive speed mode page. Support for returning
25831  *		and changing the current drive speed in use by the device is
25832  *		implemented.
25833  *
25834  *   Arguments: dev - the device 'dev_t'
25835  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
25836  *		      CDROMSDRVSPEED (set)
25837  *		data - current drive speed or requested drive speed
25838  *		flag - this argument is a pass through to ddi_copyxxx() directly
25839  *		       from the mode argument of ioctl().
25840  *
25841  * Return Code: the code returned by sd_send_scsi_cmd()
25842  *		EINVAL if invalid arguments are provided
25843  *		EFAULT if ddi_copyxxx() fails
25844  *		ENXIO if fail ddi_get_soft_state
25845  *		EIO if invalid mode sense block descriptor length
25846  */
25847 
25848 static int
25849 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
25850 {
25851 	struct sd_lun			*un = NULL;
25852 	struct mode_header		*sense_mhp, *select_mhp;
25853 	struct mode_speed		*sense_page, *select_page;
25854 	int				current_speed;
25855 	int				rval = EINVAL;
25856 	int				bd_len;
25857 	uchar_t				*sense = NULL;
25858 	uchar_t				*select = NULL;
25859 	sd_ssc_t			*ssc;
25860 
25861 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
25862 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25863 		return (ENXIO);
25864 	}
25865 
25866 	/*
25867 	 * Note: The drive speed is being modified here according to a Toshiba
25868 	 * vendor specific mode page (0x31).
25869 	 */
25870 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
25871 
25872 	ssc = sd_ssc_init(un);
25873 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
25874 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
25875 	    SD_PATH_STANDARD);
25876 	sd_ssc_fini(ssc);
25877 	if (rval != 0) {
25878 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25879 		    "sr_change_speed: Mode Sense Failed\n");
25880 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25881 		return (rval);
25882 	}
25883 	sense_mhp  = (struct mode_header *)sense;
25884 
25885 	/* Check the block descriptor len to handle only 1 block descriptor */
25886 	bd_len = sense_mhp->bdesc_length;
25887 	if (bd_len > MODE_BLK_DESC_LENGTH) {
25888 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25889 		    "sr_change_speed: Mode Sense returned invalid block "
25890 		    "descriptor length\n");
25891 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25892 		return (EIO);
25893 	}
25894 
25895 	sense_page = (struct mode_speed *)
25896 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
25897 	current_speed = sense_page->speed;
25898 
25899 	/* Process command */
25900 	switch (cmd) {
25901 	case CDROMGDRVSPEED:
25902 		/* Return the drive speed obtained during the mode sense */
25903 		if (current_speed == 0x2) {
25904 			current_speed = CDROM_TWELVE_SPEED;
25905 		}
25906 		if (ddi_copyout(&current_speed, (void *)data,
25907 		    sizeof (int), flag) != 0) {
25908 			rval = EFAULT;
25909 		}
25910 		break;
25911 	case CDROMSDRVSPEED:
25912 		/* Validate the requested drive speed */
25913 		switch ((uchar_t)data) {
25914 		case CDROM_TWELVE_SPEED:
25915 			data = 0x2;
25916 			/*FALLTHROUGH*/
25917 		case CDROM_NORMAL_SPEED:
25918 		case CDROM_DOUBLE_SPEED:
25919 		case CDROM_QUAD_SPEED:
25920 		case CDROM_MAXIMUM_SPEED:
25921 			break;
25922 		default:
25923 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25924 			    "sr_change_speed: "
25925 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
25926 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25927 			return (EINVAL);
25928 		}
25929 
25930 		/*
25931 		 * The current drive speed matches the requested drive speed so
25932 		 * there is no need to send the mode select to change the speed
25933 		 */
25934 		if (current_speed == data) {
25935 			break;
25936 		}
25937 
25938 		/* Build the select data for the requested drive speed */
25939 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
25940 		select_mhp = (struct mode_header *)select;
25941 		select_mhp->bdesc_length = 0;
25942 		select_page =
25943 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
25944 		select_page =
25945 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
25946 		select_page->mode_page.code = CDROM_MODE_SPEED;
25947 		select_page->mode_page.length = 2;
25948 		select_page->speed = (uchar_t)data;
25949 
25950 		/* Send the mode select for the requested block size */
25951 		ssc = sd_ssc_init(un);
25952 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
25953 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
25954 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25955 		sd_ssc_fini(ssc);
25956 		if (rval != 0) {
25957 			/*
25958 			 * The mode select failed for the requested drive speed,
25959 			 * so reset the data for the original drive speed and
25960 			 * send it to the target. The error is indicated by the
25961 			 * return value for the failed mode select.
25962 			 */
25963 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25964 			    "sr_drive_speed: Mode Select Failed\n");
25965 			select_page->speed = sense_page->speed;
25966 			ssc = sd_ssc_init(un);
25967 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
25968 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
25969 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25970 			sd_ssc_fini(ssc);
25971 		}
25972 		break;
25973 	default:
25974 		/* should not reach here, but check anyway */
25975 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25976 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
25977 		rval = EINVAL;
25978 		break;
25979 	}
25980 
25981 	if (select) {
25982 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
25983 	}
25984 	if (sense) {
25985 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
25986 	}
25987 
25988 	return (rval);
25989 }
25990 
25991 
25992 /*
25993  *    Function: sr_atapi_change_speed()
25994  *
25995  * Description: This routine is the driver entry point for handling CD-ROM
25996  *		drive speed ioctl requests for MMC devices that do not support
25997  *		the Real Time Streaming feature (0x107).
25998  *
25999  *		Note: This routine will use the SET SPEED command which may not
26000  *		be supported by all devices.
26001  *
26002  *   Arguments: dev- the device 'dev_t'
26003  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
26004  *		     CDROMSDRVSPEED (set)
26005  *		data- current drive speed or requested drive speed
26006  *		flag- this argument is a pass through to ddi_copyxxx() directly
26007  *		      from the mode argument of ioctl().
26008  *
26009  * Return Code: the code returned by sd_send_scsi_cmd()
26010  *		EINVAL if invalid arguments are provided
26011  *		EFAULT if ddi_copyxxx() fails
26012  *		ENXIO if fail ddi_get_soft_state
26013  *		EIO if invalid mode sense block descriptor length
26014  */
26015 
26016 static int
26017 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
26018 {
26019 	struct sd_lun			*un;
26020 	struct uscsi_cmd		*com = NULL;
26021 	struct mode_header_grp2		*sense_mhp;
26022 	uchar_t				*sense_page;
26023 	uchar_t				*sense = NULL;
26024 	char				cdb[CDB_GROUP5];
26025 	int				bd_len;
26026 	int				current_speed = 0;
26027 	int				max_speed = 0;
26028 	int				rval;
26029 	sd_ssc_t			*ssc;
26030 
26031 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
26032 
26033 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26034 		return (ENXIO);
26035 	}
26036 
26037 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
26038 
26039 	ssc = sd_ssc_init(un);
26040 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
26041 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
26042 	    SD_PATH_STANDARD);
26043 	sd_ssc_fini(ssc);
26044 	if (rval != 0) {
26045 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26046 		    "sr_atapi_change_speed: Mode Sense Failed\n");
26047 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26048 		return (rval);
26049 	}
26050 
26051 	/* Check the block descriptor len to handle only 1 block descriptor */
26052 	sense_mhp = (struct mode_header_grp2 *)sense;
26053 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
26054 	if (bd_len > MODE_BLK_DESC_LENGTH) {
26055 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26056 		    "sr_atapi_change_speed: Mode Sense returned invalid "
26057 		    "block descriptor length\n");
26058 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26059 		return (EIO);
26060 	}
26061 
26062 	/* Calculate the current and maximum drive speeds */
26063 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
26064 	current_speed = (sense_page[14] << 8) | sense_page[15];
26065 	max_speed = (sense_page[8] << 8) | sense_page[9];
26066 
26067 	/* Process the command */
26068 	switch (cmd) {
26069 	case CDROMGDRVSPEED:
26070 		current_speed /= SD_SPEED_1X;
26071 		if (ddi_copyout(&current_speed, (void *)data,
26072 		    sizeof (int), flag) != 0)
26073 			rval = EFAULT;
26074 		break;
26075 	case CDROMSDRVSPEED:
26076 		/* Convert the speed code to KB/sec */
26077 		switch ((uchar_t)data) {
26078 		case CDROM_NORMAL_SPEED:
26079 			current_speed = SD_SPEED_1X;
26080 			break;
26081 		case CDROM_DOUBLE_SPEED:
26082 			current_speed = 2 * SD_SPEED_1X;
26083 			break;
26084 		case CDROM_QUAD_SPEED:
26085 			current_speed = 4 * SD_SPEED_1X;
26086 			break;
26087 		case CDROM_TWELVE_SPEED:
26088 			current_speed = 12 * SD_SPEED_1X;
26089 			break;
26090 		case CDROM_MAXIMUM_SPEED:
26091 			current_speed = 0xffff;
26092 			break;
26093 		default:
26094 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26095 			    "sr_atapi_change_speed: invalid drive speed %d\n",
26096 			    (uchar_t)data);
26097 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26098 			return (EINVAL);
26099 		}
26100 
26101 		/* Check the request against the drive's max speed. */
26102 		if (current_speed != 0xffff) {
26103 			if (current_speed > max_speed) {
26104 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26105 				return (EINVAL);
26106 			}
26107 		}
26108 
26109 		/*
26110 		 * Build and send the SET SPEED command
26111 		 *
26112 		 * Note: The SET SPEED (0xBB) command used in this routine is
26113 		 * obsolete per the SCSI MMC spec but still supported in the
26114 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
26115 		 * therefore the command is still implemented in this routine.
26116 		 */
26117 		bzero(cdb, sizeof (cdb));
26118 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
26119 		cdb[2] = (uchar_t)(current_speed >> 8);
26120 		cdb[3] = (uchar_t)current_speed;
26121 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26122 		com->uscsi_cdb	   = (caddr_t)cdb;
26123 		com->uscsi_cdblen  = CDB_GROUP5;
26124 		com->uscsi_bufaddr = NULL;
26125 		com->uscsi_buflen  = 0;
26126 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
26127 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
26128 		break;
26129 	default:
26130 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26131 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
26132 		rval = EINVAL;
26133 	}
26134 
26135 	if (sense) {
26136 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
26137 	}
26138 	if (com) {
26139 		kmem_free(com, sizeof (*com));
26140 	}
26141 	return (rval);
26142 }
26143 
26144 
26145 /*
26146  *    Function: sr_pause_resume()
26147  *
26148  * Description: This routine is the driver entry point for handling CD-ROM
26149  *		pause/resume ioctl requests. This only affects the audio play
26150  *		operation.
26151  *
26152  *   Arguments: dev - the device 'dev_t'
26153  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
26154  *		      for setting the resume bit of the cdb.
26155  *
26156  * Return Code: the code returned by sd_send_scsi_cmd()
26157  *		EINVAL if invalid mode specified
26158  *
26159  */
26160 
26161 static int
26162 sr_pause_resume(dev_t dev, int cmd)
26163 {
26164 	struct sd_lun		*un;
26165 	struct uscsi_cmd	*com;
26166 	char			cdb[CDB_GROUP1];
26167 	int			rval;
26168 
26169 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26170 		return (ENXIO);
26171 	}
26172 
26173 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26174 	bzero(cdb, CDB_GROUP1);
26175 	cdb[0] = SCMD_PAUSE_RESUME;
26176 	switch (cmd) {
26177 	case CDROMRESUME:
26178 		cdb[8] = 1;
26179 		break;
26180 	case CDROMPAUSE:
26181 		cdb[8] = 0;
26182 		break;
26183 	default:
26184 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
26185 		    " Command '%x' Not Supported\n", cmd);
26186 		rval = EINVAL;
26187 		goto done;
26188 	}
26189 
26190 	com->uscsi_cdb    = cdb;
26191 	com->uscsi_cdblen = CDB_GROUP1;
26192 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
26193 
26194 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26195 	    SD_PATH_STANDARD);
26196 
26197 done:
26198 	kmem_free(com, sizeof (*com));
26199 	return (rval);
26200 }
26201 
26202 
26203 /*
26204  *    Function: sr_play_msf()
26205  *
26206  * Description: This routine is the driver entry point for handling CD-ROM
26207  *		ioctl requests to output the audio signals at the specified
26208  *		starting address and continue the audio play until the specified
26209  *		ending address (CDROMPLAYMSF) The address is in Minute Second
26210  *		Frame (MSF) format.
26211  *
26212  *   Arguments: dev	- the device 'dev_t'
26213  *		data	- pointer to user provided audio msf structure,
26214  *		          specifying start/end addresses.
26215  *		flag	- this argument is a pass through to ddi_copyxxx()
26216  *		          directly from the mode argument of ioctl().
26217  *
26218  * Return Code: the code returned by sd_send_scsi_cmd()
26219  *		EFAULT if ddi_copyxxx() fails
26220  *		ENXIO if fail ddi_get_soft_state
26221  *		EINVAL if data pointer is NULL
26222  */
26223 
26224 static int
26225 sr_play_msf(dev_t dev, caddr_t data, int flag)
26226 {
26227 	struct sd_lun		*un;
26228 	struct uscsi_cmd	*com;
26229 	struct cdrom_msf	msf_struct;
26230 	struct cdrom_msf	*msf = &msf_struct;
26231 	char			cdb[CDB_GROUP1];
26232 	int			rval;
26233 
26234 	if (data == NULL) {
26235 		return (EINVAL);
26236 	}
26237 
26238 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26239 		return (ENXIO);
26240 	}
26241 
26242 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
26243 		return (EFAULT);
26244 	}
26245 
26246 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26247 	bzero(cdb, CDB_GROUP1);
26248 	cdb[0] = SCMD_PLAYAUDIO_MSF;
26249 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
26250 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
26251 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
26252 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
26253 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
26254 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
26255 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
26256 	} else {
26257 		cdb[3] = msf->cdmsf_min0;
26258 		cdb[4] = msf->cdmsf_sec0;
26259 		cdb[5] = msf->cdmsf_frame0;
26260 		cdb[6] = msf->cdmsf_min1;
26261 		cdb[7] = msf->cdmsf_sec1;
26262 		cdb[8] = msf->cdmsf_frame1;
26263 	}
26264 	com->uscsi_cdb    = cdb;
26265 	com->uscsi_cdblen = CDB_GROUP1;
26266 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
26267 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26268 	    SD_PATH_STANDARD);
26269 	kmem_free(com, sizeof (*com));
26270 	return (rval);
26271 }
26272 
26273 
26274 /*
26275  *    Function: sr_play_trkind()
26276  *
26277  * Description: This routine is the driver entry point for handling CD-ROM
26278  *		ioctl requests to output the audio signals at the specified
26279  *		starting address and continue the audio play until the specified
26280  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
26281  *		format.
26282  *
26283  *   Arguments: dev	- the device 'dev_t'
26284  *		data	- pointer to user provided audio track/index structure,
26285  *		          specifying start/end addresses.
26286  *		flag	- this argument is a pass through to ddi_copyxxx()
26287  *		          directly from the mode argument of ioctl().
26288  *
26289  * Return Code: the code returned by sd_send_scsi_cmd()
26290  *		EFAULT if ddi_copyxxx() fails
26291  *		ENXIO if fail ddi_get_soft_state
26292  *		EINVAL if data pointer is NULL
26293  */
26294 
26295 static int
26296 sr_play_trkind(dev_t dev, caddr_t data, int flag)
26297 {
26298 	struct cdrom_ti		ti_struct;
26299 	struct cdrom_ti		*ti = &ti_struct;
26300 	struct uscsi_cmd	*com = NULL;
26301 	char			cdb[CDB_GROUP1];
26302 	int			rval;
26303 
26304 	if (data == NULL) {
26305 		return (EINVAL);
26306 	}
26307 
26308 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
26309 		return (EFAULT);
26310 	}
26311 
26312 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26313 	bzero(cdb, CDB_GROUP1);
26314 	cdb[0] = SCMD_PLAYAUDIO_TI;
26315 	cdb[4] = ti->cdti_trk0;
26316 	cdb[5] = ti->cdti_ind0;
26317 	cdb[7] = ti->cdti_trk1;
26318 	cdb[8] = ti->cdti_ind1;
26319 	com->uscsi_cdb    = cdb;
26320 	com->uscsi_cdblen = CDB_GROUP1;
26321 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
26322 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26323 	    SD_PATH_STANDARD);
26324 	kmem_free(com, sizeof (*com));
26325 	return (rval);
26326 }
26327 
26328 
26329 /*
26330  *    Function: sr_read_all_subcodes()
26331  *
26332  * Description: This routine is the driver entry point for handling CD-ROM
26333  *		ioctl requests to return raw subcode data while the target is
26334  *		playing audio (CDROMSUBCODE).
26335  *
26336  *   Arguments: dev	- the device 'dev_t'
26337  *		data	- pointer to user provided cdrom subcode structure,
26338  *		          specifying the transfer length and address.
26339  *		flag	- this argument is a pass through to ddi_copyxxx()
26340  *		          directly from the mode argument of ioctl().
26341  *
26342  * Return Code: the code returned by sd_send_scsi_cmd()
26343  *		EFAULT if ddi_copyxxx() fails
26344  *		ENXIO if fail ddi_get_soft_state
26345  *		EINVAL if data pointer is NULL
26346  */
26347 
26348 static int
26349 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
26350 {
26351 	struct sd_lun		*un = NULL;
26352 	struct uscsi_cmd	*com = NULL;
26353 	struct cdrom_subcode	*subcode = NULL;
26354 	int			rval;
26355 	size_t			buflen;
26356 	char			cdb[CDB_GROUP5];
26357 
26358 #ifdef _MULTI_DATAMODEL
26359 	/* To support ILP32 applications in an LP64 world */
26360 	struct cdrom_subcode32		cdrom_subcode32;
26361 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
26362 #endif
26363 	if (data == NULL) {
26364 		return (EINVAL);
26365 	}
26366 
26367 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26368 		return (ENXIO);
26369 	}
26370 
26371 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
26372 
26373 #ifdef _MULTI_DATAMODEL
26374 	switch (ddi_model_convert_from(flag & FMODELS)) {
26375 	case DDI_MODEL_ILP32:
26376 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
26377 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26378 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
26379 			kmem_free(subcode, sizeof (struct cdrom_subcode));
26380 			return (EFAULT);
26381 		}
26382 		/* Convert the ILP32 uscsi data from the application to LP64 */
26383 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
26384 		break;
26385 	case DDI_MODEL_NONE:
26386 		if (ddi_copyin(data, subcode,
26387 		    sizeof (struct cdrom_subcode), flag)) {
26388 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26389 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
26390 			kmem_free(subcode, sizeof (struct cdrom_subcode));
26391 			return (EFAULT);
26392 		}
26393 		break;
26394 	}
26395 #else /* ! _MULTI_DATAMODEL */
26396 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
26397 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26398 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
26399 		kmem_free(subcode, sizeof (struct cdrom_subcode));
26400 		return (EFAULT);
26401 	}
26402 #endif /* _MULTI_DATAMODEL */
26403 
26404 	/*
26405 	 * Since MMC-2 expects max 3 bytes for length, check if the
26406 	 * length input is greater than 3 bytes
26407 	 */
26408 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
26409 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26410 		    "sr_read_all_subcodes: "
26411 		    "cdrom transfer length too large: %d (limit %d)\n",
26412 		    subcode->cdsc_length, 0xFFFFFF);
26413 		kmem_free(subcode, sizeof (struct cdrom_subcode));
26414 		return (EINVAL);
26415 	}
26416 
26417 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
26418 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26419 	bzero(cdb, CDB_GROUP5);
26420 
26421 	if (un->un_f_mmc_cap == TRUE) {
26422 		cdb[0] = (char)SCMD_READ_CD;
26423 		cdb[2] = (char)0xff;
26424 		cdb[3] = (char)0xff;
26425 		cdb[4] = (char)0xff;
26426 		cdb[5] = (char)0xff;
26427 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
26428 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
26429 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
26430 		cdb[10] = 1;
26431 	} else {
26432 		/*
26433 		 * Note: A vendor specific command (0xDF) is being used her to
26434 		 * request a read of all subcodes.
26435 		 */
26436 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
26437 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
26438 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
26439 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
26440 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
26441 	}
26442 	com->uscsi_cdb	   = cdb;
26443 	com->uscsi_cdblen  = CDB_GROUP5;
26444 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
26445 	com->uscsi_buflen  = buflen;
26446 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26447 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
26448 	    SD_PATH_STANDARD);
26449 	kmem_free(subcode, sizeof (struct cdrom_subcode));
26450 	kmem_free(com, sizeof (*com));
26451 	return (rval);
26452 }
26453 
26454 
26455 /*
26456  *    Function: sr_read_subchannel()
26457  *
26458  * Description: This routine is the driver entry point for handling CD-ROM
26459  *		ioctl requests to return the Q sub-channel data of the CD
26460  *		current position block. (CDROMSUBCHNL) The data includes the
26461  *		track number, index number, absolute CD-ROM address (LBA or MSF
26462  *		format per the user) , track relative CD-ROM address (LBA or MSF
26463  *		format per the user), control data and audio status.
26464  *
26465  *   Arguments: dev	- the device 'dev_t'
26466  *		data	- pointer to user provided cdrom sub-channel structure
26467  *		flag	- this argument is a pass through to ddi_copyxxx()
26468  *		          directly from the mode argument of ioctl().
26469  *
26470  * Return Code: the code returned by sd_send_scsi_cmd()
26471  *		EFAULT if ddi_copyxxx() fails
26472  *		ENXIO if fail ddi_get_soft_state
26473  *		EINVAL if data pointer is NULL
26474  */
26475 
26476 static int
26477 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
26478 {
26479 	struct sd_lun		*un;
26480 	struct uscsi_cmd	*com;
26481 	struct cdrom_subchnl	subchanel;
26482 	struct cdrom_subchnl	*subchnl = &subchanel;
26483 	char			cdb[CDB_GROUP1];
26484 	caddr_t			buffer;
26485 	int			rval;
26486 
26487 	if (data == NULL) {
26488 		return (EINVAL);
26489 	}
26490 
26491 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26492 	    (un->un_state == SD_STATE_OFFLINE)) {
26493 		return (ENXIO);
26494 	}
26495 
26496 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
26497 		return (EFAULT);
26498 	}
26499 
26500 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
26501 	bzero(cdb, CDB_GROUP1);
26502 	cdb[0] = SCMD_READ_SUBCHANNEL;
26503 	/* Set the MSF bit based on the user requested address format */
26504 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
26505 	/*
26506 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
26507 	 * returned
26508 	 */
26509 	cdb[2] = 0x40;
26510 	/*
26511 	 * Set byte 3 to specify the return data format. A value of 0x01
26512 	 * indicates that the CD-ROM current position should be returned.
26513 	 */
26514 	cdb[3] = 0x01;
26515 	cdb[8] = 0x10;
26516 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26517 	com->uscsi_cdb	   = cdb;
26518 	com->uscsi_cdblen  = CDB_GROUP1;
26519 	com->uscsi_bufaddr = buffer;
26520 	com->uscsi_buflen  = 16;
26521 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26522 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26523 	    SD_PATH_STANDARD);
26524 	if (rval != 0) {
26525 		kmem_free(buffer, 16);
26526 		kmem_free(com, sizeof (*com));
26527 		return (rval);
26528 	}
26529 
26530 	/* Process the returned Q sub-channel data */
26531 	subchnl->cdsc_audiostatus = buffer[1];
26532 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
26533 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
26534 	subchnl->cdsc_trk	= buffer[6];
26535 	subchnl->cdsc_ind	= buffer[7];
26536 	if (subchnl->cdsc_format & CDROM_LBA) {
26537 		subchnl->cdsc_absaddr.lba =
26538 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26539 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26540 		subchnl->cdsc_reladdr.lba =
26541 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
26542 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
26543 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
26544 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
26545 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
26546 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
26547 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
26548 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
26549 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
26550 	} else {
26551 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
26552 		subchnl->cdsc_absaddr.msf.second = buffer[10];
26553 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
26554 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
26555 		subchnl->cdsc_reladdr.msf.second = buffer[14];
26556 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
26557 	}
26558 	kmem_free(buffer, 16);
26559 	kmem_free(com, sizeof (*com));
26560 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
26561 	    != 0) {
26562 		return (EFAULT);
26563 	}
26564 	return (rval);
26565 }
26566 
26567 
26568 /*
26569  *    Function: sr_read_tocentry()
26570  *
26571  * Description: This routine is the driver entry point for handling CD-ROM
26572  *		ioctl requests to read from the Table of Contents (TOC)
26573  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
26574  *		fields, the starting address (LBA or MSF format per the user)
26575  *		and the data mode if the user specified track is a data track.
26576  *
26577  *		Note: The READ HEADER (0x44) command used in this routine is
26578  *		obsolete per the SCSI MMC spec but still supported in the
26579  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
26580  *		therefore the command is still implemented in this routine.
26581  *
26582  *   Arguments: dev	- the device 'dev_t'
26583  *		data	- pointer to user provided toc entry structure,
26584  *			  specifying the track # and the address format
26585  *			  (LBA or MSF).
26586  *		flag	- this argument is a pass through to ddi_copyxxx()
26587  *		          directly from the mode argument of ioctl().
26588  *
26589  * Return Code: the code returned by sd_send_scsi_cmd()
26590  *		EFAULT if ddi_copyxxx() fails
26591  *		ENXIO if fail ddi_get_soft_state
26592  *		EINVAL if data pointer is NULL
26593  */
26594 
26595 static int
26596 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
26597 {
26598 	struct sd_lun		*un = NULL;
26599 	struct uscsi_cmd	*com;
26600 	struct cdrom_tocentry	toc_entry;
26601 	struct cdrom_tocentry	*entry = &toc_entry;
26602 	caddr_t			buffer;
26603 	int			rval;
26604 	char			cdb[CDB_GROUP1];
26605 
26606 	if (data == NULL) {
26607 		return (EINVAL);
26608 	}
26609 
26610 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26611 	    (un->un_state == SD_STATE_OFFLINE)) {
26612 		return (ENXIO);
26613 	}
26614 
26615 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
26616 		return (EFAULT);
26617 	}
26618 
26619 	/* Validate the requested track and address format */
26620 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
26621 		return (EINVAL);
26622 	}
26623 
26624 	if (entry->cdte_track == 0) {
26625 		return (EINVAL);
26626 	}
26627 
26628 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
26629 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26630 	bzero(cdb, CDB_GROUP1);
26631 
26632 	cdb[0] = SCMD_READ_TOC;
26633 	/* Set the MSF bit based on the user requested address format  */
26634 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
26635 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
26636 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
26637 	} else {
26638 		cdb[6] = entry->cdte_track;
26639 	}
26640 
26641 	/*
26642 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
26643 	 * (4 byte TOC response header + 8 byte track descriptor)
26644 	 */
26645 	cdb[8] = 12;
26646 	com->uscsi_cdb	   = cdb;
26647 	com->uscsi_cdblen  = CDB_GROUP1;
26648 	com->uscsi_bufaddr = buffer;
26649 	com->uscsi_buflen  = 0x0C;
26650 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
26651 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26652 	    SD_PATH_STANDARD);
26653 	if (rval != 0) {
26654 		kmem_free(buffer, 12);
26655 		kmem_free(com, sizeof (*com));
26656 		return (rval);
26657 	}
26658 
26659 	/* Process the toc entry */
26660 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
26661 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
26662 	if (entry->cdte_format & CDROM_LBA) {
26663 		entry->cdte_addr.lba =
26664 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26665 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26666 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
26667 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
26668 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
26669 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
26670 		/*
26671 		 * Send a READ TOC command using the LBA address format to get
26672 		 * the LBA for the track requested so it can be used in the
26673 		 * READ HEADER request
26674 		 *
26675 		 * Note: The MSF bit of the READ HEADER command specifies the
26676 		 * output format. The block address specified in that command
26677 		 * must be in LBA format.
26678 		 */
26679 		cdb[1] = 0;
26680 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26681 		    SD_PATH_STANDARD);
26682 		if (rval != 0) {
26683 			kmem_free(buffer, 12);
26684 			kmem_free(com, sizeof (*com));
26685 			return (rval);
26686 		}
26687 	} else {
26688 		entry->cdte_addr.msf.minute	= buffer[9];
26689 		entry->cdte_addr.msf.second	= buffer[10];
26690 		entry->cdte_addr.msf.frame	= buffer[11];
26691 		/*
26692 		 * Send a READ TOC command using the LBA address format to get
26693 		 * the LBA for the track requested so it can be used in the
26694 		 * READ HEADER request
26695 		 *
26696 		 * Note: The MSF bit of the READ HEADER command specifies the
26697 		 * output format. The block address specified in that command
26698 		 * must be in LBA format.
26699 		 */
26700 		cdb[1] = 0;
26701 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26702 		    SD_PATH_STANDARD);
26703 		if (rval != 0) {
26704 			kmem_free(buffer, 12);
26705 			kmem_free(com, sizeof (*com));
26706 			return (rval);
26707 		}
26708 	}
26709 
26710 	/*
26711 	 * Build and send the READ HEADER command to determine the data mode of
26712 	 * the user specified track.
26713 	 */
26714 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
26715 	    (entry->cdte_track != CDROM_LEADOUT)) {
26716 		bzero(cdb, CDB_GROUP1);
26717 		cdb[0] = SCMD_READ_HEADER;
26718 		cdb[2] = buffer[8];
26719 		cdb[3] = buffer[9];
26720 		cdb[4] = buffer[10];
26721 		cdb[5] = buffer[11];
26722 		cdb[8] = 0x08;
26723 		com->uscsi_buflen = 0x08;
26724 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26725 		    SD_PATH_STANDARD);
26726 		if (rval == 0) {
26727 			entry->cdte_datamode = buffer[0];
26728 		} else {
26729 			/*
26730 			 * READ HEADER command failed, since this is
26731 			 * obsoleted in one spec, its better to return
26732 			 * -1 for an invlid track so that we can still
26733 			 * receive the rest of the TOC data.
26734 			 */
26735 			entry->cdte_datamode = (uchar_t)-1;
26736 		}
26737 	} else {
26738 		entry->cdte_datamode = (uchar_t)-1;
26739 	}
26740 
26741 	kmem_free(buffer, 12);
26742 	kmem_free(com, sizeof (*com));
26743 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
26744 		return (EFAULT);
26745 
26746 	return (rval);
26747 }
26748 
26749 
26750 /*
26751  *    Function: sr_read_tochdr()
26752  *
26753  * Description: This routine is the driver entry point for handling CD-ROM
26754  * 		ioctl requests to read the Table of Contents (TOC) header
26755  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
26756  *		and ending track numbers
26757  *
26758  *   Arguments: dev	- the device 'dev_t'
26759  *		data	- pointer to user provided toc header structure,
26760  *			  specifying the starting and ending track numbers.
26761  *		flag	- this argument is a pass through to ddi_copyxxx()
26762  *			  directly from the mode argument of ioctl().
26763  *
26764  * Return Code: the code returned by sd_send_scsi_cmd()
26765  *		EFAULT if ddi_copyxxx() fails
26766  *		ENXIO if fail ddi_get_soft_state
26767  *		EINVAL if data pointer is NULL
26768  */
26769 
26770 static int
26771 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
26772 {
26773 	struct sd_lun		*un;
26774 	struct uscsi_cmd	*com;
26775 	struct cdrom_tochdr	toc_header;
26776 	struct cdrom_tochdr	*hdr = &toc_header;
26777 	char			cdb[CDB_GROUP1];
26778 	int			rval;
26779 	caddr_t			buffer;
26780 
26781 	if (data == NULL) {
26782 		return (EINVAL);
26783 	}
26784 
26785 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26786 	    (un->un_state == SD_STATE_OFFLINE)) {
26787 		return (ENXIO);
26788 	}
26789 
26790 	buffer = kmem_zalloc(4, KM_SLEEP);
26791 	bzero(cdb, CDB_GROUP1);
26792 	cdb[0] = SCMD_READ_TOC;
26793 	/*
26794 	 * Specifying a track number of 0x00 in the READ TOC command indicates
26795 	 * that the TOC header should be returned
26796 	 */
26797 	cdb[6] = 0x00;
26798 	/*
26799 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
26800 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
26801 	 */
26802 	cdb[8] = 0x04;
26803 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26804 	com->uscsi_cdb	   = cdb;
26805 	com->uscsi_cdblen  = CDB_GROUP1;
26806 	com->uscsi_bufaddr = buffer;
26807 	com->uscsi_buflen  = 0x04;
26808 	com->uscsi_timeout = 300;
26809 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26810 
26811 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26812 	    SD_PATH_STANDARD);
26813 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
26814 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
26815 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
26816 	} else {
26817 		hdr->cdth_trk0 = buffer[2];
26818 		hdr->cdth_trk1 = buffer[3];
26819 	}
26820 	kmem_free(buffer, 4);
26821 	kmem_free(com, sizeof (*com));
26822 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
26823 		return (EFAULT);
26824 	}
26825 	return (rval);
26826 }
26827 
26828 
26829 /*
26830  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
26831  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
26832  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
26833  * digital audio and extended architecture digital audio. These modes are
26834  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
26835  * MMC specs.
26836  *
26837  * In addition to support for the various data formats these routines also
26838  * include support for devices that implement only the direct access READ
26839  * commands (0x08, 0x28), devices that implement the READ_CD commands
26840  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
26841  * READ CDXA commands (0xD8, 0xDB)
26842  */
26843 
26844 /*
26845  *    Function: sr_read_mode1()
26846  *
26847  * Description: This routine is the driver entry point for handling CD-ROM
26848  *		ioctl read mode1 requests (CDROMREADMODE1).
26849  *
26850  *   Arguments: dev	- the device 'dev_t'
26851  *		data	- pointer to user provided cd read structure specifying
26852  *			  the lba buffer address and length.
26853  *		flag	- this argument is a pass through to ddi_copyxxx()
26854  *			  directly from the mode argument of ioctl().
26855  *
26856  * Return Code: the code returned by sd_send_scsi_cmd()
26857  *		EFAULT if ddi_copyxxx() fails
26858  *		ENXIO if fail ddi_get_soft_state
26859  *		EINVAL if data pointer is NULL
26860  */
26861 
26862 static int
26863 sr_read_mode1(dev_t dev, caddr_t data, int flag)
26864 {
26865 	struct sd_lun		*un;
26866 	struct cdrom_read	mode1_struct;
26867 	struct cdrom_read	*mode1 = &mode1_struct;
26868 	int			rval;
26869 	sd_ssc_t		*ssc;
26870 
26871 #ifdef _MULTI_DATAMODEL
26872 	/* To support ILP32 applications in an LP64 world */
26873 	struct cdrom_read32	cdrom_read32;
26874 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
26875 #endif /* _MULTI_DATAMODEL */
26876 
26877 	if (data == NULL) {
26878 		return (EINVAL);
26879 	}
26880 
26881 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26882 	    (un->un_state == SD_STATE_OFFLINE)) {
26883 		return (ENXIO);
26884 	}
26885 
26886 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
26887 	    "sd_read_mode1: entry: un:0x%p\n", un);
26888 
26889 #ifdef _MULTI_DATAMODEL
26890 	switch (ddi_model_convert_from(flag & FMODELS)) {
26891 	case DDI_MODEL_ILP32:
26892 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
26893 			return (EFAULT);
26894 		}
26895 		/* Convert the ILP32 uscsi data from the application to LP64 */
26896 		cdrom_read32tocdrom_read(cdrd32, mode1);
26897 		break;
26898 	case DDI_MODEL_NONE:
26899 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
26900 			return (EFAULT);
26901 		}
26902 	}
26903 #else /* ! _MULTI_DATAMODEL */
26904 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
26905 		return (EFAULT);
26906 	}
26907 #endif /* _MULTI_DATAMODEL */
26908 
26909 	ssc = sd_ssc_init(un);
26910 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
26911 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
26912 	sd_ssc_fini(ssc);
26913 
26914 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
26915 	    "sd_read_mode1: exit: un:0x%p\n", un);
26916 
26917 	return (rval);
26918 }
26919 
26920 
26921 /*
26922  *    Function: sr_read_cd_mode2()
26923  *
26924  * Description: This routine is the driver entry point for handling CD-ROM
26925  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
26926  *		support the READ CD (0xBE) command or the 1st generation
26927  *		READ CD (0xD4) command.
26928  *
26929  *   Arguments: dev	- the device 'dev_t'
26930  *		data	- pointer to user provided cd read structure specifying
26931  *			  the lba buffer address and length.
26932  *		flag	- this argument is a pass through to ddi_copyxxx()
26933  *			  directly from the mode argument of ioctl().
26934  *
26935  * Return Code: the code returned by sd_send_scsi_cmd()
26936  *		EFAULT if ddi_copyxxx() fails
26937  *		ENXIO if fail ddi_get_soft_state
26938  *		EINVAL if data pointer is NULL
26939  */
26940 
26941 static int
26942 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
26943 {
26944 	struct sd_lun		*un;
26945 	struct uscsi_cmd	*com;
26946 	struct cdrom_read	mode2_struct;
26947 	struct cdrom_read	*mode2 = &mode2_struct;
26948 	uchar_t			cdb[CDB_GROUP5];
26949 	int			nblocks;
26950 	int			rval;
26951 #ifdef _MULTI_DATAMODEL
26952 	/*  To support ILP32 applications in an LP64 world */
26953 	struct cdrom_read32	cdrom_read32;
26954 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
26955 #endif /* _MULTI_DATAMODEL */
26956 
26957 	if (data == NULL) {
26958 		return (EINVAL);
26959 	}
26960 
26961 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26962 	    (un->un_state == SD_STATE_OFFLINE)) {
26963 		return (ENXIO);
26964 	}
26965 
26966 #ifdef _MULTI_DATAMODEL
26967 	switch (ddi_model_convert_from(flag & FMODELS)) {
26968 	case DDI_MODEL_ILP32:
26969 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
26970 			return (EFAULT);
26971 		}
26972 		/* Convert the ILP32 uscsi data from the application to LP64 */
26973 		cdrom_read32tocdrom_read(cdrd32, mode2);
26974 		break;
26975 	case DDI_MODEL_NONE:
26976 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
26977 			return (EFAULT);
26978 		}
26979 		break;
26980 	}
26981 
26982 #else /* ! _MULTI_DATAMODEL */
26983 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
26984 		return (EFAULT);
26985 	}
26986 #endif /* _MULTI_DATAMODEL */
26987 
26988 	bzero(cdb, sizeof (cdb));
26989 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
26990 		/* Read command supported by 1st generation atapi drives */
26991 		cdb[0] = SCMD_READ_CDD4;
26992 	} else {
26993 		/* Universal CD Access Command */
26994 		cdb[0] = SCMD_READ_CD;
26995 	}
26996 
26997 	/*
26998 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
26999 	 */
27000 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
27001 
27002 	/* set the start address */
27003 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
27004 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
27005 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
27006 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
27007 
27008 	/* set the transfer length */
27009 	nblocks = mode2->cdread_buflen / 2336;
27010 	cdb[6] = (uchar_t)(nblocks >> 16);
27011 	cdb[7] = (uchar_t)(nblocks >> 8);
27012 	cdb[8] = (uchar_t)nblocks;
27013 
27014 	/* set the filter bits */
27015 	cdb[9] = CDROM_READ_CD_USERDATA;
27016 
27017 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27018 	com->uscsi_cdb = (caddr_t)cdb;
27019 	com->uscsi_cdblen = sizeof (cdb);
27020 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
27021 	com->uscsi_buflen = mode2->cdread_buflen;
27022 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27023 
27024 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27025 	    SD_PATH_STANDARD);
27026 	kmem_free(com, sizeof (*com));
27027 	return (rval);
27028 }
27029 
27030 
27031 /*
27032  *    Function: sr_read_mode2()
27033  *
27034  * Description: This routine is the driver entry point for handling CD-ROM
27035  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
27036  *		do not support the READ CD (0xBE) command.
27037  *
27038  *   Arguments: dev	- the device 'dev_t'
27039  *		data	- pointer to user provided cd read structure specifying
27040  *			  the lba buffer address and length.
27041  *		flag	- this argument is a pass through to ddi_copyxxx()
27042  *			  directly from the mode argument of ioctl().
27043  *
27044  * Return Code: the code returned by sd_send_scsi_cmd()
27045  *		EFAULT if ddi_copyxxx() fails
27046  *		ENXIO if fail ddi_get_soft_state
27047  *		EINVAL if data pointer is NULL
27048  *		EIO if fail to reset block size
27049  *		EAGAIN if commands are in progress in the driver
27050  */
27051 
27052 static int
27053 sr_read_mode2(dev_t dev, caddr_t data, int flag)
27054 {
27055 	struct sd_lun		*un;
27056 	struct cdrom_read	mode2_struct;
27057 	struct cdrom_read	*mode2 = &mode2_struct;
27058 	int			rval;
27059 	uint32_t		restore_blksize;
27060 	struct uscsi_cmd	*com;
27061 	uchar_t			cdb[CDB_GROUP0];
27062 	int			nblocks;
27063 
27064 #ifdef _MULTI_DATAMODEL
27065 	/* To support ILP32 applications in an LP64 world */
27066 	struct cdrom_read32	cdrom_read32;
27067 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
27068 #endif /* _MULTI_DATAMODEL */
27069 
27070 	if (data == NULL) {
27071 		return (EINVAL);
27072 	}
27073 
27074 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27075 	    (un->un_state == SD_STATE_OFFLINE)) {
27076 		return (ENXIO);
27077 	}
27078 
27079 	/*
27080 	 * Because this routine will update the device and driver block size
27081 	 * being used we want to make sure there are no commands in progress.
27082 	 * If commands are in progress the user will have to try again.
27083 	 *
27084 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
27085 	 * in sdioctl to protect commands from sdioctl through to the top of
27086 	 * sd_uscsi_strategy. See sdioctl for details.
27087 	 */
27088 	mutex_enter(SD_MUTEX(un));
27089 	if (un->un_ncmds_in_driver != 1) {
27090 		mutex_exit(SD_MUTEX(un));
27091 		return (EAGAIN);
27092 	}
27093 	mutex_exit(SD_MUTEX(un));
27094 
27095 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27096 	    "sd_read_mode2: entry: un:0x%p\n", un);
27097 
27098 #ifdef _MULTI_DATAMODEL
27099 	switch (ddi_model_convert_from(flag & FMODELS)) {
27100 	case DDI_MODEL_ILP32:
27101 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
27102 			return (EFAULT);
27103 		}
27104 		/* Convert the ILP32 uscsi data from the application to LP64 */
27105 		cdrom_read32tocdrom_read(cdrd32, mode2);
27106 		break;
27107 	case DDI_MODEL_NONE:
27108 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
27109 			return (EFAULT);
27110 		}
27111 		break;
27112 	}
27113 #else /* ! _MULTI_DATAMODEL */
27114 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
27115 		return (EFAULT);
27116 	}
27117 #endif /* _MULTI_DATAMODEL */
27118 
27119 	/* Store the current target block size for restoration later */
27120 	restore_blksize = un->un_tgt_blocksize;
27121 
27122 	/* Change the device and soft state target block size to 2336 */
27123 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
27124 		rval = EIO;
27125 		goto done;
27126 	}
27127 
27128 
27129 	bzero(cdb, sizeof (cdb));
27130 
27131 	/* set READ operation */
27132 	cdb[0] = SCMD_READ;
27133 
27134 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
27135 	mode2->cdread_lba >>= 2;
27136 
27137 	/* set the start address */
27138 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
27139 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
27140 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
27141 
27142 	/* set the transfer length */
27143 	nblocks = mode2->cdread_buflen / 2336;
27144 	cdb[4] = (uchar_t)nblocks & 0xFF;
27145 
27146 	/* build command */
27147 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27148 	com->uscsi_cdb = (caddr_t)cdb;
27149 	com->uscsi_cdblen = sizeof (cdb);
27150 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
27151 	com->uscsi_buflen = mode2->cdread_buflen;
27152 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27153 
27154 	/*
27155 	 * Issue SCSI command with user space address for read buffer.
27156 	 *
27157 	 * This sends the command through main channel in the driver.
27158 	 *
27159 	 * Since this is accessed via an IOCTL call, we go through the
27160 	 * standard path, so that if the device was powered down, then
27161 	 * it would be 'awakened' to handle the command.
27162 	 */
27163 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27164 	    SD_PATH_STANDARD);
27165 
27166 	kmem_free(com, sizeof (*com));
27167 
27168 	/* Restore the device and soft state target block size */
27169 	if (sr_sector_mode(dev, restore_blksize) != 0) {
27170 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27171 		    "can't do switch back to mode 1\n");
27172 		/*
27173 		 * If sd_send_scsi_READ succeeded we still need to report
27174 		 * an error because we failed to reset the block size
27175 		 */
27176 		if (rval == 0) {
27177 			rval = EIO;
27178 		}
27179 	}
27180 
27181 done:
27182 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
27183 	    "sd_read_mode2: exit: un:0x%p\n", un);
27184 
27185 	return (rval);
27186 }
27187 
27188 
27189 /*
27190  *    Function: sr_sector_mode()
27191  *
27192  * Description: This utility function is used by sr_read_mode2 to set the target
27193  *		block size based on the user specified size. This is a legacy
27194  *		implementation based upon a vendor specific mode page
27195  *
27196  *   Arguments: dev	- the device 'dev_t'
27197  *		data	- flag indicating if block size is being set to 2336 or
27198  *			  512.
27199  *
27200  * Return Code: the code returned by sd_send_scsi_cmd()
27201  *		EFAULT if ddi_copyxxx() fails
27202  *		ENXIO if fail ddi_get_soft_state
27203  *		EINVAL if data pointer is NULL
27204  */
27205 
27206 static int
27207 sr_sector_mode(dev_t dev, uint32_t blksize)
27208 {
27209 	struct sd_lun	*un;
27210 	uchar_t		*sense;
27211 	uchar_t		*select;
27212 	int		rval;
27213 	sd_ssc_t	*ssc;
27214 
27215 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27216 	    (un->un_state == SD_STATE_OFFLINE)) {
27217 		return (ENXIO);
27218 	}
27219 
27220 	sense = kmem_zalloc(20, KM_SLEEP);
27221 
27222 	/* Note: This is a vendor specific mode page (0x81) */
27223 	ssc = sd_ssc_init(un);
27224 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
27225 	    SD_PATH_STANDARD);
27226 	sd_ssc_fini(ssc);
27227 	if (rval != 0) {
27228 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
27229 		    "sr_sector_mode: Mode Sense failed\n");
27230 		kmem_free(sense, 20);
27231 		return (rval);
27232 	}
27233 	select = kmem_zalloc(20, KM_SLEEP);
27234 	select[3] = 0x08;
27235 	select[10] = ((blksize >> 8) & 0xff);
27236 	select[11] = (blksize & 0xff);
27237 	select[12] = 0x01;
27238 	select[13] = 0x06;
27239 	select[14] = sense[14];
27240 	select[15] = sense[15];
27241 	if (blksize == SD_MODE2_BLKSIZE) {
27242 		select[14] |= 0x01;
27243 	}
27244 
27245 	ssc = sd_ssc_init(un);
27246 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
27247 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27248 	sd_ssc_fini(ssc);
27249 	if (rval != 0) {
27250 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
27251 		    "sr_sector_mode: Mode Select failed\n");
27252 	} else {
27253 		/*
27254 		 * Only update the softstate block size if we successfully
27255 		 * changed the device block mode.
27256 		 */
27257 		mutex_enter(SD_MUTEX(un));
27258 		sd_update_block_info(un, blksize, 0);
27259 		mutex_exit(SD_MUTEX(un));
27260 	}
27261 	kmem_free(sense, 20);
27262 	kmem_free(select, 20);
27263 	return (rval);
27264 }
27265 
27266 
27267 /*
27268  *    Function: sr_read_cdda()
27269  *
27270  * Description: This routine is the driver entry point for handling CD-ROM
27271  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
27272  *		the target supports CDDA these requests are handled via a vendor
27273  *		specific command (0xD8) If the target does not support CDDA
27274  *		these requests are handled via the READ CD command (0xBE).
27275  *
27276  *   Arguments: dev	- the device 'dev_t'
27277  *		data	- pointer to user provided CD-DA structure specifying
27278  *			  the track starting address, transfer length, and
27279  *			  subcode options.
27280  *		flag	- this argument is a pass through to ddi_copyxxx()
27281  *			  directly from the mode argument of ioctl().
27282  *
27283  * Return Code: the code returned by sd_send_scsi_cmd()
27284  *		EFAULT if ddi_copyxxx() fails
27285  *		ENXIO if fail ddi_get_soft_state
27286  *		EINVAL if invalid arguments are provided
27287  *		ENOTTY
27288  */
27289 
27290 static int
27291 sr_read_cdda(dev_t dev, caddr_t data, int flag)
27292 {
27293 	struct sd_lun			*un;
27294 	struct uscsi_cmd		*com;
27295 	struct cdrom_cdda		*cdda;
27296 	int				rval;
27297 	size_t				buflen;
27298 	char				cdb[CDB_GROUP5];
27299 
27300 #ifdef _MULTI_DATAMODEL
27301 	/* To support ILP32 applications in an LP64 world */
27302 	struct cdrom_cdda32	cdrom_cdda32;
27303 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
27304 #endif /* _MULTI_DATAMODEL */
27305 
27306 	if (data == NULL) {
27307 		return (EINVAL);
27308 	}
27309 
27310 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27311 		return (ENXIO);
27312 	}
27313 
27314 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
27315 
27316 #ifdef _MULTI_DATAMODEL
27317 	switch (ddi_model_convert_from(flag & FMODELS)) {
27318 	case DDI_MODEL_ILP32:
27319 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
27320 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27321 			    "sr_read_cdda: ddi_copyin Failed\n");
27322 			kmem_free(cdda, sizeof (struct cdrom_cdda));
27323 			return (EFAULT);
27324 		}
27325 		/* Convert the ILP32 uscsi data from the application to LP64 */
27326 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
27327 		break;
27328 	case DDI_MODEL_NONE:
27329 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
27330 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27331 			    "sr_read_cdda: ddi_copyin Failed\n");
27332 			kmem_free(cdda, sizeof (struct cdrom_cdda));
27333 			return (EFAULT);
27334 		}
27335 		break;
27336 	}
27337 #else /* ! _MULTI_DATAMODEL */
27338 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
27339 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27340 		    "sr_read_cdda: ddi_copyin Failed\n");
27341 		kmem_free(cdda, sizeof (struct cdrom_cdda));
27342 		return (EFAULT);
27343 	}
27344 #endif /* _MULTI_DATAMODEL */
27345 
27346 	/*
27347 	 * Since MMC-2 expects max 3 bytes for length, check if the
27348 	 * length input is greater than 3 bytes
27349 	 */
27350 	if ((cdda->cdda_length & 0xFF000000) != 0) {
27351 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
27352 		    "cdrom transfer length too large: %d (limit %d)\n",
27353 		    cdda->cdda_length, 0xFFFFFF);
27354 		kmem_free(cdda, sizeof (struct cdrom_cdda));
27355 		return (EINVAL);
27356 	}
27357 
27358 	switch (cdda->cdda_subcode) {
27359 	case CDROM_DA_NO_SUBCODE:
27360 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
27361 		break;
27362 	case CDROM_DA_SUBQ:
27363 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
27364 		break;
27365 	case CDROM_DA_ALL_SUBCODE:
27366 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
27367 		break;
27368 	case CDROM_DA_SUBCODE_ONLY:
27369 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
27370 		break;
27371 	default:
27372 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27373 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
27374 		    cdda->cdda_subcode);
27375 		kmem_free(cdda, sizeof (struct cdrom_cdda));
27376 		return (EINVAL);
27377 	}
27378 
27379 	/* Build and send the command */
27380 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27381 	bzero(cdb, CDB_GROUP5);
27382 
27383 	if (un->un_f_cfg_cdda == TRUE) {
27384 		cdb[0] = (char)SCMD_READ_CD;
27385 		cdb[1] = 0x04;
27386 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
27387 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
27388 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
27389 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
27390 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
27391 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
27392 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
27393 		cdb[9] = 0x10;
27394 		switch (cdda->cdda_subcode) {
27395 		case CDROM_DA_NO_SUBCODE :
27396 			cdb[10] = 0x0;
27397 			break;
27398 		case CDROM_DA_SUBQ :
27399 			cdb[10] = 0x2;
27400 			break;
27401 		case CDROM_DA_ALL_SUBCODE :
27402 			cdb[10] = 0x1;
27403 			break;
27404 		case CDROM_DA_SUBCODE_ONLY :
27405 			/* FALLTHROUGH */
27406 		default :
27407 			kmem_free(cdda, sizeof (struct cdrom_cdda));
27408 			kmem_free(com, sizeof (*com));
27409 			return (ENOTTY);
27410 		}
27411 	} else {
27412 		cdb[0] = (char)SCMD_READ_CDDA;
27413 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
27414 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
27415 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
27416 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
27417 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
27418 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
27419 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
27420 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
27421 		cdb[10] = cdda->cdda_subcode;
27422 	}
27423 
27424 	com->uscsi_cdb = cdb;
27425 	com->uscsi_cdblen = CDB_GROUP5;
27426 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
27427 	com->uscsi_buflen = buflen;
27428 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27429 
27430 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27431 	    SD_PATH_STANDARD);
27432 
27433 	kmem_free(cdda, sizeof (struct cdrom_cdda));
27434 	kmem_free(com, sizeof (*com));
27435 	return (rval);
27436 }
27437 
27438 
27439 /*
27440  *    Function: sr_read_cdxa()
27441  *
27442  * Description: This routine is the driver entry point for handling CD-ROM
27443  *		ioctl requests to return CD-XA (Extended Architecture) data.
27444  *		(CDROMCDXA).
27445  *
27446  *   Arguments: dev	- the device 'dev_t'
27447  *		data	- pointer to user provided CD-XA structure specifying
27448  *			  the data starting address, transfer length, and format
27449  *		flag	- this argument is a pass through to ddi_copyxxx()
27450  *			  directly from the mode argument of ioctl().
27451  *
27452  * Return Code: the code returned by sd_send_scsi_cmd()
27453  *		EFAULT if ddi_copyxxx() fails
27454  *		ENXIO if fail ddi_get_soft_state
27455  *		EINVAL if data pointer is NULL
27456  */
27457 
27458 static int
27459 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
27460 {
27461 	struct sd_lun		*un;
27462 	struct uscsi_cmd	*com;
27463 	struct cdrom_cdxa	*cdxa;
27464 	int			rval;
27465 	size_t			buflen;
27466 	char			cdb[CDB_GROUP5];
27467 	uchar_t			read_flags;
27468 
27469 #ifdef _MULTI_DATAMODEL
27470 	/* To support ILP32 applications in an LP64 world */
27471 	struct cdrom_cdxa32		cdrom_cdxa32;
27472 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
27473 #endif /* _MULTI_DATAMODEL */
27474 
27475 	if (data == NULL) {
27476 		return (EINVAL);
27477 	}
27478 
27479 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27480 		return (ENXIO);
27481 	}
27482 
27483 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
27484 
27485 #ifdef _MULTI_DATAMODEL
27486 	switch (ddi_model_convert_from(flag & FMODELS)) {
27487 	case DDI_MODEL_ILP32:
27488 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
27489 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27490 			return (EFAULT);
27491 		}
27492 		/*
27493 		 * Convert the ILP32 uscsi data from the
27494 		 * application to LP64 for internal use.
27495 		 */
27496 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
27497 		break;
27498 	case DDI_MODEL_NONE:
27499 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
27500 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27501 			return (EFAULT);
27502 		}
27503 		break;
27504 	}
27505 #else /* ! _MULTI_DATAMODEL */
27506 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
27507 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27508 		return (EFAULT);
27509 	}
27510 #endif /* _MULTI_DATAMODEL */
27511 
27512 	/*
27513 	 * Since MMC-2 expects max 3 bytes for length, check if the
27514 	 * length input is greater than 3 bytes
27515 	 */
27516 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
27517 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
27518 		    "cdrom transfer length too large: %d (limit %d)\n",
27519 		    cdxa->cdxa_length, 0xFFFFFF);
27520 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27521 		return (EINVAL);
27522 	}
27523 
27524 	switch (cdxa->cdxa_format) {
27525 	case CDROM_XA_DATA:
27526 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
27527 		read_flags = 0x10;
27528 		break;
27529 	case CDROM_XA_SECTOR_DATA:
27530 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
27531 		read_flags = 0xf8;
27532 		break;
27533 	case CDROM_XA_DATA_W_ERROR:
27534 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
27535 		read_flags = 0xfc;
27536 		break;
27537 	default:
27538 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27539 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
27540 		    cdxa->cdxa_format);
27541 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27542 		return (EINVAL);
27543 	}
27544 
27545 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27546 	bzero(cdb, CDB_GROUP5);
27547 	if (un->un_f_mmc_cap == TRUE) {
27548 		cdb[0] = (char)SCMD_READ_CD;
27549 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
27550 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
27551 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
27552 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
27553 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
27554 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
27555 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
27556 		cdb[9] = (char)read_flags;
27557 	} else {
27558 		/*
27559 		 * Note: A vendor specific command (0xDB) is being used her to
27560 		 * request a read of all subcodes.
27561 		 */
27562 		cdb[0] = (char)SCMD_READ_CDXA;
27563 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
27564 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
27565 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
27566 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
27567 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
27568 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
27569 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
27570 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
27571 		cdb[10] = cdxa->cdxa_format;
27572 	}
27573 	com->uscsi_cdb	   = cdb;
27574 	com->uscsi_cdblen  = CDB_GROUP5;
27575 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
27576 	com->uscsi_buflen  = buflen;
27577 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27578 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27579 	    SD_PATH_STANDARD);
27580 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
27581 	kmem_free(com, sizeof (*com));
27582 	return (rval);
27583 }
27584 
27585 
27586 /*
27587  *    Function: sr_eject()
27588  *
27589  * Description: This routine is the driver entry point for handling CD-ROM
27590  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
27591  *
27592  *   Arguments: dev	- the device 'dev_t'
27593  *
27594  * Return Code: the code returned by sd_send_scsi_cmd()
27595  */
27596 
27597 static int
27598 sr_eject(dev_t dev)
27599 {
27600 	struct sd_lun	*un;
27601 	int		rval;
27602 	sd_ssc_t	*ssc;
27603 
27604 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27605 	    (un->un_state == SD_STATE_OFFLINE)) {
27606 		return (ENXIO);
27607 	}
27608 
27609 	/*
27610 	 * To prevent race conditions with the eject
27611 	 * command, keep track of an eject command as
27612 	 * it progresses. If we are already handling
27613 	 * an eject command in the driver for the given
27614 	 * unit and another request to eject is received
27615 	 * immediately return EAGAIN so we don't lose
27616 	 * the command if the current eject command fails.
27617 	 */
27618 	mutex_enter(SD_MUTEX(un));
27619 	if (un->un_f_ejecting == TRUE) {
27620 		mutex_exit(SD_MUTEX(un));
27621 		return (EAGAIN);
27622 	}
27623 	un->un_f_ejecting = TRUE;
27624 	mutex_exit(SD_MUTEX(un));
27625 
27626 	ssc = sd_ssc_init(un);
27627 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
27628 	    SD_PATH_STANDARD);
27629 	sd_ssc_fini(ssc);
27630 
27631 	if (rval != 0) {
27632 		mutex_enter(SD_MUTEX(un));
27633 		un->un_f_ejecting = FALSE;
27634 		mutex_exit(SD_MUTEX(un));
27635 		return (rval);
27636 	}
27637 
27638 	ssc = sd_ssc_init(un);
27639 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_TARGET_EJECT,
27640 	    SD_PATH_STANDARD);
27641 	sd_ssc_fini(ssc);
27642 
27643 	if (rval == 0) {
27644 		mutex_enter(SD_MUTEX(un));
27645 		sr_ejected(un);
27646 		un->un_mediastate = DKIO_EJECTED;
27647 		un->un_f_ejecting = FALSE;
27648 		cv_broadcast(&un->un_state_cv);
27649 		mutex_exit(SD_MUTEX(un));
27650 	} else {
27651 		mutex_enter(SD_MUTEX(un));
27652 		un->un_f_ejecting = FALSE;
27653 		mutex_exit(SD_MUTEX(un));
27654 	}
27655 	return (rval);
27656 }
27657 
27658 
27659 /*
27660  *    Function: sr_ejected()
27661  *
27662  * Description: This routine updates the soft state structure to invalidate the
27663  *		geometry information after the media has been ejected or a
27664  *		media eject has been detected.
27665  *
27666  *   Arguments: un - driver soft state (unit) structure
27667  */
27668 
27669 static void
27670 sr_ejected(struct sd_lun *un)
27671 {
27672 	struct sd_errstats *stp;
27673 
27674 	ASSERT(un != NULL);
27675 	ASSERT(mutex_owned(SD_MUTEX(un)));
27676 
27677 	un->un_f_blockcount_is_valid	= FALSE;
27678 	un->un_f_tgt_blocksize_is_valid	= FALSE;
27679 	mutex_exit(SD_MUTEX(un));
27680 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
27681 	mutex_enter(SD_MUTEX(un));
27682 
27683 	if (un->un_errstats != NULL) {
27684 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
27685 		stp->sd_capacity.value.ui64 = 0;
27686 	}
27687 }
27688 
27689 
27690 /*
27691  *    Function: sr_check_wp()
27692  *
27693  * Description: This routine checks the write protection of a removable
27694  *      media disk and hotpluggable devices via the write protect bit of
27695  *      the Mode Page Header device specific field. Some devices choke
27696  *      on unsupported mode page. In order to workaround this issue,
27697  *      this routine has been implemented to use 0x3f mode page(request
27698  *      for all pages) for all device types.
27699  *
27700  *   Arguments: dev             - the device 'dev_t'
27701  *
27702  * Return Code: int indicating if the device is write protected (1) or not (0)
27703  *
27704  *     Context: Kernel thread.
27705  *
27706  */
27707 
27708 static int
27709 sr_check_wp(dev_t dev)
27710 {
27711 	struct sd_lun	*un;
27712 	uchar_t		device_specific;
27713 	uchar_t		*sense;
27714 	int		hdrlen;
27715 	int		rval = FALSE;
27716 	int		status;
27717 	sd_ssc_t	*ssc;
27718 
27719 	/*
27720 	 * Note: The return codes for this routine should be reworked to
27721 	 * properly handle the case of a NULL softstate.
27722 	 */
27723 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27724 		return (FALSE);
27725 	}
27726 
27727 	if (un->un_f_cfg_is_atapi == TRUE) {
27728 		/*
27729 		 * The mode page contents are not required; set the allocation
27730 		 * length for the mode page header only
27731 		 */
27732 		hdrlen = MODE_HEADER_LENGTH_GRP2;
27733 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
27734 		ssc = sd_ssc_init(un);
27735 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
27736 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
27737 		sd_ssc_fini(ssc);
27738 		if (status != 0)
27739 			goto err_exit;
27740 		device_specific =
27741 		    ((struct mode_header_grp2 *)sense)->device_specific;
27742 	} else {
27743 		hdrlen = MODE_HEADER_LENGTH;
27744 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
27745 		ssc = sd_ssc_init(un);
27746 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
27747 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
27748 		sd_ssc_fini(ssc);
27749 		if (status != 0)
27750 			goto err_exit;
27751 		device_specific =
27752 		    ((struct mode_header *)sense)->device_specific;
27753 	}
27754 
27755 
27756 	/*
27757 	 * Write protect mode sense failed; not all disks
27758 	 * understand this query. Return FALSE assuming that
27759 	 * these devices are not writable.
27760 	 */
27761 	if (device_specific & WRITE_PROTECT) {
27762 		rval = TRUE;
27763 	}
27764 
27765 err_exit:
27766 	kmem_free(sense, hdrlen);
27767 	return (rval);
27768 }
27769 
27770 /*
27771  *    Function: sr_volume_ctrl()
27772  *
27773  * Description: This routine is the driver entry point for handling CD-ROM
27774  *		audio output volume ioctl requests. (CDROMVOLCTRL)
27775  *
27776  *   Arguments: dev	- the device 'dev_t'
27777  *		data	- pointer to user audio volume control structure
27778  *		flag	- this argument is a pass through to ddi_copyxxx()
27779  *			  directly from the mode argument of ioctl().
27780  *
27781  * Return Code: the code returned by sd_send_scsi_cmd()
27782  *		EFAULT if ddi_copyxxx() fails
27783  *		ENXIO if fail ddi_get_soft_state
27784  *		EINVAL if data pointer is NULL
27785  *
27786  */
27787 
27788 static int
27789 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
27790 {
27791 	struct sd_lun		*un;
27792 	struct cdrom_volctrl    volume;
27793 	struct cdrom_volctrl    *vol = &volume;
27794 	uchar_t			*sense_page;
27795 	uchar_t			*select_page;
27796 	uchar_t			*sense;
27797 	uchar_t			*select;
27798 	int			sense_buflen;
27799 	int			select_buflen;
27800 	int			rval;
27801 	sd_ssc_t		*ssc;
27802 
27803 	if (data == NULL) {
27804 		return (EINVAL);
27805 	}
27806 
27807 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27808 	    (un->un_state == SD_STATE_OFFLINE)) {
27809 		return (ENXIO);
27810 	}
27811 
27812 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
27813 		return (EFAULT);
27814 	}
27815 
27816 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
27817 		struct mode_header_grp2		*sense_mhp;
27818 		struct mode_header_grp2		*select_mhp;
27819 		int				bd_len;
27820 
27821 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
27822 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
27823 		    MODEPAGE_AUDIO_CTRL_LEN;
27824 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
27825 		select = kmem_zalloc(select_buflen, KM_SLEEP);
27826 		ssc = sd_ssc_init(un);
27827 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
27828 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
27829 		    SD_PATH_STANDARD);
27830 		sd_ssc_fini(ssc);
27831 
27832 		if (rval != 0) {
27833 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
27834 			    "sr_volume_ctrl: Mode Sense Failed\n");
27835 			kmem_free(sense, sense_buflen);
27836 			kmem_free(select, select_buflen);
27837 			return (rval);
27838 		}
27839 		sense_mhp = (struct mode_header_grp2 *)sense;
27840 		select_mhp = (struct mode_header_grp2 *)select;
27841 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
27842 		    sense_mhp->bdesc_length_lo;
27843 		if (bd_len > MODE_BLK_DESC_LENGTH) {
27844 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27845 			    "sr_volume_ctrl: Mode Sense returned invalid "
27846 			    "block descriptor length\n");
27847 			kmem_free(sense, sense_buflen);
27848 			kmem_free(select, select_buflen);
27849 			return (EIO);
27850 		}
27851 		sense_page = (uchar_t *)
27852 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27853 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
27854 		select_mhp->length_msb = 0;
27855 		select_mhp->length_lsb = 0;
27856 		select_mhp->bdesc_length_hi = 0;
27857 		select_mhp->bdesc_length_lo = 0;
27858 	} else {
27859 		struct mode_header		*sense_mhp, *select_mhp;
27860 
27861 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
27862 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
27863 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
27864 		select = kmem_zalloc(select_buflen, KM_SLEEP);
27865 		ssc = sd_ssc_init(un);
27866 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27867 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
27868 		    SD_PATH_STANDARD);
27869 		sd_ssc_fini(ssc);
27870 
27871 		if (rval != 0) {
27872 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27873 			    "sr_volume_ctrl: Mode Sense Failed\n");
27874 			kmem_free(sense, sense_buflen);
27875 			kmem_free(select, select_buflen);
27876 			return (rval);
27877 		}
27878 		sense_mhp  = (struct mode_header *)sense;
27879 		select_mhp = (struct mode_header *)select;
27880 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
27881 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27882 			    "sr_volume_ctrl: Mode Sense returned invalid "
27883 			    "block descriptor length\n");
27884 			kmem_free(sense, sense_buflen);
27885 			kmem_free(select, select_buflen);
27886 			return (EIO);
27887 		}
27888 		sense_page = (uchar_t *)
27889 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27890 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
27891 		select_mhp->length = 0;
27892 		select_mhp->bdesc_length = 0;
27893 	}
27894 	/*
27895 	 * Note: An audio control data structure could be created and overlayed
27896 	 * on the following in place of the array indexing method implemented.
27897 	 */
27898 
27899 	/* Build the select data for the user volume data */
27900 	select_page[0] = MODEPAGE_AUDIO_CTRL;
27901 	select_page[1] = 0xE;
27902 	/* Set the immediate bit */
27903 	select_page[2] = 0x04;
27904 	/* Zero out reserved fields */
27905 	select_page[3] = 0x00;
27906 	select_page[4] = 0x00;
27907 	/* Return sense data for fields not to be modified */
27908 	select_page[5] = sense_page[5];
27909 	select_page[6] = sense_page[6];
27910 	select_page[7] = sense_page[7];
27911 	/* Set the user specified volume levels for channel 0 and 1 */
27912 	select_page[8] = 0x01;
27913 	select_page[9] = vol->channel0;
27914 	select_page[10] = 0x02;
27915 	select_page[11] = vol->channel1;
27916 	/* Channel 2 and 3 are currently unsupported so return the sense data */
27917 	select_page[12] = sense_page[12];
27918 	select_page[13] = sense_page[13];
27919 	select_page[14] = sense_page[14];
27920 	select_page[15] = sense_page[15];
27921 
27922 	ssc = sd_ssc_init(un);
27923 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
27924 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
27925 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27926 	} else {
27927 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27928 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27929 	}
27930 	sd_ssc_fini(ssc);
27931 
27932 	kmem_free(sense, sense_buflen);
27933 	kmem_free(select, select_buflen);
27934 	return (rval);
27935 }
27936 
27937 
27938 /*
27939  *    Function: sr_read_sony_session_offset()
27940  *
27941  * Description: This routine is the driver entry point for handling CD-ROM
27942  *		ioctl requests for session offset information. (CDROMREADOFFSET)
27943  *		The address of the first track in the last session of a
27944  *		multi-session CD-ROM is returned
27945  *
27946  *		Note: This routine uses a vendor specific key value in the
27947  *		command control field without implementing any vendor check here
27948  *		or in the ioctl routine.
27949  *
27950  *   Arguments: dev	- the device 'dev_t'
27951  *		data	- pointer to an int to hold the requested address
27952  *		flag	- this argument is a pass through to ddi_copyxxx()
27953  *			  directly from the mode argument of ioctl().
27954  *
27955  * Return Code: the code returned by sd_send_scsi_cmd()
27956  *		EFAULT if ddi_copyxxx() fails
27957  *		ENXIO if fail ddi_get_soft_state
27958  *		EINVAL if data pointer is NULL
27959  */
27960 
27961 static int
27962 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
27963 {
27964 	struct sd_lun		*un;
27965 	struct uscsi_cmd	*com;
27966 	caddr_t			buffer;
27967 	char			cdb[CDB_GROUP1];
27968 	int			session_offset = 0;
27969 	int			rval;
27970 
27971 	if (data == NULL) {
27972 		return (EINVAL);
27973 	}
27974 
27975 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27976 	    (un->un_state == SD_STATE_OFFLINE)) {
27977 		return (ENXIO);
27978 	}
27979 
27980 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
27981 	bzero(cdb, CDB_GROUP1);
27982 	cdb[0] = SCMD_READ_TOC;
27983 	/*
27984 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
27985 	 * (4 byte TOC response header + 8 byte response data)
27986 	 */
27987 	cdb[8] = SONY_SESSION_OFFSET_LEN;
27988 	/* Byte 9 is the control byte. A vendor specific value is used */
27989 	cdb[9] = SONY_SESSION_OFFSET_KEY;
27990 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27991 	com->uscsi_cdb = cdb;
27992 	com->uscsi_cdblen = CDB_GROUP1;
27993 	com->uscsi_bufaddr = buffer;
27994 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
27995 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27996 
27997 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27998 	    SD_PATH_STANDARD);
27999 	if (rval != 0) {
28000 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
28001 		kmem_free(com, sizeof (*com));
28002 		return (rval);
28003 	}
28004 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
28005 		session_offset =
28006 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
28007 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
28008 		/*
28009 		 * Offset returned offset in current lbasize block's. Convert to
28010 		 * 2k block's to return to the user
28011 		 */
28012 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
28013 			session_offset >>= 2;
28014 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
28015 			session_offset >>= 1;
28016 		}
28017 	}
28018 
28019 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
28020 		rval = EFAULT;
28021 	}
28022 
28023 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
28024 	kmem_free(com, sizeof (*com));
28025 	return (rval);
28026 }
28027 
28028 
28029 /*
28030  *    Function: sd_wm_cache_constructor()
28031  *
28032  * Description: Cache Constructor for the wmap cache for the read/modify/write
28033  * 		devices.
28034  *
28035  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
28036  *		un	- sd_lun structure for the device.
28037  *		flag	- the km flags passed to constructor
28038  *
28039  * Return Code: 0 on success.
28040  *		-1 on failure.
28041  */
28042 
28043 /*ARGSUSED*/
28044 static int
28045 sd_wm_cache_constructor(void *wm, void *un, int flags)
28046 {
28047 	bzero(wm, sizeof (struct sd_w_map));
28048 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
28049 	return (0);
28050 }
28051 
28052 
28053 /*
28054  *    Function: sd_wm_cache_destructor()
28055  *
28056  * Description: Cache destructor for the wmap cache for the read/modify/write
28057  * 		devices.
28058  *
28059  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
28060  *		un	- sd_lun structure for the device.
28061  */
28062 /*ARGSUSED*/
28063 static void
28064 sd_wm_cache_destructor(void *wm, void *un)
28065 {
28066 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
28067 }
28068 
28069 
28070 /*
28071  *    Function: sd_range_lock()
28072  *
28073  * Description: Lock the range of blocks specified as parameter to ensure
28074  *		that read, modify write is atomic and no other i/o writes
28075  *		to the same location. The range is specified in terms
28076  *		of start and end blocks. Block numbers are the actual
28077  *		media block numbers and not system.
28078  *
28079  *   Arguments: un	- sd_lun structure for the device.
28080  *		startb - The starting block number
28081  *		endb - The end block number
28082  *		typ - type of i/o - simple/read_modify_write
28083  *
28084  * Return Code: wm  - pointer to the wmap structure.
28085  *
28086  *     Context: This routine can sleep.
28087  */
28088 
28089 static struct sd_w_map *
28090 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
28091 {
28092 	struct sd_w_map *wmp = NULL;
28093 	struct sd_w_map *sl_wmp = NULL;
28094 	struct sd_w_map *tmp_wmp;
28095 	wm_state state = SD_WM_CHK_LIST;
28096 
28097 
28098 	ASSERT(un != NULL);
28099 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28100 
28101 	mutex_enter(SD_MUTEX(un));
28102 
28103 	while (state != SD_WM_DONE) {
28104 
28105 		switch (state) {
28106 		case SD_WM_CHK_LIST:
28107 			/*
28108 			 * This is the starting state. Check the wmap list
28109 			 * to see if the range is currently available.
28110 			 */
28111 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
28112 				/*
28113 				 * If this is a simple write and no rmw
28114 				 * i/o is pending then try to lock the
28115 				 * range as the range should be available.
28116 				 */
28117 				state = SD_WM_LOCK_RANGE;
28118 			} else {
28119 				tmp_wmp = sd_get_range(un, startb, endb);
28120 				if (tmp_wmp != NULL) {
28121 					if ((wmp != NULL) && ONLIST(un, wmp)) {
28122 						/*
28123 						 * Should not keep onlist wmps
28124 						 * while waiting this macro
28125 						 * will also do wmp = NULL;
28126 						 */
28127 						FREE_ONLIST_WMAP(un, wmp);
28128 					}
28129 					/*
28130 					 * sl_wmp is the wmap on which wait
28131 					 * is done, since the tmp_wmp points
28132 					 * to the inuse wmap, set sl_wmp to
28133 					 * tmp_wmp and change the state to sleep
28134 					 */
28135 					sl_wmp = tmp_wmp;
28136 					state = SD_WM_WAIT_MAP;
28137 				} else {
28138 					state = SD_WM_LOCK_RANGE;
28139 				}
28140 
28141 			}
28142 			break;
28143 
28144 		case SD_WM_LOCK_RANGE:
28145 			ASSERT(un->un_wm_cache);
28146 			/*
28147 			 * The range need to be locked, try to get a wmap.
28148 			 * First attempt it with NO_SLEEP, want to avoid a sleep
28149 			 * if possible as we will have to release the sd mutex
28150 			 * if we have to sleep.
28151 			 */
28152 			if (wmp == NULL)
28153 				wmp = kmem_cache_alloc(un->un_wm_cache,
28154 				    KM_NOSLEEP);
28155 			if (wmp == NULL) {
28156 				mutex_exit(SD_MUTEX(un));
28157 				_NOTE(DATA_READABLE_WITHOUT_LOCK
28158 				    (sd_lun::un_wm_cache))
28159 				wmp = kmem_cache_alloc(un->un_wm_cache,
28160 				    KM_SLEEP);
28161 				mutex_enter(SD_MUTEX(un));
28162 				/*
28163 				 * we released the mutex so recheck and go to
28164 				 * check list state.
28165 				 */
28166 				state = SD_WM_CHK_LIST;
28167 			} else {
28168 				/*
28169 				 * We exit out of state machine since we
28170 				 * have the wmap. Do the housekeeping first.
28171 				 * place the wmap on the wmap list if it is not
28172 				 * on it already and then set the state to done.
28173 				 */
28174 				wmp->wm_start = startb;
28175 				wmp->wm_end = endb;
28176 				wmp->wm_flags = typ | SD_WM_BUSY;
28177 				if (typ & SD_WTYPE_RMW) {
28178 					un->un_rmw_count++;
28179 				}
28180 				/*
28181 				 * If not already on the list then link
28182 				 */
28183 				if (!ONLIST(un, wmp)) {
28184 					wmp->wm_next = un->un_wm;
28185 					wmp->wm_prev = NULL;
28186 					if (wmp->wm_next)
28187 						wmp->wm_next->wm_prev = wmp;
28188 					un->un_wm = wmp;
28189 				}
28190 				state = SD_WM_DONE;
28191 			}
28192 			break;
28193 
28194 		case SD_WM_WAIT_MAP:
28195 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
28196 			/*
28197 			 * Wait is done on sl_wmp, which is set in the
28198 			 * check_list state.
28199 			 */
28200 			sl_wmp->wm_wanted_count++;
28201 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
28202 			sl_wmp->wm_wanted_count--;
28203 			/*
28204 			 * We can reuse the memory from the completed sl_wmp
28205 			 * lock range for our new lock, but only if noone is
28206 			 * waiting for it.
28207 			 */
28208 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
28209 			if (sl_wmp->wm_wanted_count == 0) {
28210 				if (wmp != NULL)
28211 					CHK_N_FREEWMP(un, wmp);
28212 				wmp = sl_wmp;
28213 			}
28214 			sl_wmp = NULL;
28215 			/*
28216 			 * After waking up, need to recheck for availability of
28217 			 * range.
28218 			 */
28219 			state = SD_WM_CHK_LIST;
28220 			break;
28221 
28222 		default:
28223 			panic("sd_range_lock: "
28224 			    "Unknown state %d in sd_range_lock", state);
28225 			/*NOTREACHED*/
28226 		} /* switch(state) */
28227 
28228 	} /* while(state != SD_WM_DONE) */
28229 
28230 	mutex_exit(SD_MUTEX(un));
28231 
28232 	ASSERT(wmp != NULL);
28233 
28234 	return (wmp);
28235 }
28236 
28237 
28238 /*
28239  *    Function: sd_get_range()
28240  *
28241  * Description: Find if there any overlapping I/O to this one
28242  *		Returns the write-map of 1st such I/O, NULL otherwise.
28243  *
28244  *   Arguments: un	- sd_lun structure for the device.
28245  *		startb - The starting block number
28246  *		endb - The end block number
28247  *
28248  * Return Code: wm  - pointer to the wmap structure.
28249  */
28250 
28251 static struct sd_w_map *
28252 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
28253 {
28254 	struct sd_w_map *wmp;
28255 
28256 	ASSERT(un != NULL);
28257 
28258 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
28259 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
28260 			continue;
28261 		}
28262 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
28263 			break;
28264 		}
28265 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
28266 			break;
28267 		}
28268 	}
28269 
28270 	return (wmp);
28271 }
28272 
28273 
28274 /*
28275  *    Function: sd_free_inlist_wmap()
28276  *
28277  * Description: Unlink and free a write map struct.
28278  *
28279  *   Arguments: un      - sd_lun structure for the device.
28280  *		wmp	- sd_w_map which needs to be unlinked.
28281  */
28282 
28283 static void
28284 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
28285 {
28286 	ASSERT(un != NULL);
28287 
28288 	if (un->un_wm == wmp) {
28289 		un->un_wm = wmp->wm_next;
28290 	} else {
28291 		wmp->wm_prev->wm_next = wmp->wm_next;
28292 	}
28293 
28294 	if (wmp->wm_next) {
28295 		wmp->wm_next->wm_prev = wmp->wm_prev;
28296 	}
28297 
28298 	wmp->wm_next = wmp->wm_prev = NULL;
28299 
28300 	kmem_cache_free(un->un_wm_cache, wmp);
28301 }
28302 
28303 
28304 /*
28305  *    Function: sd_range_unlock()
28306  *
28307  * Description: Unlock the range locked by wm.
28308  *		Free write map if nobody else is waiting on it.
28309  *
28310  *   Arguments: un      - sd_lun structure for the device.
28311  *              wmp     - sd_w_map which needs to be unlinked.
28312  */
28313 
28314 static void
28315 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
28316 {
28317 	ASSERT(un != NULL);
28318 	ASSERT(wm != NULL);
28319 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28320 
28321 	mutex_enter(SD_MUTEX(un));
28322 
28323 	if (wm->wm_flags & SD_WTYPE_RMW) {
28324 		un->un_rmw_count--;
28325 	}
28326 
28327 	if (wm->wm_wanted_count) {
28328 		wm->wm_flags = 0;
28329 		/*
28330 		 * Broadcast that the wmap is available now.
28331 		 */
28332 		cv_broadcast(&wm->wm_avail);
28333 	} else {
28334 		/*
28335 		 * If no one is waiting on the map, it should be free'ed.
28336 		 */
28337 		sd_free_inlist_wmap(un, wm);
28338 	}
28339 
28340 	mutex_exit(SD_MUTEX(un));
28341 }
28342 
28343 
28344 /*
28345  *    Function: sd_read_modify_write_task
28346  *
28347  * Description: Called from a taskq thread to initiate the write phase of
28348  *		a read-modify-write request.  This is used for targets where
28349  *		un->un_sys_blocksize != un->un_tgt_blocksize.
28350  *
28351  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
28352  *
28353  *     Context: Called under taskq thread context.
28354  */
28355 
28356 static void
28357 sd_read_modify_write_task(void *arg)
28358 {
28359 	struct sd_mapblocksize_info	*bsp;
28360 	struct buf	*bp;
28361 	struct sd_xbuf	*xp;
28362 	struct sd_lun	*un;
28363 
28364 	bp = arg;	/* The bp is given in arg */
28365 	ASSERT(bp != NULL);
28366 
28367 	/* Get the pointer to the layer-private data struct */
28368 	xp = SD_GET_XBUF(bp);
28369 	ASSERT(xp != NULL);
28370 	bsp = xp->xb_private;
28371 	ASSERT(bsp != NULL);
28372 
28373 	un = SD_GET_UN(bp);
28374 	ASSERT(un != NULL);
28375 	ASSERT(!mutex_owned(SD_MUTEX(un)));
28376 
28377 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
28378 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
28379 
28380 	/*
28381 	 * This is the write phase of a read-modify-write request, called
28382 	 * under the context of a taskq thread in response to the completion
28383 	 * of the read portion of the rmw request completing under interrupt
28384 	 * context. The write request must be sent from here down the iostart
28385 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
28386 	 * we use the layer index saved in the layer-private data area.
28387 	 */
28388 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
28389 
28390 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
28391 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
28392 }
28393 
28394 
28395 /*
28396  *    Function: sddump_do_read_of_rmw()
28397  *
28398  * Description: This routine will be called from sddump, If sddump is called
28399  *		with an I/O which not aligned on device blocksize boundary
28400  *		then the write has to be converted to read-modify-write.
28401  *		Do the read part here in order to keep sddump simple.
28402  *		Note - That the sd_mutex is held across the call to this
28403  *		routine.
28404  *
28405  *   Arguments: un	- sd_lun
28406  *		blkno	- block number in terms of media block size.
28407  *		nblk	- number of blocks.
28408  *		bpp	- pointer to pointer to the buf structure. On return
28409  *			from this function, *bpp points to the valid buffer
28410  *			to which the write has to be done.
28411  *
28412  * Return Code: 0 for success or errno-type return code
28413  */
28414 
28415 static int
28416 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
28417 	struct buf **bpp)
28418 {
28419 	int err;
28420 	int i;
28421 	int rval;
28422 	struct buf *bp;
28423 	struct scsi_pkt *pkt = NULL;
28424 	uint32_t target_blocksize;
28425 
28426 	ASSERT(un != NULL);
28427 	ASSERT(mutex_owned(SD_MUTEX(un)));
28428 
28429 	target_blocksize = un->un_tgt_blocksize;
28430 
28431 	mutex_exit(SD_MUTEX(un));
28432 
28433 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
28434 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
28435 	if (bp == NULL) {
28436 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28437 		    "no resources for dumping; giving up");
28438 		err = ENOMEM;
28439 		goto done;
28440 	}
28441 
28442 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
28443 	    blkno, nblk);
28444 	if (rval != 0) {
28445 		scsi_free_consistent_buf(bp);
28446 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28447 		    "no resources for dumping; giving up");
28448 		err = ENOMEM;
28449 		goto done;
28450 	}
28451 
28452 	pkt->pkt_flags |= FLAG_NOINTR;
28453 
28454 	err = EIO;
28455 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
28456 
28457 		/*
28458 		 * Scsi_poll returns 0 (success) if the command completes and
28459 		 * the status block is STATUS_GOOD.  We should only check
28460 		 * errors if this condition is not true.  Even then we should
28461 		 * send our own request sense packet only if we have a check
28462 		 * condition and auto request sense has not been performed by
28463 		 * the hba.
28464 		 */
28465 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
28466 
28467 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
28468 			err = 0;
28469 			break;
28470 		}
28471 
28472 		/*
28473 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
28474 		 * no need to read RQS data.
28475 		 */
28476 		if (pkt->pkt_reason == CMD_DEV_GONE) {
28477 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28478 			    "Error while dumping state with rmw..."
28479 			    "Device is gone\n");
28480 			break;
28481 		}
28482 
28483 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
28484 			SD_INFO(SD_LOG_DUMP, un,
28485 			    "sddump: read failed with CHECK, try # %d\n", i);
28486 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
28487 				(void) sd_send_polled_RQS(un);
28488 			}
28489 
28490 			continue;
28491 		}
28492 
28493 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
28494 			int reset_retval = 0;
28495 
28496 			SD_INFO(SD_LOG_DUMP, un,
28497 			    "sddump: read failed with BUSY, try # %d\n", i);
28498 
28499 			if (un->un_f_lun_reset_enabled == TRUE) {
28500 				reset_retval = scsi_reset(SD_ADDRESS(un),
28501 				    RESET_LUN);
28502 			}
28503 			if (reset_retval == 0) {
28504 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
28505 			}
28506 			(void) sd_send_polled_RQS(un);
28507 
28508 		} else {
28509 			SD_INFO(SD_LOG_DUMP, un,
28510 			    "sddump: read failed with 0x%x, try # %d\n",
28511 			    SD_GET_PKT_STATUS(pkt), i);
28512 			mutex_enter(SD_MUTEX(un));
28513 			sd_reset_target(un, pkt);
28514 			mutex_exit(SD_MUTEX(un));
28515 		}
28516 
28517 		/*
28518 		 * If we are not getting anywhere with lun/target resets,
28519 		 * let's reset the bus.
28520 		 */
28521 		if (i > SD_NDUMP_RETRIES/2) {
28522 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
28523 			(void) sd_send_polled_RQS(un);
28524 		}
28525 
28526 	}
28527 	scsi_destroy_pkt(pkt);
28528 
28529 	if (err != 0) {
28530 		scsi_free_consistent_buf(bp);
28531 		*bpp = NULL;
28532 	} else {
28533 		*bpp = bp;
28534 	}
28535 
28536 done:
28537 	mutex_enter(SD_MUTEX(un));
28538 	return (err);
28539 }
28540 
28541 
28542 /*
28543  *    Function: sd_failfast_flushq
28544  *
28545  * Description: Take all bp's on the wait queue that have B_FAILFAST set
28546  *		in b_flags and move them onto the failfast queue, then kick
28547  *		off a thread to return all bp's on the failfast queue to
28548  *		their owners with an error set.
28549  *
28550  *   Arguments: un - pointer to the soft state struct for the instance.
28551  *
28552  *     Context: may execute in interrupt context.
28553  */
28554 
28555 static void
28556 sd_failfast_flushq(struct sd_lun *un)
28557 {
28558 	struct buf *bp;
28559 	struct buf *next_waitq_bp;
28560 	struct buf *prev_waitq_bp = NULL;
28561 
28562 	ASSERT(un != NULL);
28563 	ASSERT(mutex_owned(SD_MUTEX(un)));
28564 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
28565 	ASSERT(un->un_failfast_bp == NULL);
28566 
28567 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
28568 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
28569 
28570 	/*
28571 	 * Check if we should flush all bufs when entering failfast state, or
28572 	 * just those with B_FAILFAST set.
28573 	 */
28574 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
28575 		/*
28576 		 * Move *all* bp's on the wait queue to the failfast flush
28577 		 * queue, including those that do NOT have B_FAILFAST set.
28578 		 */
28579 		if (un->un_failfast_headp == NULL) {
28580 			ASSERT(un->un_failfast_tailp == NULL);
28581 			un->un_failfast_headp = un->un_waitq_headp;
28582 		} else {
28583 			ASSERT(un->un_failfast_tailp != NULL);
28584 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
28585 		}
28586 
28587 		un->un_failfast_tailp = un->un_waitq_tailp;
28588 
28589 		/* update kstat for each bp moved out of the waitq */
28590 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
28591 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
28592 		}
28593 
28594 		/* empty the waitq */
28595 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
28596 
28597 	} else {
28598 		/*
28599 		 * Go thru the wait queue, pick off all entries with
28600 		 * B_FAILFAST set, and move these onto the failfast queue.
28601 		 */
28602 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
28603 			/*
28604 			 * Save the pointer to the next bp on the wait queue,
28605 			 * so we get to it on the next iteration of this loop.
28606 			 */
28607 			next_waitq_bp = bp->av_forw;
28608 
28609 			/*
28610 			 * If this bp from the wait queue does NOT have
28611 			 * B_FAILFAST set, just move on to the next element
28612 			 * in the wait queue. Note, this is the only place
28613 			 * where it is correct to set prev_waitq_bp.
28614 			 */
28615 			if ((bp->b_flags & B_FAILFAST) == 0) {
28616 				prev_waitq_bp = bp;
28617 				continue;
28618 			}
28619 
28620 			/*
28621 			 * Remove the bp from the wait queue.
28622 			 */
28623 			if (bp == un->un_waitq_headp) {
28624 				/* The bp is the first element of the waitq. */
28625 				un->un_waitq_headp = next_waitq_bp;
28626 				if (un->un_waitq_headp == NULL) {
28627 					/* The wait queue is now empty */
28628 					un->un_waitq_tailp = NULL;
28629 				}
28630 			} else {
28631 				/*
28632 				 * The bp is either somewhere in the middle
28633 				 * or at the end of the wait queue.
28634 				 */
28635 				ASSERT(un->un_waitq_headp != NULL);
28636 				ASSERT(prev_waitq_bp != NULL);
28637 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
28638 				    == 0);
28639 				if (bp == un->un_waitq_tailp) {
28640 					/* bp is the last entry on the waitq. */
28641 					ASSERT(next_waitq_bp == NULL);
28642 					un->un_waitq_tailp = prev_waitq_bp;
28643 				}
28644 				prev_waitq_bp->av_forw = next_waitq_bp;
28645 			}
28646 			bp->av_forw = NULL;
28647 
28648 			/*
28649 			 * update kstat since the bp is moved out of
28650 			 * the waitq
28651 			 */
28652 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
28653 
28654 			/*
28655 			 * Now put the bp onto the failfast queue.
28656 			 */
28657 			if (un->un_failfast_headp == NULL) {
28658 				/* failfast queue is currently empty */
28659 				ASSERT(un->un_failfast_tailp == NULL);
28660 				un->un_failfast_headp =
28661 				    un->un_failfast_tailp = bp;
28662 			} else {
28663 				/* Add the bp to the end of the failfast q */
28664 				ASSERT(un->un_failfast_tailp != NULL);
28665 				ASSERT(un->un_failfast_tailp->b_flags &
28666 				    B_FAILFAST);
28667 				un->un_failfast_tailp->av_forw = bp;
28668 				un->un_failfast_tailp = bp;
28669 			}
28670 		}
28671 	}
28672 
28673 	/*
28674 	 * Now return all bp's on the failfast queue to their owners.
28675 	 */
28676 	while ((bp = un->un_failfast_headp) != NULL) {
28677 
28678 		un->un_failfast_headp = bp->av_forw;
28679 		if (un->un_failfast_headp == NULL) {
28680 			un->un_failfast_tailp = NULL;
28681 		}
28682 
28683 		/*
28684 		 * We want to return the bp with a failure error code, but
28685 		 * we do not want a call to sd_start_cmds() to occur here,
28686 		 * so use sd_return_failed_command_no_restart() instead of
28687 		 * sd_return_failed_command().
28688 		 */
28689 		sd_return_failed_command_no_restart(un, bp, EIO);
28690 	}
28691 
28692 	/* Flush the xbuf queues if required. */
28693 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
28694 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
28695 	}
28696 
28697 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
28698 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
28699 }
28700 
28701 
28702 /*
28703  *    Function: sd_failfast_flushq_callback
28704  *
28705  * Description: Return TRUE if the given bp meets the criteria for failfast
28706  *		flushing. Used with ddi_xbuf_flushq(9F).
28707  *
28708  *   Arguments: bp - ptr to buf struct to be examined.
28709  *
28710  *     Context: Any
28711  */
28712 
28713 static int
28714 sd_failfast_flushq_callback(struct buf *bp)
28715 {
28716 	/*
28717 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
28718 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
28719 	 */
28720 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
28721 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
28722 }
28723 
28724 
28725 
28726 /*
28727  * Function: sd_setup_next_xfer
28728  *
28729  * Description: Prepare next I/O operation using DMA_PARTIAL
28730  *
28731  */
28732 
28733 static int
28734 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
28735     struct scsi_pkt *pkt, struct sd_xbuf *xp)
28736 {
28737 	ssize_t	num_blks_not_xfered;
28738 	daddr_t	strt_blk_num;
28739 	ssize_t	bytes_not_xfered;
28740 	int	rval;
28741 
28742 	ASSERT(pkt->pkt_resid == 0);
28743 
28744 	/*
28745 	 * Calculate next block number and amount to be transferred.
28746 	 *
28747 	 * How much data NOT transfered to the HBA yet.
28748 	 */
28749 	bytes_not_xfered = xp->xb_dma_resid;
28750 
28751 	/*
28752 	 * figure how many blocks NOT transfered to the HBA yet.
28753 	 */
28754 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
28755 
28756 	/*
28757 	 * set starting block number to the end of what WAS transfered.
28758 	 */
28759 	strt_blk_num = xp->xb_blkno +
28760 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
28761 
28762 	/*
28763 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
28764 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
28765 	 * the disk mutex here.
28766 	 */
28767 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
28768 	    strt_blk_num, num_blks_not_xfered);
28769 
28770 	if (rval == 0) {
28771 
28772 		/*
28773 		 * Success.
28774 		 *
28775 		 * Adjust things if there are still more blocks to be
28776 		 * transfered.
28777 		 */
28778 		xp->xb_dma_resid = pkt->pkt_resid;
28779 		pkt->pkt_resid = 0;
28780 
28781 		return (1);
28782 	}
28783 
28784 	/*
28785 	 * There's really only one possible return value from
28786 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
28787 	 * returns NULL.
28788 	 */
28789 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
28790 
28791 	bp->b_resid = bp->b_bcount;
28792 	bp->b_flags |= B_ERROR;
28793 
28794 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28795 	    "Error setting up next portion of DMA transfer\n");
28796 
28797 	return (0);
28798 }
28799 
28800 /*
28801  *    Function: sd_panic_for_res_conflict
28802  *
28803  * Description: Call panic with a string formatted with "Reservation Conflict"
28804  *		and a human readable identifier indicating the SD instance
28805  *		that experienced the reservation conflict.
28806  *
28807  *   Arguments: un - pointer to the soft state struct for the instance.
28808  *
28809  *     Context: may execute in interrupt context.
28810  */
28811 
28812 #define	SD_RESV_CONFLICT_FMT_LEN 40
28813 void
28814 sd_panic_for_res_conflict(struct sd_lun *un)
28815 {
28816 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
28817 	char path_str[MAXPATHLEN];
28818 
28819 	(void) snprintf(panic_str, sizeof (panic_str),
28820 	    "Reservation Conflict\nDisk: %s",
28821 	    ddi_pathname(SD_DEVINFO(un), path_str));
28822 
28823 	panic(panic_str);
28824 }
28825 
28826 /*
28827  * Note: The following sd_faultinjection_ioctl( ) routines implement
28828  * driver support for handling fault injection for error analysis
28829  * causing faults in multiple layers of the driver.
28830  *
28831  */
28832 
28833 #ifdef SD_FAULT_INJECTION
28834 static uint_t   sd_fault_injection_on = 0;
28835 
28836 /*
28837  *    Function: sd_faultinjection_ioctl()
28838  *
28839  * Description: This routine is the driver entry point for handling
28840  *              faultinjection ioctls to inject errors into the
28841  *              layer model
28842  *
28843  *   Arguments: cmd	- the ioctl cmd received
28844  *		arg	- the arguments from user and returns
28845  */
28846 
28847 static void
28848 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
28849 
28850 	uint_t i = 0;
28851 	uint_t rval;
28852 
28853 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
28854 
28855 	mutex_enter(SD_MUTEX(un));
28856 
28857 	switch (cmd) {
28858 	case SDIOCRUN:
28859 		/* Allow pushed faults to be injected */
28860 		SD_INFO(SD_LOG_SDTEST, un,
28861 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
28862 
28863 		sd_fault_injection_on = 1;
28864 
28865 		SD_INFO(SD_LOG_IOERR, un,
28866 		    "sd_faultinjection_ioctl: run finished\n");
28867 		break;
28868 
28869 	case SDIOCSTART:
28870 		/* Start Injection Session */
28871 		SD_INFO(SD_LOG_SDTEST, un,
28872 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
28873 
28874 		sd_fault_injection_on = 0;
28875 		un->sd_injection_mask = 0xFFFFFFFF;
28876 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
28877 			un->sd_fi_fifo_pkt[i] = NULL;
28878 			un->sd_fi_fifo_xb[i] = NULL;
28879 			un->sd_fi_fifo_un[i] = NULL;
28880 			un->sd_fi_fifo_arq[i] = NULL;
28881 		}
28882 		un->sd_fi_fifo_start = 0;
28883 		un->sd_fi_fifo_end = 0;
28884 
28885 		mutex_enter(&(un->un_fi_mutex));
28886 		un->sd_fi_log[0] = '\0';
28887 		un->sd_fi_buf_len = 0;
28888 		mutex_exit(&(un->un_fi_mutex));
28889 
28890 		SD_INFO(SD_LOG_IOERR, un,
28891 		    "sd_faultinjection_ioctl: start finished\n");
28892 		break;
28893 
28894 	case SDIOCSTOP:
28895 		/* Stop Injection Session */
28896 		SD_INFO(SD_LOG_SDTEST, un,
28897 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
28898 		sd_fault_injection_on = 0;
28899 		un->sd_injection_mask = 0x0;
28900 
28901 		/* Empty stray or unuseds structs from fifo */
28902 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
28903 			if (un->sd_fi_fifo_pkt[i] != NULL) {
28904 				kmem_free(un->sd_fi_fifo_pkt[i],
28905 				    sizeof (struct sd_fi_pkt));
28906 			}
28907 			if (un->sd_fi_fifo_xb[i] != NULL) {
28908 				kmem_free(un->sd_fi_fifo_xb[i],
28909 				    sizeof (struct sd_fi_xb));
28910 			}
28911 			if (un->sd_fi_fifo_un[i] != NULL) {
28912 				kmem_free(un->sd_fi_fifo_un[i],
28913 				    sizeof (struct sd_fi_un));
28914 			}
28915 			if (un->sd_fi_fifo_arq[i] != NULL) {
28916 				kmem_free(un->sd_fi_fifo_arq[i],
28917 				    sizeof (struct sd_fi_arq));
28918 			}
28919 			un->sd_fi_fifo_pkt[i] = NULL;
28920 			un->sd_fi_fifo_un[i] = NULL;
28921 			un->sd_fi_fifo_xb[i] = NULL;
28922 			un->sd_fi_fifo_arq[i] = NULL;
28923 		}
28924 		un->sd_fi_fifo_start = 0;
28925 		un->sd_fi_fifo_end = 0;
28926 
28927 		SD_INFO(SD_LOG_IOERR, un,
28928 		    "sd_faultinjection_ioctl: stop finished\n");
28929 		break;
28930 
28931 	case SDIOCINSERTPKT:
28932 		/* Store a packet struct to be pushed onto fifo */
28933 		SD_INFO(SD_LOG_SDTEST, un,
28934 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
28935 
28936 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
28937 
28938 		sd_fault_injection_on = 0;
28939 
28940 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
28941 		if (un->sd_fi_fifo_pkt[i] != NULL) {
28942 			kmem_free(un->sd_fi_fifo_pkt[i],
28943 			    sizeof (struct sd_fi_pkt));
28944 		}
28945 		if (arg != NULL) {
28946 			un->sd_fi_fifo_pkt[i] =
28947 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
28948 			if (un->sd_fi_fifo_pkt[i] == NULL) {
28949 				/* Alloc failed don't store anything */
28950 				break;
28951 			}
28952 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
28953 			    sizeof (struct sd_fi_pkt), 0);
28954 			if (rval == -1) {
28955 				kmem_free(un->sd_fi_fifo_pkt[i],
28956 				    sizeof (struct sd_fi_pkt));
28957 				un->sd_fi_fifo_pkt[i] = NULL;
28958 			}
28959 		} else {
28960 			SD_INFO(SD_LOG_IOERR, un,
28961 			    "sd_faultinjection_ioctl: pkt null\n");
28962 		}
28963 		break;
28964 
28965 	case SDIOCINSERTXB:
28966 		/* Store a xb struct to be pushed onto fifo */
28967 		SD_INFO(SD_LOG_SDTEST, un,
28968 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
28969 
28970 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
28971 
28972 		sd_fault_injection_on = 0;
28973 
28974 		if (un->sd_fi_fifo_xb[i] != NULL) {
28975 			kmem_free(un->sd_fi_fifo_xb[i],
28976 			    sizeof (struct sd_fi_xb));
28977 			un->sd_fi_fifo_xb[i] = NULL;
28978 		}
28979 		if (arg != NULL) {
28980 			un->sd_fi_fifo_xb[i] =
28981 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
28982 			if (un->sd_fi_fifo_xb[i] == NULL) {
28983 				/* Alloc failed don't store anything */
28984 				break;
28985 			}
28986 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
28987 			    sizeof (struct sd_fi_xb), 0);
28988 
28989 			if (rval == -1) {
28990 				kmem_free(un->sd_fi_fifo_xb[i],
28991 				    sizeof (struct sd_fi_xb));
28992 				un->sd_fi_fifo_xb[i] = NULL;
28993 			}
28994 		} else {
28995 			SD_INFO(SD_LOG_IOERR, un,
28996 			    "sd_faultinjection_ioctl: xb null\n");
28997 		}
28998 		break;
28999 
29000 	case SDIOCINSERTUN:
29001 		/* Store a un struct to be pushed onto fifo */
29002 		SD_INFO(SD_LOG_SDTEST, un,
29003 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
29004 
29005 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29006 
29007 		sd_fault_injection_on = 0;
29008 
29009 		if (un->sd_fi_fifo_un[i] != NULL) {
29010 			kmem_free(un->sd_fi_fifo_un[i],
29011 			    sizeof (struct sd_fi_un));
29012 			un->sd_fi_fifo_un[i] = NULL;
29013 		}
29014 		if (arg != NULL) {
29015 			un->sd_fi_fifo_un[i] =
29016 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
29017 			if (un->sd_fi_fifo_un[i] == NULL) {
29018 				/* Alloc failed don't store anything */
29019 				break;
29020 			}
29021 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
29022 			    sizeof (struct sd_fi_un), 0);
29023 			if (rval == -1) {
29024 				kmem_free(un->sd_fi_fifo_un[i],
29025 				    sizeof (struct sd_fi_un));
29026 				un->sd_fi_fifo_un[i] = NULL;
29027 			}
29028 
29029 		} else {
29030 			SD_INFO(SD_LOG_IOERR, un,
29031 			    "sd_faultinjection_ioctl: un null\n");
29032 		}
29033 
29034 		break;
29035 
29036 	case SDIOCINSERTARQ:
29037 		/* Store a arq struct to be pushed onto fifo */
29038 		SD_INFO(SD_LOG_SDTEST, un,
29039 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
29040 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
29041 
29042 		sd_fault_injection_on = 0;
29043 
29044 		if (un->sd_fi_fifo_arq[i] != NULL) {
29045 			kmem_free(un->sd_fi_fifo_arq[i],
29046 			    sizeof (struct sd_fi_arq));
29047 			un->sd_fi_fifo_arq[i] = NULL;
29048 		}
29049 		if (arg != NULL) {
29050 			un->sd_fi_fifo_arq[i] =
29051 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
29052 			if (un->sd_fi_fifo_arq[i] == NULL) {
29053 				/* Alloc failed don't store anything */
29054 				break;
29055 			}
29056 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
29057 			    sizeof (struct sd_fi_arq), 0);
29058 			if (rval == -1) {
29059 				kmem_free(un->sd_fi_fifo_arq[i],
29060 				    sizeof (struct sd_fi_arq));
29061 				un->sd_fi_fifo_arq[i] = NULL;
29062 			}
29063 
29064 		} else {
29065 			SD_INFO(SD_LOG_IOERR, un,
29066 			    "sd_faultinjection_ioctl: arq null\n");
29067 		}
29068 
29069 		break;
29070 
29071 	case SDIOCPUSH:
29072 		/* Push stored xb, pkt, un, and arq onto fifo */
29073 		sd_fault_injection_on = 0;
29074 
29075 		if (arg != NULL) {
29076 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
29077 			if (rval != -1 &&
29078 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
29079 				un->sd_fi_fifo_end += i;
29080 			}
29081 		} else {
29082 			SD_INFO(SD_LOG_IOERR, un,
29083 			    "sd_faultinjection_ioctl: push arg null\n");
29084 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
29085 				un->sd_fi_fifo_end++;
29086 			}
29087 		}
29088 		SD_INFO(SD_LOG_IOERR, un,
29089 		    "sd_faultinjection_ioctl: push to end=%d\n",
29090 		    un->sd_fi_fifo_end);
29091 		break;
29092 
29093 	case SDIOCRETRIEVE:
29094 		/* Return buffer of log from Injection session */
29095 		SD_INFO(SD_LOG_SDTEST, un,
29096 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
29097 
29098 		sd_fault_injection_on = 0;
29099 
29100 		mutex_enter(&(un->un_fi_mutex));
29101 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
29102 		    un->sd_fi_buf_len+1, 0);
29103 		mutex_exit(&(un->un_fi_mutex));
29104 
29105 		if (rval == -1) {
29106 			/*
29107 			 * arg is possibly invalid setting
29108 			 * it to NULL for return
29109 			 */
29110 			arg = NULL;
29111 		}
29112 		break;
29113 	}
29114 
29115 	mutex_exit(SD_MUTEX(un));
29116 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
29117 			    " exit\n");
29118 }
29119 
29120 
29121 /*
29122  *    Function: sd_injection_log()
29123  *
29124  * Description: This routine adds buff to the already existing injection log
29125  *              for retrieval via faultinjection_ioctl for use in fault
29126  *              detection and recovery
29127  *
29128  *   Arguments: buf - the string to add to the log
29129  */
29130 
29131 static void
29132 sd_injection_log(char *buf, struct sd_lun *un)
29133 {
29134 	uint_t len;
29135 
29136 	ASSERT(un != NULL);
29137 	ASSERT(buf != NULL);
29138 
29139 	mutex_enter(&(un->un_fi_mutex));
29140 
29141 	len = min(strlen(buf), 255);
29142 	/* Add logged value to Injection log to be returned later */
29143 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
29144 		uint_t	offset = strlen((char *)un->sd_fi_log);
29145 		char *destp = (char *)un->sd_fi_log + offset;
29146 		int i;
29147 		for (i = 0; i < len; i++) {
29148 			*destp++ = *buf++;
29149 		}
29150 		un->sd_fi_buf_len += len;
29151 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
29152 	}
29153 
29154 	mutex_exit(&(un->un_fi_mutex));
29155 }
29156 
29157 
29158 /*
29159  *    Function: sd_faultinjection()
29160  *
29161  * Description: This routine takes the pkt and changes its
29162  *		content based on error injection scenerio.
29163  *
29164  *   Arguments: pktp	- packet to be changed
29165  */
29166 
29167 static void
29168 sd_faultinjection(struct scsi_pkt *pktp)
29169 {
29170 	uint_t i;
29171 	struct sd_fi_pkt *fi_pkt;
29172 	struct sd_fi_xb *fi_xb;
29173 	struct sd_fi_un *fi_un;
29174 	struct sd_fi_arq *fi_arq;
29175 	struct buf *bp;
29176 	struct sd_xbuf *xb;
29177 	struct sd_lun *un;
29178 
29179 	ASSERT(pktp != NULL);
29180 
29181 	/* pull bp xb and un from pktp */
29182 	bp = (struct buf *)pktp->pkt_private;
29183 	xb = SD_GET_XBUF(bp);
29184 	un = SD_GET_UN(bp);
29185 
29186 	ASSERT(un != NULL);
29187 
29188 	mutex_enter(SD_MUTEX(un));
29189 
29190 	SD_TRACE(SD_LOG_SDTEST, un,
29191 	    "sd_faultinjection: entry Injection from sdintr\n");
29192 
29193 	/* if injection is off return */
29194 	if (sd_fault_injection_on == 0 ||
29195 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
29196 		mutex_exit(SD_MUTEX(un));
29197 		return;
29198 	}
29199 
29200 	SD_INFO(SD_LOG_SDTEST, un,
29201 	    "sd_faultinjection: is working for copying\n");
29202 
29203 	/* take next set off fifo */
29204 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
29205 
29206 	fi_pkt = un->sd_fi_fifo_pkt[i];
29207 	fi_xb = un->sd_fi_fifo_xb[i];
29208 	fi_un = un->sd_fi_fifo_un[i];
29209 	fi_arq = un->sd_fi_fifo_arq[i];
29210 
29211 
29212 	/* set variables accordingly */
29213 	/* set pkt if it was on fifo */
29214 	if (fi_pkt != NULL) {
29215 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
29216 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
29217 		if (fi_pkt->pkt_cdbp != 0xff)
29218 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
29219 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
29220 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
29221 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
29222 
29223 	}
29224 	/* set xb if it was on fifo */
29225 	if (fi_xb != NULL) {
29226 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
29227 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
29228 		if (fi_xb->xb_retry_count != 0)
29229 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
29230 		SD_CONDSET(xb, xb, xb_victim_retry_count,
29231 		    "xb_victim_retry_count");
29232 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
29233 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
29234 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
29235 
29236 		/* copy in block data from sense */
29237 		/*
29238 		 * if (fi_xb->xb_sense_data[0] != -1) {
29239 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
29240 		 *	SENSE_LENGTH);
29241 		 * }
29242 		 */
29243 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
29244 
29245 		/* copy in extended sense codes */
29246 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29247 		    xb, es_code, "es_code");
29248 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29249 		    xb, es_key, "es_key");
29250 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29251 		    xb, es_add_code, "es_add_code");
29252 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
29253 		    xb, es_qual_code, "es_qual_code");
29254 		struct scsi_extended_sense *esp;
29255 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
29256 		esp->es_class = CLASS_EXTENDED_SENSE;
29257 	}
29258 
29259 	/* set un if it was on fifo */
29260 	if (fi_un != NULL) {
29261 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
29262 		SD_CONDSET(un, un, un_ctype, "un_ctype");
29263 		SD_CONDSET(un, un, un_reset_retry_count,
29264 		    "un_reset_retry_count");
29265 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
29266 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
29267 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
29268 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
29269 		    "un_f_allow_bus_device_reset");
29270 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
29271 
29272 	}
29273 
29274 	/* copy in auto request sense if it was on fifo */
29275 	if (fi_arq != NULL) {
29276 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
29277 	}
29278 
29279 	/* free structs */
29280 	if (un->sd_fi_fifo_pkt[i] != NULL) {
29281 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
29282 	}
29283 	if (un->sd_fi_fifo_xb[i] != NULL) {
29284 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
29285 	}
29286 	if (un->sd_fi_fifo_un[i] != NULL) {
29287 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
29288 	}
29289 	if (un->sd_fi_fifo_arq[i] != NULL) {
29290 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
29291 	}
29292 
29293 	/*
29294 	 * kmem_free does not gurantee to set to NULL
29295 	 * since we uses these to determine if we set
29296 	 * values or not lets confirm they are always
29297 	 * NULL after free
29298 	 */
29299 	un->sd_fi_fifo_pkt[i] = NULL;
29300 	un->sd_fi_fifo_un[i] = NULL;
29301 	un->sd_fi_fifo_xb[i] = NULL;
29302 	un->sd_fi_fifo_arq[i] = NULL;
29303 
29304 	un->sd_fi_fifo_start++;
29305 
29306 	mutex_exit(SD_MUTEX(un));
29307 
29308 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
29309 }
29310 
29311 #endif /* SD_FAULT_INJECTION */
29312 
29313 /*
29314  * This routine is invoked in sd_unit_attach(). Before calling it, the
29315  * properties in conf file should be processed already, and "hotpluggable"
29316  * property was processed also.
29317  *
29318  * The sd driver distinguishes 3 different type of devices: removable media,
29319  * non-removable media, and hotpluggable. Below the differences are defined:
29320  *
29321  * 1. Device ID
29322  *
29323  *     The device ID of a device is used to identify this device. Refer to
29324  *     ddi_devid_register(9F).
29325  *
29326  *     For a non-removable media disk device which can provide 0x80 or 0x83
29327  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
29328  *     device ID is created to identify this device. For other non-removable
29329  *     media devices, a default device ID is created only if this device has
29330  *     at least 2 alter cylinders. Otherwise, this device has no devid.
29331  *
29332  *     -------------------------------------------------------
29333  *     removable media   hotpluggable  | Can Have Device ID
29334  *     -------------------------------------------------------
29335  *         false             false     |     Yes
29336  *         false             true      |     Yes
29337  *         true                x       |     No
29338  *     ------------------------------------------------------
29339  *
29340  *
29341  * 2. SCSI group 4 commands
29342  *
29343  *     In SCSI specs, only some commands in group 4 command set can use
29344  *     8-byte addresses that can be used to access >2TB storage spaces.
29345  *     Other commands have no such capability. Without supporting group4,
29346  *     it is impossible to make full use of storage spaces of a disk with
29347  *     capacity larger than 2TB.
29348  *
29349  *     -----------------------------------------------
29350  *     removable media   hotpluggable   LP64  |  Group
29351  *     -----------------------------------------------
29352  *           false          false       false |   1
29353  *           false          false       true  |   4
29354  *           false          true        false |   1
29355  *           false          true        true  |   4
29356  *           true             x           x   |   5
29357  *     -----------------------------------------------
29358  *
29359  *
29360  * 3. Check for VTOC Label
29361  *
29362  *     If a direct-access disk has no EFI label, sd will check if it has a
29363  *     valid VTOC label. Now, sd also does that check for removable media
29364  *     and hotpluggable devices.
29365  *
29366  *     --------------------------------------------------------------
29367  *     Direct-Access   removable media    hotpluggable |  Check Label
29368  *     -------------------------------------------------------------
29369  *         false          false           false        |   No
29370  *         false          false           true         |   No
29371  *         false          true            false        |   Yes
29372  *         false          true            true         |   Yes
29373  *         true            x                x          |   Yes
29374  *     --------------------------------------------------------------
29375  *
29376  *
29377  * 4. Building default VTOC label
29378  *
29379  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
29380  *     If those devices have no valid VTOC label, sd(7d) will attempt to
29381  *     create default VTOC for them. Currently sd creates default VTOC label
29382  *     for all devices on x86 platform (VTOC_16), but only for removable
29383  *     media devices on SPARC (VTOC_8).
29384  *
29385  *     -----------------------------------------------------------
29386  *       removable media hotpluggable platform   |   Default Label
29387  *     -----------------------------------------------------------
29388  *             false          false    sparc     |     No
29389  *             false          true      x86      |     Yes
29390  *             false          true     sparc     |     Yes
29391  *             true             x        x       |     Yes
29392  *     ----------------------------------------------------------
29393  *
29394  *
29395  * 5. Supported blocksizes of target devices
29396  *
29397  *     Sd supports non-512-byte blocksize for removable media devices only.
29398  *     For other devices, only 512-byte blocksize is supported. This may be
29399  *     changed in near future because some RAID devices require non-512-byte
29400  *     blocksize
29401  *
29402  *     -----------------------------------------------------------
29403  *     removable media    hotpluggable    | non-512-byte blocksize
29404  *     -----------------------------------------------------------
29405  *           false          false         |   No
29406  *           false          true          |   No
29407  *           true             x           |   Yes
29408  *     -----------------------------------------------------------
29409  *
29410  *
29411  * 6. Automatic mount & unmount
29412  *
29413  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
29414  *     if a device is removable media device. It return 1 for removable media
29415  *     devices, and 0 for others.
29416  *
29417  *     The automatic mounting subsystem should distinguish between the types
29418  *     of devices and apply automounting policies to each.
29419  *
29420  *
29421  * 7. fdisk partition management
29422  *
29423  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
29424  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
29425  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
29426  *     fdisk partitions on both x86 and SPARC platform.
29427  *
29428  *     -----------------------------------------------------------
29429  *       platform   removable media  USB/1394  |  fdisk supported
29430  *     -----------------------------------------------------------
29431  *        x86         X               X        |       true
29432  *     ------------------------------------------------------------
29433  *        sparc       X               X        |       false
29434  *     ------------------------------------------------------------
29435  *
29436  *
29437  * 8. MBOOT/MBR
29438  *
29439  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
29440  *     read/write mboot for removable media devices on sparc platform.
29441  *
29442  *     -----------------------------------------------------------
29443  *       platform   removable media  USB/1394  |  mboot supported
29444  *     -----------------------------------------------------------
29445  *        x86         X               X        |       true
29446  *     ------------------------------------------------------------
29447  *        sparc      false           false     |       false
29448  *        sparc      false           true      |       true
29449  *        sparc      true            false     |       true
29450  *        sparc      true            true      |       true
29451  *     ------------------------------------------------------------
29452  *
29453  *
29454  * 9.  error handling during opening device
29455  *
29456  *     If failed to open a disk device, an errno is returned. For some kinds
29457  *     of errors, different errno is returned depending on if this device is
29458  *     a removable media device. This brings USB/1394 hard disks in line with
29459  *     expected hard disk behavior. It is not expected that this breaks any
29460  *     application.
29461  *
29462  *     ------------------------------------------------------
29463  *       removable media    hotpluggable   |  errno
29464  *     ------------------------------------------------------
29465  *             false          false        |   EIO
29466  *             false          true         |   EIO
29467  *             true             x          |   ENXIO
29468  *     ------------------------------------------------------
29469  *
29470  *
29471  * 11. ioctls: DKIOCEJECT, CDROMEJECT
29472  *
29473  *     These IOCTLs are applicable only to removable media devices.
29474  *
29475  *     -----------------------------------------------------------
29476  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
29477  *     -----------------------------------------------------------
29478  *             false          false        |     No
29479  *             false          true         |     No
29480  *             true            x           |     Yes
29481  *     -----------------------------------------------------------
29482  *
29483  *
29484  * 12. Kstats for partitions
29485  *
29486  *     sd creates partition kstat for non-removable media devices. USB and
29487  *     Firewire hard disks now have partition kstats
29488  *
29489  *      ------------------------------------------------------
29490  *       removable media    hotpluggable   |   kstat
29491  *      ------------------------------------------------------
29492  *             false          false        |    Yes
29493  *             false          true         |    Yes
29494  *             true             x          |    No
29495  *       ------------------------------------------------------
29496  *
29497  *
29498  * 13. Removable media & hotpluggable properties
29499  *
29500  *     Sd driver creates a "removable-media" property for removable media
29501  *     devices. Parent nexus drivers create a "hotpluggable" property if
29502  *     it supports hotplugging.
29503  *
29504  *     ---------------------------------------------------------------------
29505  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
29506  *     ---------------------------------------------------------------------
29507  *       false            false       |    No                   No
29508  *       false            true        |    No                   Yes
29509  *       true             false       |    Yes                  No
29510  *       true             true        |    Yes                  Yes
29511  *     ---------------------------------------------------------------------
29512  *
29513  *
29514  * 14. Power Management
29515  *
29516  *     sd only power manages removable media devices or devices that support
29517  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
29518  *
29519  *     A parent nexus that supports hotplugging can also set "pm-capable"
29520  *     if the disk can be power managed.
29521  *
29522  *     ------------------------------------------------------------
29523  *       removable media hotpluggable pm-capable  |   power manage
29524  *     ------------------------------------------------------------
29525  *             false          false     false     |     No
29526  *             false          false     true      |     Yes
29527  *             false          true      false     |     No
29528  *             false          true      true      |     Yes
29529  *             true             x        x        |     Yes
29530  *     ------------------------------------------------------------
29531  *
29532  *      USB and firewire hard disks can now be power managed independently
29533  *      of the framebuffer
29534  *
29535  *
29536  * 15. Support for USB disks with capacity larger than 1TB
29537  *
29538  *     Currently, sd doesn't permit a fixed disk device with capacity
29539  *     larger than 1TB to be used in a 32-bit operating system environment.
29540  *     However, sd doesn't do that for removable media devices. Instead, it
29541  *     assumes that removable media devices cannot have a capacity larger
29542  *     than 1TB. Therefore, using those devices on 32-bit system is partially
29543  *     supported, which can cause some unexpected results.
29544  *
29545  *     ---------------------------------------------------------------------
29546  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
29547  *     ---------------------------------------------------------------------
29548  *             false          false  |   true         |     no
29549  *             false          true   |   true         |     no
29550  *             true           false  |   true         |     Yes
29551  *             true           true   |   true         |     Yes
29552  *     ---------------------------------------------------------------------
29553  *
29554  *
29555  * 16. Check write-protection at open time
29556  *
29557  *     When a removable media device is being opened for writing without NDELAY
29558  *     flag, sd will check if this device is writable. If attempting to open
29559  *     without NDELAY flag a write-protected device, this operation will abort.
29560  *
29561  *     ------------------------------------------------------------
29562  *       removable media    USB/1394   |   WP Check
29563  *     ------------------------------------------------------------
29564  *             false          false    |     No
29565  *             false          true     |     No
29566  *             true           false    |     Yes
29567  *             true           true     |     Yes
29568  *     ------------------------------------------------------------
29569  *
29570  *
29571  * 17. syslog when corrupted VTOC is encountered
29572  *
29573  *      Currently, if an invalid VTOC is encountered, sd only print syslog
29574  *      for fixed SCSI disks.
29575  *     ------------------------------------------------------------
29576  *       removable media    USB/1394   |   print syslog
29577  *     ------------------------------------------------------------
29578  *             false          false    |     Yes
29579  *             false          true     |     No
29580  *             true           false    |     No
29581  *             true           true     |     No
29582  *     ------------------------------------------------------------
29583  */
29584 static void
29585 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
29586 {
29587 	int	pm_capable_prop;
29588 
29589 	ASSERT(un->un_sd);
29590 	ASSERT(un->un_sd->sd_inq);
29591 
29592 	/*
29593 	 * Enable SYNC CACHE support for all devices.
29594 	 */
29595 	un->un_f_sync_cache_supported = TRUE;
29596 
29597 	/*
29598 	 * Set the sync cache required flag to false.
29599 	 * This would ensure that there is no SYNC CACHE
29600 	 * sent when there are no writes
29601 	 */
29602 	un->un_f_sync_cache_required = FALSE;
29603 
29604 	if (un->un_sd->sd_inq->inq_rmb) {
29605 		/*
29606 		 * The media of this device is removable. And for this kind
29607 		 * of devices, it is possible to change medium after opening
29608 		 * devices. Thus we should support this operation.
29609 		 */
29610 		un->un_f_has_removable_media = TRUE;
29611 
29612 		/*
29613 		 * support non-512-byte blocksize of removable media devices
29614 		 */
29615 		un->un_f_non_devbsize_supported = TRUE;
29616 
29617 		/*
29618 		 * Assume that all removable media devices support DOOR_LOCK
29619 		 */
29620 		un->un_f_doorlock_supported = TRUE;
29621 
29622 		/*
29623 		 * For a removable media device, it is possible to be opened
29624 		 * with NDELAY flag when there is no media in drive, in this
29625 		 * case we don't care if device is writable. But if without
29626 		 * NDELAY flag, we need to check if media is write-protected.
29627 		 */
29628 		un->un_f_chk_wp_open = TRUE;
29629 
29630 		/*
29631 		 * need to start a SCSI watch thread to monitor media state,
29632 		 * when media is being inserted or ejected, notify syseventd.
29633 		 */
29634 		un->un_f_monitor_media_state = TRUE;
29635 
29636 		/*
29637 		 * Some devices don't support START_STOP_UNIT command.
29638 		 * Therefore, we'd better check if a device supports it
29639 		 * before sending it.
29640 		 */
29641 		un->un_f_check_start_stop = TRUE;
29642 
29643 		/*
29644 		 * support eject media ioctl:
29645 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
29646 		 */
29647 		un->un_f_eject_media_supported = TRUE;
29648 
29649 		/*
29650 		 * Because many removable-media devices don't support
29651 		 * LOG_SENSE, we couldn't use this command to check if
29652 		 * a removable media device support power-management.
29653 		 * We assume that they support power-management via
29654 		 * START_STOP_UNIT command and can be spun up and down
29655 		 * without limitations.
29656 		 */
29657 		un->un_f_pm_supported = TRUE;
29658 
29659 		/*
29660 		 * Need to create a zero length (Boolean) property
29661 		 * removable-media for the removable media devices.
29662 		 * Note that the return value of the property is not being
29663 		 * checked, since if unable to create the property
29664 		 * then do not want the attach to fail altogether. Consistent
29665 		 * with other property creation in attach.
29666 		 */
29667 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
29668 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
29669 
29670 	} else {
29671 		/*
29672 		 * create device ID for device
29673 		 */
29674 		un->un_f_devid_supported = TRUE;
29675 
29676 		/*
29677 		 * Spin up non-removable-media devices once it is attached
29678 		 */
29679 		un->un_f_attach_spinup = TRUE;
29680 
29681 		/*
29682 		 * According to SCSI specification, Sense data has two kinds of
29683 		 * format: fixed format, and descriptor format. At present, we
29684 		 * don't support descriptor format sense data for removable
29685 		 * media.
29686 		 */
29687 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
29688 			un->un_f_descr_format_supported = TRUE;
29689 		}
29690 
29691 		/*
29692 		 * kstats are created only for non-removable media devices.
29693 		 *
29694 		 * Set this in sd.conf to 0 in order to disable kstats.  The
29695 		 * default is 1, so they are enabled by default.
29696 		 */
29697 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
29698 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
29699 		    "enable-partition-kstats", 1));
29700 
29701 		/*
29702 		 * Check if HBA has set the "pm-capable" property.
29703 		 * If "pm-capable" exists and is non-zero then we can
29704 		 * power manage the device without checking the start/stop
29705 		 * cycle count log sense page.
29706 		 *
29707 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
29708 		 * then we should not power manage the device.
29709 		 *
29710 		 * If "pm-capable" doesn't exist then pm_capable_prop will
29711 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
29712 		 * sd will check the start/stop cycle count log sense page
29713 		 * and power manage the device if the cycle count limit has
29714 		 * not been exceeded.
29715 		 */
29716 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
29717 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
29718 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
29719 			un->un_f_log_sense_supported = TRUE;
29720 		} else {
29721 			/*
29722 			 * pm-capable property exists.
29723 			 *
29724 			 * Convert "TRUE" values for pm_capable_prop to
29725 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
29726 			 * later. "TRUE" values are any values except
29727 			 * SD_PM_CAPABLE_FALSE (0) and
29728 			 * SD_PM_CAPABLE_UNDEFINED (-1)
29729 			 */
29730 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
29731 				un->un_f_log_sense_supported = FALSE;
29732 			} else {
29733 				un->un_f_pm_supported = TRUE;
29734 			}
29735 
29736 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
29737 			    "sd_unit_attach: un:0x%p pm-capable "
29738 			    "property set to %d.\n", un, un->un_f_pm_supported);
29739 		}
29740 	}
29741 
29742 	if (un->un_f_is_hotpluggable) {
29743 
29744 		/*
29745 		 * Have to watch hotpluggable devices as well, since
29746 		 * that's the only way for userland applications to
29747 		 * detect hot removal while device is busy/mounted.
29748 		 */
29749 		un->un_f_monitor_media_state = TRUE;
29750 
29751 		un->un_f_check_start_stop = TRUE;
29752 
29753 	}
29754 }
29755 
29756 /*
29757  * sd_tg_rdwr:
29758  * Provides rdwr access for cmlb via sd_tgops. The start_block is
29759  * in sys block size, req_length in bytes.
29760  *
29761  */
29762 static int
29763 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
29764     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
29765 {
29766 	struct sd_lun *un;
29767 	int path_flag = (int)(uintptr_t)tg_cookie;
29768 	char *dkl = NULL;
29769 	diskaddr_t real_addr = start_block;
29770 	diskaddr_t first_byte, end_block;
29771 
29772 	size_t	buffer_size = reqlength;
29773 	int rval = 0;
29774 	diskaddr_t	cap;
29775 	uint32_t	lbasize;
29776 	sd_ssc_t	*ssc;
29777 
29778 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
29779 	if (un == NULL)
29780 		return (ENXIO);
29781 
29782 	if (cmd != TG_READ && cmd != TG_WRITE)
29783 		return (EINVAL);
29784 
29785 	ssc = sd_ssc_init(un);
29786 	mutex_enter(SD_MUTEX(un));
29787 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
29788 		mutex_exit(SD_MUTEX(un));
29789 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
29790 		    &lbasize, path_flag);
29791 		if (rval != 0)
29792 			goto done1;
29793 		mutex_enter(SD_MUTEX(un));
29794 		sd_update_block_info(un, lbasize, cap);
29795 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
29796 			mutex_exit(SD_MUTEX(un));
29797 			rval = EIO;
29798 			goto done;
29799 		}
29800 	}
29801 
29802 	if (NOT_DEVBSIZE(un)) {
29803 		/*
29804 		 * sys_blocksize != tgt_blocksize, need to re-adjust
29805 		 * blkno and save the index to beginning of dk_label
29806 		 */
29807 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
29808 		real_addr = first_byte / un->un_tgt_blocksize;
29809 
29810 		end_block = (first_byte + reqlength +
29811 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
29812 
29813 		/* round up buffer size to multiple of target block size */
29814 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
29815 
29816 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
29817 		    "label_addr: 0x%x allocation size: 0x%x\n",
29818 		    real_addr, buffer_size);
29819 
29820 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
29821 		    (reqlength % un->un_tgt_blocksize) != 0)
29822 			/* the request is not aligned */
29823 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
29824 	}
29825 
29826 	/*
29827 	 * The MMC standard allows READ CAPACITY to be
29828 	 * inaccurate by a bounded amount (in the interest of
29829 	 * response latency).  As a result, failed READs are
29830 	 * commonplace (due to the reading of metadata and not
29831 	 * data). Depending on the per-Vendor/drive Sense data,
29832 	 * the failed READ can cause many (unnecessary) retries.
29833 	 */
29834 
29835 	if (ISCD(un) && (cmd == TG_READ) &&
29836 	    (un->un_f_blockcount_is_valid == TRUE) &&
29837 	    ((start_block == (un->un_blockcount - 1))||
29838 	    (start_block == (un->un_blockcount - 2)))) {
29839 			path_flag = SD_PATH_DIRECT_PRIORITY;
29840 	}
29841 
29842 	mutex_exit(SD_MUTEX(un));
29843 	if (cmd == TG_READ) {
29844 		rval = sd_send_scsi_READ(ssc, (dkl != NULL)? dkl: bufaddr,
29845 		    buffer_size, real_addr, path_flag);
29846 		if (dkl != NULL)
29847 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
29848 			    real_addr), bufaddr, reqlength);
29849 	} else {
29850 		if (dkl) {
29851 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
29852 			    real_addr, path_flag);
29853 			if (rval) {
29854 				goto done1;
29855 			}
29856 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
29857 			    real_addr), reqlength);
29858 		}
29859 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL)? dkl: bufaddr,
29860 		    buffer_size, real_addr, path_flag);
29861 	}
29862 
29863 done1:
29864 	if (dkl != NULL)
29865 		kmem_free(dkl, buffer_size);
29866 
29867 	if (rval != 0) {
29868 		if (rval == EIO)
29869 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
29870 		else
29871 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
29872 	}
29873 done:
29874 	sd_ssc_fini(ssc);
29875 	return (rval);
29876 }
29877 
29878 
29879 static int
29880 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
29881 {
29882 
29883 	struct sd_lun *un;
29884 	diskaddr_t	cap;
29885 	uint32_t	lbasize;
29886 	int		path_flag = (int)(uintptr_t)tg_cookie;
29887 	int		ret = 0;
29888 
29889 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
29890 	if (un == NULL)
29891 		return (ENXIO);
29892 
29893 	switch (cmd) {
29894 	case TG_GETPHYGEOM:
29895 	case TG_GETVIRTGEOM:
29896 	case TG_GETCAPACITY:
29897 	case TG_GETBLOCKSIZE:
29898 		mutex_enter(SD_MUTEX(un));
29899 
29900 		if ((un->un_f_blockcount_is_valid == TRUE) &&
29901 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
29902 			cap = un->un_blockcount;
29903 			lbasize = un->un_tgt_blocksize;
29904 			mutex_exit(SD_MUTEX(un));
29905 		} else {
29906 			sd_ssc_t	*ssc;
29907 			mutex_exit(SD_MUTEX(un));
29908 			ssc = sd_ssc_init(un);
29909 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
29910 			    &lbasize, path_flag);
29911 			if (ret != 0) {
29912 				if (ret == EIO)
29913 					sd_ssc_assessment(ssc,
29914 					    SD_FMT_STATUS_CHECK);
29915 				else
29916 					sd_ssc_assessment(ssc,
29917 					    SD_FMT_IGNORE);
29918 				sd_ssc_fini(ssc);
29919 				return (ret);
29920 			}
29921 			sd_ssc_fini(ssc);
29922 			mutex_enter(SD_MUTEX(un));
29923 			sd_update_block_info(un, lbasize, cap);
29924 			if ((un->un_f_blockcount_is_valid == FALSE) ||
29925 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
29926 				mutex_exit(SD_MUTEX(un));
29927 				return (EIO);
29928 			}
29929 			mutex_exit(SD_MUTEX(un));
29930 		}
29931 
29932 		if (cmd == TG_GETCAPACITY) {
29933 			*(diskaddr_t *)arg = cap;
29934 			return (0);
29935 		}
29936 
29937 		if (cmd == TG_GETBLOCKSIZE) {
29938 			*(uint32_t *)arg = lbasize;
29939 			return (0);
29940 		}
29941 
29942 		if (cmd == TG_GETPHYGEOM)
29943 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
29944 			    cap, lbasize, path_flag);
29945 		else
29946 			/* TG_GETVIRTGEOM */
29947 			ret = sd_get_virtual_geometry(un,
29948 			    (cmlb_geom_t *)arg, cap, lbasize);
29949 
29950 		return (ret);
29951 
29952 	case TG_GETATTR:
29953 		mutex_enter(SD_MUTEX(un));
29954 		((tg_attribute_t *)arg)->media_is_writable =
29955 		    un->un_f_mmc_writable_media;
29956 		mutex_exit(SD_MUTEX(un));
29957 		return (0);
29958 	default:
29959 		return (ENOTTY);
29960 
29961 	}
29962 }
29963 
29964 /*
29965  *    Function: sd_ssc_ereport_post
29966  *
29967  * Description: Will be called when SD driver need to post an ereport.
29968  *
29969  *    Context: Kernel thread or interrupt context.
29970  */
29971 static void
29972 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
29973 {
29974 	int uscsi_path_instance = 0;
29975 	uchar_t	uscsi_pkt_reason;
29976 	uint32_t uscsi_pkt_state;
29977 	uint32_t uscsi_pkt_statistics;
29978 	uint64_t uscsi_ena;
29979 	uchar_t op_code;
29980 	uint8_t *sensep;
29981 	union scsi_cdb *cdbp;
29982 	uint_t cdblen = 0;
29983 	uint_t senlen = 0;
29984 	struct sd_lun *un;
29985 	dev_info_t *dip;
29986 	char *devid;
29987 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
29988 	    SSC_FLAGS_INVALID_STATUS |
29989 	    SSC_FLAGS_INVALID_SENSE |
29990 	    SSC_FLAGS_INVALID_DATA;
29991 	char assessment[16];
29992 
29993 	ASSERT(ssc != NULL);
29994 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
29995 	ASSERT(ssc->ssc_uscsi_info != NULL);
29996 
29997 	un = ssc->ssc_un;
29998 	ASSERT(un != NULL);
29999 
30000 	dip = un->un_sd->sd_dev;
30001 
30002 	/*
30003 	 * Get the devid:
30004 	 *	devid will only be passed to non-transport error reports.
30005 	 */
30006 	devid = DEVI(dip)->devi_devid_str;
30007 
30008 	/*
30009 	 * If we are syncing or dumping, the command will not be executed
30010 	 * so we bypass this situation.
30011 	 */
30012 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
30013 	    (un->un_state == SD_STATE_DUMPING))
30014 		return;
30015 
30016 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
30017 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
30018 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
30019 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
30020 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
30021 
30022 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
30023 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
30024 
30025 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
30026 	if (cdbp == NULL) {
30027 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30028 		    "sd_ssc_ereport_post meet empty cdb\n");
30029 		return;
30030 	}
30031 
30032 	op_code = cdbp->scc_cmd;
30033 
30034 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
30035 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
30036 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
30037 
30038 	if (senlen > 0)
30039 		ASSERT(sensep != NULL);
30040 
30041 	/*
30042 	 * Initialize drv_assess to corresponding values.
30043 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
30044 	 * on the sense-key returned back.
30045 	 */
30046 	switch (drv_assess) {
30047 		case SD_FM_DRV_RECOVERY:
30048 			(void) sprintf(assessment, "%s", "recovered");
30049 			break;
30050 		case SD_FM_DRV_RETRY:
30051 			(void) sprintf(assessment, "%s", "retry");
30052 			break;
30053 		case SD_FM_DRV_NOTICE:
30054 			(void) sprintf(assessment, "%s", "info");
30055 			break;
30056 		case SD_FM_DRV_FATAL:
30057 		default:
30058 			(void) sprintf(assessment, "%s", "unknown");
30059 	}
30060 	/*
30061 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
30062 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
30063 	 * driver-assessment will always be "recovered" here.
30064 	 */
30065 	if (drv_assess == SD_FM_DRV_RECOVERY) {
30066 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30067 		    "cmd.disk.recovered", uscsi_ena, devid, DDI_NOSLEEP,
30068 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30069 		    "driver-assessment", DATA_TYPE_STRING, assessment,
30070 		    "op-code", DATA_TYPE_UINT8, op_code,
30071 		    "cdb", DATA_TYPE_UINT8_ARRAY,
30072 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30073 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30074 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30075 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
30076 		    NULL);
30077 		return;
30078 	}
30079 
30080 	/*
30081 	 * If there is un-expected/un-decodable data, we should post
30082 	 * ereport.io.scsi.cmd.disk.dev.uderr.
30083 	 * driver-assessment will be set based on parameter drv_assess.
30084 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
30085 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
30086 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
30087 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
30088 	 */
30089 	if (ssc->ssc_flags & ssc_invalid_flags) {
30090 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
30091 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30092 			    "cmd.disk.dev.uderr", uscsi_ena, devid, DDI_NOSLEEP,
30093 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30094 			    "driver-assessment", DATA_TYPE_STRING,
30095 			    drv_assess == SD_FM_DRV_FATAL ?
30096 			    "fail" : assessment,
30097 			    "op-code", DATA_TYPE_UINT8, op_code,
30098 			    "cdb", DATA_TYPE_UINT8_ARRAY,
30099 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30100 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30101 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30102 			    "pkt-stats", DATA_TYPE_UINT32,
30103 			    uscsi_pkt_statistics,
30104 			    "stat-code", DATA_TYPE_UINT8,
30105 			    ssc->ssc_uscsi_cmd->uscsi_status,
30106 			    "un-decode-info", DATA_TYPE_STRING,
30107 			    ssc->ssc_info,
30108 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
30109 			    senlen, sensep,
30110 			    NULL);
30111 		} else {
30112 			/*
30113 			 * For other type of invalid data, the
30114 			 * un-decode-value field would be empty because the
30115 			 * un-decodable content could be seen from upper
30116 			 * level payload or inside un-decode-info.
30117 			 */
30118 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30119 			    "cmd.disk.dev.uderr", uscsi_ena, devid, DDI_NOSLEEP,
30120 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30121 			    "driver-assessment", DATA_TYPE_STRING,
30122 			    drv_assess == SD_FM_DRV_FATAL ?
30123 			    "fail" : assessment,
30124 			    "op-code", DATA_TYPE_UINT8, op_code,
30125 			    "cdb", DATA_TYPE_UINT8_ARRAY,
30126 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30127 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30128 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
30129 			    "pkt-stats", DATA_TYPE_UINT32,
30130 			    uscsi_pkt_statistics,
30131 			    "stat-code", DATA_TYPE_UINT8,
30132 			    ssc->ssc_uscsi_cmd->uscsi_status,
30133 			    "un-decode-info", DATA_TYPE_STRING,
30134 			    ssc->ssc_info,
30135 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
30136 			    0, NULL,
30137 			    NULL);
30138 		}
30139 		ssc->ssc_flags &= ~ssc_invalid_flags;
30140 		return;
30141 	}
30142 
30143 	if (uscsi_pkt_reason != CMD_CMPLT ||
30144 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
30145 		/*
30146 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
30147 		 * set inside sd_start_cmds due to errors(bad packet or
30148 		 * fatal transport error), we should take it as a
30149 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
30150 		 * driver-assessment will be set based on drv_assess.
30151 		 * We will set devid to NULL because it is a transport
30152 		 * error.
30153 		 */
30154 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
30155 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
30156 
30157 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
30158 		    "cmd.disk.tran", uscsi_ena, NULL, DDI_NOSLEEP, FM_VERSION,
30159 		    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30160 		    "driver-assessment", DATA_TYPE_STRING,
30161 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
30162 		    "op-code", DATA_TYPE_UINT8, op_code,
30163 		    "cdb", DATA_TYPE_UINT8_ARRAY,
30164 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30165 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
30166 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
30167 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
30168 		    NULL);
30169 	} else {
30170 		/*
30171 		 * If we got here, we have a completed command, and we need
30172 		 * to further investigate the sense data to see what kind
30173 		 * of ereport we should post.
30174 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr
30175 		 * if sense-key == 0x3.
30176 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
30177 		 * driver-assessment will be set based on the parameter
30178 		 * drv_assess.
30179 		 */
30180 		if (senlen > 0) {
30181 			/*
30182 			 * Here we have sense data available.
30183 			 */
30184 			uint8_t sense_key;
30185 			sense_key = scsi_sense_key(sensep);
30186 			if (sense_key == 0x3) {
30187 				/*
30188 				 * sense-key == 0x3(medium error),
30189 				 * driver-assessment should be "fatal" if
30190 				 * drv_assess is SD_FM_DRV_FATAL.
30191 				 */
30192 				scsi_fm_ereport_post(un->un_sd,
30193 				    uscsi_path_instance,
30194 				    "cmd.disk.dev.rqs.merr",
30195 				    uscsi_ena, devid, DDI_NOSLEEP, FM_VERSION,
30196 				    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30197 				    "driver-assessment",
30198 				    DATA_TYPE_STRING,
30199 				    drv_assess == SD_FM_DRV_FATAL ?
30200 				    "fatal" : assessment,
30201 				    "op-code",
30202 				    DATA_TYPE_UINT8, op_code,
30203 				    "cdb",
30204 				    DATA_TYPE_UINT8_ARRAY, cdblen,
30205 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
30206 				    "pkt-reason",
30207 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
30208 				    "pkt-state",
30209 				    DATA_TYPE_UINT8, uscsi_pkt_state,
30210 				    "pkt-stats",
30211 				    DATA_TYPE_UINT32,
30212 				    uscsi_pkt_statistics,
30213 				    "stat-code",
30214 				    DATA_TYPE_UINT8,
30215 				    ssc->ssc_uscsi_cmd->uscsi_status,
30216 				    "key",
30217 				    DATA_TYPE_UINT8,
30218 				    scsi_sense_key(sensep),
30219 				    "asc",
30220 				    DATA_TYPE_UINT8,
30221 				    scsi_sense_asc(sensep),
30222 				    "ascq",
30223 				    DATA_TYPE_UINT8,
30224 				    scsi_sense_ascq(sensep),
30225 				    "sense-data",
30226 				    DATA_TYPE_UINT8_ARRAY,
30227 				    senlen, sensep,
30228 				    "lba",
30229 				    DATA_TYPE_UINT64,
30230 				    ssc->ssc_uscsi_info->ui_lba,
30231 				    NULL);
30232 				} else {
30233 					/*
30234 					 * if sense-key == 0x4(hardware
30235 					 * error), driver-assessment should
30236 					 * be "fatal" if drv_assess is
30237 					 * SD_FM_DRV_FATAL.
30238 					 */
30239 					scsi_fm_ereport_post(un->un_sd,
30240 					    uscsi_path_instance,
30241 					    "cmd.disk.dev.rqs.derr",
30242 					    uscsi_ena, devid, DDI_NOSLEEP,
30243 					    FM_VERSION,
30244 					    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
30245 					    "driver-assessment",
30246 					    DATA_TYPE_STRING,
30247 					    drv_assess == SD_FM_DRV_FATAL ?
30248 					    (sense_key == 0x4 ?
30249 					    "fatal" : "fail") : assessment,
30250 					    "op-code",
30251 					    DATA_TYPE_UINT8, op_code,
30252 					    "cdb",
30253 					    DATA_TYPE_UINT8_ARRAY, cdblen,
30254 					    ssc->ssc_uscsi_cmd->uscsi_cdb,
30255 					    "pkt-reason",
30256 					    DATA_TYPE_UINT8, uscsi_pkt_reason,
30257 					    "pkt-state",
30258 					    DATA_TYPE_UINT8, uscsi_pkt_state,
30259 					    "pkt-stats",
30260 					    DATA_TYPE_UINT32,
30261 					    uscsi_pkt_statistics,
30262 					    "stat-code",
30263 					    DATA_TYPE_UINT8,
30264 					    ssc->ssc_uscsi_cmd->uscsi_status,
30265 					    "key",
30266 					    DATA_TYPE_UINT8,
30267 					    scsi_sense_key(sensep),
30268 					    "asc",
30269 					    DATA_TYPE_UINT8,
30270 					    scsi_sense_asc(sensep),
30271 					    "ascq",
30272 					    DATA_TYPE_UINT8,
30273 					    scsi_sense_ascq(sensep),
30274 					    "sense-data",
30275 					    DATA_TYPE_UINT8_ARRAY,
30276 					    senlen, sensep,
30277 					    NULL);
30278 				}
30279 		} else {
30280 			/*
30281 			 * For stat_code == STATUS_GOOD, this is not a
30282 			 * hardware error.
30283 			 */
30284 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
30285 				return;
30286 
30287 			/*
30288 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
30289 			 * stat-code but with sense data unavailable.
30290 			 * driver-assessment will be set based on parameter
30291 			 * drv_assess.
30292 			 */
30293 			scsi_fm_ereport_post(un->un_sd,
30294 			    uscsi_path_instance, "cmd.disk.dev.serr", uscsi_ena,
30295 			    devid, DDI_NOSLEEP, FM_VERSION, DATA_TYPE_UINT8,
30296 			    FM_EREPORT_VERS0,
30297 			    "driver-assessment", DATA_TYPE_STRING,
30298 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
30299 			    "op-code", DATA_TYPE_UINT8, op_code,
30300 			    "cdb",
30301 			    DATA_TYPE_UINT8_ARRAY,
30302 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
30303 			    "pkt-reason",
30304 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
30305 			    "pkt-state",
30306 			    DATA_TYPE_UINT8, uscsi_pkt_state,
30307 			    "pkt-stats",
30308 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
30309 			    "stat-code",
30310 			    DATA_TYPE_UINT8,
30311 			    ssc->ssc_uscsi_cmd->uscsi_status,
30312 			    NULL);
30313 		}
30314 	}
30315 }
30316 
30317 /*
30318  *     Function: sd_ssc_extract_info
30319  *
30320  * Description: Extract information available to help generate ereport.
30321  *
30322  *     Context: Kernel thread or interrupt context.
30323  */
30324 static void
30325 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
30326     struct buf *bp, struct sd_xbuf *xp)
30327 {
30328 	size_t senlen = 0;
30329 	union scsi_cdb *cdbp;
30330 	int path_instance;
30331 	/*
30332 	 * Need scsi_cdb_size array to determine the cdb length.
30333 	 */
30334 	extern uchar_t	scsi_cdb_size[];
30335 
30336 	ASSERT(un != NULL);
30337 	ASSERT(pktp != NULL);
30338 	ASSERT(bp != NULL);
30339 	ASSERT(xp != NULL);
30340 	ASSERT(ssc != NULL);
30341 	ASSERT(mutex_owned(SD_MUTEX(un)));
30342 
30343 	/*
30344 	 * Transfer the cdb buffer pointer here.
30345 	 */
30346 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
30347 
30348 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
30349 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
30350 
30351 	/*
30352 	 * Transfer the sense data buffer pointer if sense data is available,
30353 	 * calculate the sense data length first.
30354 	 */
30355 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
30356 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
30357 		/*
30358 		 * For arq case, we will enter here.
30359 		 */
30360 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
30361 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
30362 		} else {
30363 			senlen = SENSE_LENGTH;
30364 		}
30365 	} else {
30366 		/*
30367 		 * For non-arq case, we will enter this branch.
30368 		 */
30369 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
30370 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
30371 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
30372 		}
30373 
30374 	}
30375 
30376 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
30377 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
30378 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
30379 
30380 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
30381 
30382 	/*
30383 	 * Only transfer path_instance when scsi_pkt was properly allocated.
30384 	 */
30385 	path_instance = pktp->pkt_path_instance;
30386 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
30387 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
30388 	else
30389 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
30390 
30391 	/*
30392 	 * Copy in the other fields we may need when posting ereport.
30393 	 */
30394 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
30395 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
30396 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
30397 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
30398 
30399 	/*
30400 	 * For partially read/write command, we will not create ena
30401 	 * in case of a successful command be reconized as recovered.
30402 	 */
30403 	if ((pktp->pkt_reason == CMD_CMPLT) &&
30404 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
30405 	    (senlen == 0)) {
30406 		return;
30407 	}
30408 
30409 	/*
30410 	 * To associate ereports of a single command execution flow, we
30411 	 * need a shared ena for a specific command.
30412 	 */
30413 	if (xp->xb_ena == 0)
30414 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
30415 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
30416 }
30417