xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 5b6f569b)
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 (c) 1990, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 /*
26  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
27  */
28 /*
29  * Copyright 2011 cyril.galibern@opensvc.com
30  */
31 
32 /*
33  * SCSI disk target driver.
34  */
35 #include <sys/scsi/scsi.h>
36 #include <sys/dkbad.h>
37 #include <sys/dklabel.h>
38 #include <sys/dkio.h>
39 #include <sys/fdio.h>
40 #include <sys/cdio.h>
41 #include <sys/mhd.h>
42 #include <sys/vtoc.h>
43 #include <sys/dktp/fdisk.h>
44 #include <sys/kstat.h>
45 #include <sys/vtrace.h>
46 #include <sys/note.h>
47 #include <sys/thread.h>
48 #include <sys/proc.h>
49 #include <sys/efi_partition.h>
50 #include <sys/var.h>
51 #include <sys/aio_req.h>
52 
53 #ifdef __lock_lint
54 #define	_LP64
55 #define	__amd64
56 #endif
57 
58 #if (defined(__fibre))
59 /* Note: is there a leadville version of the following? */
60 #include <sys/fc4/fcal_linkapp.h>
61 #endif
62 #include <sys/taskq.h>
63 #include <sys/uuid.h>
64 #include <sys/byteorder.h>
65 #include <sys/sdt.h>
66 
67 #include "sd_xbuf.h"
68 
69 #include <sys/scsi/targets/sddef.h>
70 #include <sys/cmlb.h>
71 #include <sys/sysevent/eventdefs.h>
72 #include <sys/sysevent/dev.h>
73 
74 #include <sys/fm/protocol.h>
75 
76 /*
77  * Loadable module info.
78  */
79 #if (defined(__fibre))
80 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver"
81 char _depends_on[]	= "misc/scsi misc/cmlb drv/fcp";
82 #else /* !__fibre */
83 #define	SD_MODULE_NAME	"SCSI Disk Driver"
84 char _depends_on[]	= "misc/scsi misc/cmlb";
85 #endif /* !__fibre */
86 
87 /*
88  * Define the interconnect type, to allow the driver to distinguish
89  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
90  *
91  * This is really for backward compatibility. In the future, the driver
92  * should actually check the "interconnect-type" property as reported by
93  * the HBA; however at present this property is not defined by all HBAs,
94  * so we will use this #define (1) to permit the driver to run in
95  * backward-compatibility mode; and (2) to print a notification message
96  * if an FC HBA does not support the "interconnect-type" property.  The
97  * behavior of the driver will be to assume parallel SCSI behaviors unless
98  * the "interconnect-type" property is defined by the HBA **AND** has a
99  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
100  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
101  * Channel behaviors (as per the old ssd).  (Note that the
102  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
103  * will result in the driver assuming parallel SCSI behaviors.)
104  *
105  * (see common/sys/scsi/impl/services.h)
106  *
107  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
108  * since some FC HBAs may already support that, and there is some code in
109  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
110  * default would confuse that code, and besides things should work fine
111  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
112  * "interconnect_type" property.
113  *
114  */
115 #if (defined(__fibre))
116 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
117 #else
118 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
119 #endif
120 
121 /*
122  * The name of the driver, established from the module name in _init.
123  */
124 static	char *sd_label			= NULL;
125 
126 /*
127  * Driver name is unfortunately prefixed on some driver.conf properties.
128  */
129 #if (defined(__fibre))
130 #define	sd_max_xfer_size		ssd_max_xfer_size
131 #define	sd_config_list			ssd_config_list
132 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
133 static	char *sd_config_list		= "ssd-config-list";
134 #else
135 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
136 static	char *sd_config_list		= "sd-config-list";
137 #endif
138 
139 /*
140  * Driver global variables
141  */
142 
143 #if (defined(__fibre))
144 /*
145  * These #defines are to avoid namespace collisions that occur because this
146  * code is currently used to compile two separate driver modules: sd and ssd.
147  * All global variables need to be treated this way (even if declared static)
148  * in order to allow the debugger to resolve the names properly.
149  * It is anticipated that in the near future the ssd module will be obsoleted,
150  * at which time this namespace issue should go away.
151  */
152 #define	sd_state			ssd_state
153 #define	sd_io_time			ssd_io_time
154 #define	sd_failfast_enable		ssd_failfast_enable
155 #define	sd_ua_retry_count		ssd_ua_retry_count
156 #define	sd_report_pfa			ssd_report_pfa
157 #define	sd_max_throttle			ssd_max_throttle
158 #define	sd_min_throttle			ssd_min_throttle
159 #define	sd_rot_delay			ssd_rot_delay
160 
161 #define	sd_retry_on_reservation_conflict	\
162 					ssd_retry_on_reservation_conflict
163 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
164 #define	sd_resv_conflict_name		ssd_resv_conflict_name
165 
166 #define	sd_component_mask		ssd_component_mask
167 #define	sd_level_mask			ssd_level_mask
168 #define	sd_debug_un			ssd_debug_un
169 #define	sd_error_level			ssd_error_level
170 
171 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
172 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
173 
174 #define	sd_tr				ssd_tr
175 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
176 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
177 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
178 #define	sd_check_media_time		ssd_check_media_time
179 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
180 #define	sd_label_mutex			ssd_label_mutex
181 #define	sd_detach_mutex			ssd_detach_mutex
182 #define	sd_log_buf			ssd_log_buf
183 #define	sd_log_mutex			ssd_log_mutex
184 
185 #define	sd_disk_table			ssd_disk_table
186 #define	sd_disk_table_size		ssd_disk_table_size
187 #define	sd_sense_mutex			ssd_sense_mutex
188 #define	sd_cdbtab			ssd_cdbtab
189 
190 #define	sd_cb_ops			ssd_cb_ops
191 #define	sd_ops				ssd_ops
192 #define	sd_additional_codes		ssd_additional_codes
193 #define	sd_tgops			ssd_tgops
194 
195 #define	sd_minor_data			ssd_minor_data
196 #define	sd_minor_data_efi		ssd_minor_data_efi
197 
198 #define	sd_tq				ssd_tq
199 #define	sd_wmr_tq			ssd_wmr_tq
200 #define	sd_taskq_name			ssd_taskq_name
201 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
202 #define	sd_taskq_minalloc		ssd_taskq_minalloc
203 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
204 
205 #define	sd_dump_format_string		ssd_dump_format_string
206 
207 #define	sd_iostart_chain		ssd_iostart_chain
208 #define	sd_iodone_chain			ssd_iodone_chain
209 
210 #define	sd_pm_idletime			ssd_pm_idletime
211 
212 #define	sd_force_pm_supported		ssd_force_pm_supported
213 
214 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
215 
216 #define	sd_ssc_init			ssd_ssc_init
217 #define	sd_ssc_send			ssd_ssc_send
218 #define	sd_ssc_fini			ssd_ssc_fini
219 #define	sd_ssc_assessment		ssd_ssc_assessment
220 #define	sd_ssc_post			ssd_ssc_post
221 #define	sd_ssc_print			ssd_ssc_print
222 #define	sd_ssc_ereport_post		ssd_ssc_ereport_post
223 #define	sd_ssc_set_info			ssd_ssc_set_info
224 #define	sd_ssc_extract_info		ssd_ssc_extract_info
225 
226 #endif
227 
228 #ifdef	SDDEBUG
229 int	sd_force_pm_supported		= 0;
230 #endif	/* SDDEBUG */
231 
232 void *sd_state				= NULL;
233 int sd_io_time				= SD_IO_TIME;
234 int sd_failfast_enable			= 1;
235 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
236 int sd_report_pfa			= 1;
237 int sd_max_throttle			= SD_MAX_THROTTLE;
238 int sd_min_throttle			= SD_MIN_THROTTLE;
239 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
240 int sd_qfull_throttle_enable		= TRUE;
241 
242 int sd_retry_on_reservation_conflict	= 1;
243 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
244 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
245 
246 static int sd_dtype_optical_bind	= -1;
247 
248 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
249 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
250 
251 /*
252  * Global data for debug logging. To enable debug printing, sd_component_mask
253  * and sd_level_mask should be set to the desired bit patterns as outlined in
254  * sddef.h.
255  */
256 uint_t	sd_component_mask		= 0x0;
257 uint_t	sd_level_mask			= 0x0;
258 struct	sd_lun *sd_debug_un		= NULL;
259 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
260 
261 /* Note: these may go away in the future... */
262 static uint32_t	sd_xbuf_active_limit	= 512;
263 static uint32_t sd_xbuf_reserve_limit	= 16;
264 
265 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
266 
267 /*
268  * Timer value used to reset the throttle after it has been reduced
269  * (typically in response to TRAN_BUSY or STATUS_QFULL)
270  */
271 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
272 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
273 
274 /*
275  * Interval value associated with the media change scsi watch.
276  */
277 static int sd_check_media_time		= 3000000;
278 
279 /*
280  * Wait value used for in progress operations during a DDI_SUSPEND
281  */
282 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
283 
284 /*
285  * sd_label_mutex protects a static buffer used in the disk label
286  * component of the driver
287  */
288 static kmutex_t sd_label_mutex;
289 
290 /*
291  * sd_detach_mutex protects un_layer_count, un_detach_count, and
292  * un_opens_in_progress in the sd_lun structure.
293  */
294 static kmutex_t sd_detach_mutex;
295 
296 _NOTE(MUTEX_PROTECTS_DATA(sd_detach_mutex,
297 	sd_lun::{un_layer_count un_detach_count un_opens_in_progress}))
298 
299 /*
300  * Global buffer and mutex for debug logging
301  */
302 static char	sd_log_buf[1024];
303 static kmutex_t	sd_log_mutex;
304 
305 /*
306  * Structs and globals for recording attached lun information.
307  * This maintains a chain. Each node in the chain represents a SCSI controller.
308  * The structure records the number of luns attached to each target connected
309  * with the controller.
310  * For parallel scsi device only.
311  */
312 struct sd_scsi_hba_tgt_lun {
313 	struct sd_scsi_hba_tgt_lun	*next;
314 	dev_info_t			*pdip;
315 	int				nlun[NTARGETS_WIDE];
316 };
317 
318 /*
319  * Flag to indicate the lun is attached or detached
320  */
321 #define	SD_SCSI_LUN_ATTACH	0
322 #define	SD_SCSI_LUN_DETACH	1
323 
324 static kmutex_t	sd_scsi_target_lun_mutex;
325 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
326 
327 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
328     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
329 
330 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
331     sd_scsi_target_lun_head))
332 
333 /*
334  * "Smart" Probe Caching structs, globals, #defines, etc.
335  * For parallel scsi and non-self-identify device only.
336  */
337 
338 /*
339  * The following resources and routines are implemented to support
340  * "smart" probing, which caches the scsi_probe() results in an array,
341  * in order to help avoid long probe times.
342  */
343 struct sd_scsi_probe_cache {
344 	struct	sd_scsi_probe_cache	*next;
345 	dev_info_t	*pdip;
346 	int		cache[NTARGETS_WIDE];
347 };
348 
349 static kmutex_t	sd_scsi_probe_cache_mutex;
350 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
351 
352 /*
353  * Really we only need protection on the head of the linked list, but
354  * better safe than sorry.
355  */
356 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
357     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
358 
359 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
360     sd_scsi_probe_cache_head))
361 
362 /*
363  * Power attribute table
364  */
365 static sd_power_attr_ss sd_pwr_ss = {
366 	{ "NAME=spindle-motor", "0=off", "1=on", NULL },
367 	{0, 100},
368 	{30, 0},
369 	{20000, 0}
370 };
371 
372 static sd_power_attr_pc sd_pwr_pc = {
373 	{ "NAME=spindle-motor", "0=stopped", "1=standby", "2=idle",
374 		"3=active", NULL },
375 	{0, 0, 0, 100},
376 	{90, 90, 20, 0},
377 	{15000, 15000, 1000, 0}
378 };
379 
380 /*
381  * Power level to power condition
382  */
383 static int sd_pl2pc[] = {
384 	SD_TARGET_START_VALID,
385 	SD_TARGET_STANDBY,
386 	SD_TARGET_IDLE,
387 	SD_TARGET_ACTIVE
388 };
389 
390 /*
391  * Vendor specific data name property declarations
392  */
393 
394 #if defined(__fibre) || defined(__i386) ||defined(__amd64)
395 
396 static sd_tunables seagate_properties = {
397 	SEAGATE_THROTTLE_VALUE,
398 	0,
399 	0,
400 	0,
401 	0,
402 	0,
403 	0,
404 	0,
405 	0
406 };
407 
408 
409 static sd_tunables fujitsu_properties = {
410 	FUJITSU_THROTTLE_VALUE,
411 	0,
412 	0,
413 	0,
414 	0,
415 	0,
416 	0,
417 	0,
418 	0
419 };
420 
421 static sd_tunables ibm_properties = {
422 	IBM_THROTTLE_VALUE,
423 	0,
424 	0,
425 	0,
426 	0,
427 	0,
428 	0,
429 	0,
430 	0
431 };
432 
433 static sd_tunables purple_properties = {
434 	PURPLE_THROTTLE_VALUE,
435 	0,
436 	0,
437 	PURPLE_BUSY_RETRIES,
438 	PURPLE_RESET_RETRY_COUNT,
439 	PURPLE_RESERVE_RELEASE_TIME,
440 	0,
441 	0,
442 	0
443 };
444 
445 static sd_tunables sve_properties = {
446 	SVE_THROTTLE_VALUE,
447 	0,
448 	0,
449 	SVE_BUSY_RETRIES,
450 	SVE_RESET_RETRY_COUNT,
451 	SVE_RESERVE_RELEASE_TIME,
452 	SVE_MIN_THROTTLE_VALUE,
453 	SVE_DISKSORT_DISABLED_FLAG,
454 	0
455 };
456 
457 static sd_tunables maserati_properties = {
458 	0,
459 	0,
460 	0,
461 	0,
462 	0,
463 	0,
464 	0,
465 	MASERATI_DISKSORT_DISABLED_FLAG,
466 	MASERATI_LUN_RESET_ENABLED_FLAG
467 };
468 
469 static sd_tunables pirus_properties = {
470 	PIRUS_THROTTLE_VALUE,
471 	0,
472 	PIRUS_NRR_COUNT,
473 	PIRUS_BUSY_RETRIES,
474 	PIRUS_RESET_RETRY_COUNT,
475 	0,
476 	PIRUS_MIN_THROTTLE_VALUE,
477 	PIRUS_DISKSORT_DISABLED_FLAG,
478 	PIRUS_LUN_RESET_ENABLED_FLAG
479 };
480 
481 #endif
482 
483 #if (defined(__sparc) && !defined(__fibre)) || \
484 	(defined(__i386) || defined(__amd64))
485 
486 
487 static sd_tunables elite_properties = {
488 	ELITE_THROTTLE_VALUE,
489 	0,
490 	0,
491 	0,
492 	0,
493 	0,
494 	0,
495 	0,
496 	0
497 };
498 
499 static sd_tunables st31200n_properties = {
500 	ST31200N_THROTTLE_VALUE,
501 	0,
502 	0,
503 	0,
504 	0,
505 	0,
506 	0,
507 	0,
508 	0
509 };
510 
511 #endif /* Fibre or not */
512 
513 static sd_tunables lsi_properties_scsi = {
514 	LSI_THROTTLE_VALUE,
515 	0,
516 	LSI_NOTREADY_RETRIES,
517 	0,
518 	0,
519 	0,
520 	0,
521 	0,
522 	0
523 };
524 
525 static sd_tunables symbios_properties = {
526 	SYMBIOS_THROTTLE_VALUE,
527 	0,
528 	SYMBIOS_NOTREADY_RETRIES,
529 	0,
530 	0,
531 	0,
532 	0,
533 	0,
534 	0
535 };
536 
537 static sd_tunables lsi_properties = {
538 	0,
539 	0,
540 	LSI_NOTREADY_RETRIES,
541 	0,
542 	0,
543 	0,
544 	0,
545 	0,
546 	0
547 };
548 
549 static sd_tunables lsi_oem_properties = {
550 	0,
551 	0,
552 	LSI_OEM_NOTREADY_RETRIES,
553 	0,
554 	0,
555 	0,
556 	0,
557 	0,
558 	0,
559 	1
560 };
561 
562 
563 
564 #if (defined(SD_PROP_TST))
565 
566 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
567 #define	SD_TST_THROTTLE_VAL	16
568 #define	SD_TST_NOTREADY_VAL	12
569 #define	SD_TST_BUSY_VAL		60
570 #define	SD_TST_RST_RETRY_VAL	36
571 #define	SD_TST_RSV_REL_TIME	60
572 
573 static sd_tunables tst_properties = {
574 	SD_TST_THROTTLE_VAL,
575 	SD_TST_CTYPE_VAL,
576 	SD_TST_NOTREADY_VAL,
577 	SD_TST_BUSY_VAL,
578 	SD_TST_RST_RETRY_VAL,
579 	SD_TST_RSV_REL_TIME,
580 	0,
581 	0,
582 	0
583 };
584 #endif
585 
586 /* This is similar to the ANSI toupper implementation */
587 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
588 
589 /*
590  * Static Driver Configuration Table
591  *
592  * This is the table of disks which need throttle adjustment (or, perhaps
593  * something else as defined by the flags at a future time.)  device_id
594  * is a string consisting of concatenated vid (vendor), pid (product/model)
595  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
596  * the parts of the string are as defined by the sizes in the scsi_inquiry
597  * structure.  Device type is searched as far as the device_id string is
598  * defined.  Flags defines which values are to be set in the driver from the
599  * properties list.
600  *
601  * Entries below which begin and end with a "*" are a special case.
602  * These do not have a specific vendor, and the string which follows
603  * can appear anywhere in the 16 byte PID portion of the inquiry data.
604  *
605  * Entries below which begin and end with a " " (blank) are a special
606  * case. The comparison function will treat multiple consecutive blanks
607  * as equivalent to a single blank. For example, this causes a
608  * sd_disk_table entry of " NEC CDROM " to match a device's id string
609  * of  "NEC       CDROM".
610  *
611  * Note: The MD21 controller type has been obsoleted.
612  *	 ST318202F is a Legacy device
613  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
614  *	 made with an FC connection. The entries here are a legacy.
615  */
616 static sd_disk_config_t sd_disk_table[] = {
617 #if defined(__fibre) || defined(__i386) || defined(__amd64)
618 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
619 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
620 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
621 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
622 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
623 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
624 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
625 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
626 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
627 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
628 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
629 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
630 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
631 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
632 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
633 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
634 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
635 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
636 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
637 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
638 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
639 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
640 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
641 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
642 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
643 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
644 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
645 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
646 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
647 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
648 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
649 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
650 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
651 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
652 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
653 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
654 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
655 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
656 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
657 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
658 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
659 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
660 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
661 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
662 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
663 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
664 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
665 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
666 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
667 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
668 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
669 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
670 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
671 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
672 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
673 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
674 			SD_CONF_BSET_BSY_RETRY_COUNT|
675 			SD_CONF_BSET_RST_RETRIES|
676 			SD_CONF_BSET_RSV_REL_TIME,
677 		&purple_properties },
678 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
679 		SD_CONF_BSET_BSY_RETRY_COUNT|
680 		SD_CONF_BSET_RST_RETRIES|
681 		SD_CONF_BSET_RSV_REL_TIME|
682 		SD_CONF_BSET_MIN_THROTTLE|
683 		SD_CONF_BSET_DISKSORT_DISABLED,
684 		&sve_properties },
685 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
686 			SD_CONF_BSET_BSY_RETRY_COUNT|
687 			SD_CONF_BSET_RST_RETRIES|
688 			SD_CONF_BSET_RSV_REL_TIME,
689 		&purple_properties },
690 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
691 		SD_CONF_BSET_LUN_RESET_ENABLED,
692 		&maserati_properties },
693 	{ "SUN     SE6920", 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     SE6940", 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     StorageTek 6920", SD_CONF_BSET_THROTTLE |
710 		SD_CONF_BSET_NRR_COUNT|
711 		SD_CONF_BSET_BSY_RETRY_COUNT|
712 		SD_CONF_BSET_RST_RETRIES|
713 		SD_CONF_BSET_MIN_THROTTLE|
714 		SD_CONF_BSET_DISKSORT_DISABLED|
715 		SD_CONF_BSET_LUN_RESET_ENABLED,
716 		&pirus_properties },
717 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
718 		SD_CONF_BSET_NRR_COUNT|
719 		SD_CONF_BSET_BSY_RETRY_COUNT|
720 		SD_CONF_BSET_RST_RETRIES|
721 		SD_CONF_BSET_MIN_THROTTLE|
722 		SD_CONF_BSET_DISKSORT_DISABLED|
723 		SD_CONF_BSET_LUN_RESET_ENABLED,
724 		&pirus_properties },
725 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
726 		SD_CONF_BSET_NRR_COUNT|
727 		SD_CONF_BSET_BSY_RETRY_COUNT|
728 		SD_CONF_BSET_RST_RETRIES|
729 		SD_CONF_BSET_MIN_THROTTLE|
730 		SD_CONF_BSET_DISKSORT_DISABLED|
731 		SD_CONF_BSET_LUN_RESET_ENABLED,
732 		&pirus_properties },
733 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
734 		SD_CONF_BSET_NRR_COUNT|
735 		SD_CONF_BSET_BSY_RETRY_COUNT|
736 		SD_CONF_BSET_RST_RETRIES|
737 		SD_CONF_BSET_MIN_THROTTLE|
738 		SD_CONF_BSET_DISKSORT_DISABLED|
739 		SD_CONF_BSET_LUN_RESET_ENABLED,
740 		&pirus_properties },
741 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
742 	{ "SUN     SUN_6180", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
743 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
744 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
745 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
746 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
747 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
748 #endif /* fibre or NON-sparc platforms */
749 #if ((defined(__sparc) && !defined(__fibre)) ||\
750 	(defined(__i386) || defined(__amd64)))
751 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
752 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
753 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
754 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
755 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
756 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
757 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
758 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
759 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
760 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
761 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
762 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
763 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
764 	    &symbios_properties },
765 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
766 	    &lsi_properties_scsi },
767 #if defined(__i386) || defined(__amd64)
768 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
769 				    | SD_CONF_BSET_READSUB_BCD
770 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
771 				    | SD_CONF_BSET_NO_READ_HEADER
772 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
773 
774 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
775 				    | SD_CONF_BSET_READSUB_BCD
776 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
777 				    | SD_CONF_BSET_NO_READ_HEADER
778 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
779 #endif /* __i386 || __amd64 */
780 #endif /* sparc NON-fibre or NON-sparc platforms */
781 
782 #if (defined(SD_PROP_TST))
783 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
784 				| SD_CONF_BSET_CTYPE
785 				| SD_CONF_BSET_NRR_COUNT
786 				| SD_CONF_BSET_FAB_DEVID
787 				| SD_CONF_BSET_NOCACHE
788 				| SD_CONF_BSET_BSY_RETRY_COUNT
789 				| SD_CONF_BSET_PLAYMSF_BCD
790 				| SD_CONF_BSET_READSUB_BCD
791 				| SD_CONF_BSET_READ_TOC_TRK_BCD
792 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
793 				| SD_CONF_BSET_NO_READ_HEADER
794 				| SD_CONF_BSET_READ_CD_XD4
795 				| SD_CONF_BSET_RST_RETRIES
796 				| SD_CONF_BSET_RSV_REL_TIME
797 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
798 #endif
799 };
800 
801 static const int sd_disk_table_size =
802 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
803 
804 /*
805  * Emulation mode disk drive VID/PID table
806  */
807 static char sd_flash_dev_table[][25] = {
808 	"ATA     MARVELL SD88SA02",
809 	"MARVELL SD88SA02",
810 	"TOSHIBA THNSNV05",
811 };
812 
813 static const int sd_flash_dev_table_size =
814 	sizeof (sd_flash_dev_table) / sizeof (sd_flash_dev_table[0]);
815 
816 #define	SD_INTERCONNECT_PARALLEL	0
817 #define	SD_INTERCONNECT_FABRIC		1
818 #define	SD_INTERCONNECT_FIBRE		2
819 #define	SD_INTERCONNECT_SSA		3
820 #define	SD_INTERCONNECT_SATA		4
821 #define	SD_INTERCONNECT_SAS		5
822 
823 #define	SD_IS_PARALLEL_SCSI(un)		\
824 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
825 #define	SD_IS_SERIAL(un)		\
826 	(((un)->un_interconnect_type == SD_INTERCONNECT_SATA) ||\
827 	((un)->un_interconnect_type == SD_INTERCONNECT_SAS))
828 
829 /*
830  * Definitions used by device id registration routines
831  */
832 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
833 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
834 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
835 
836 static kmutex_t sd_sense_mutex = {0};
837 
838 /*
839  * Macros for updates of the driver state
840  */
841 #define	New_state(un, s)        \
842 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
843 #define	Restore_state(un)	\
844 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
845 
846 static struct sd_cdbinfo sd_cdbtab[] = {
847 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
848 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
849 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
850 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
851 };
852 
853 /*
854  * Specifies the number of seconds that must have elapsed since the last
855  * cmd. has completed for a device to be declared idle to the PM framework.
856  */
857 static int sd_pm_idletime = 1;
858 
859 /*
860  * Internal function prototypes
861  */
862 
863 #if (defined(__fibre))
864 /*
865  * These #defines are to avoid namespace collisions that occur because this
866  * code is currently used to compile two separate driver modules: sd and ssd.
867  * All function names need to be treated this way (even if declared static)
868  * in order to allow the debugger to resolve the names properly.
869  * It is anticipated that in the near future the ssd module will be obsoleted,
870  * at which time this ugliness should go away.
871  */
872 #define	sd_log_trace			ssd_log_trace
873 #define	sd_log_info			ssd_log_info
874 #define	sd_log_err			ssd_log_err
875 #define	sdprobe				ssdprobe
876 #define	sdinfo				ssdinfo
877 #define	sd_prop_op			ssd_prop_op
878 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
879 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
880 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
881 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
882 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
883 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
884 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
885 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
886 #define	sd_spin_up_unit			ssd_spin_up_unit
887 #define	sd_enable_descr_sense		ssd_enable_descr_sense
888 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
889 #define	sd_set_mmc_caps			ssd_set_mmc_caps
890 #define	sd_read_unit_properties		ssd_read_unit_properties
891 #define	sd_process_sdconf_file		ssd_process_sdconf_file
892 #define	sd_process_sdconf_table		ssd_process_sdconf_table
893 #define	sd_sdconf_id_match		ssd_sdconf_id_match
894 #define	sd_blank_cmp			ssd_blank_cmp
895 #define	sd_chk_vers1_data		ssd_chk_vers1_data
896 #define	sd_set_vers1_properties		ssd_set_vers1_properties
897 #define	sd_check_solid_state		ssd_check_solid_state
898 #define	sd_check_emulation_mode		ssd_check_emulation_mode
899 
900 #define	sd_get_physical_geometry	ssd_get_physical_geometry
901 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
902 #define	sd_update_block_info		ssd_update_block_info
903 #define	sd_register_devid		ssd_register_devid
904 #define	sd_get_devid			ssd_get_devid
905 #define	sd_create_devid			ssd_create_devid
906 #define	sd_write_deviceid		ssd_write_deviceid
907 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
908 #define	sd_setup_pm			ssd_setup_pm
909 #define	sd_create_pm_components		ssd_create_pm_components
910 #define	sd_ddi_suspend			ssd_ddi_suspend
911 #define	sd_ddi_resume			ssd_ddi_resume
912 #define	sd_pm_state_change		ssd_pm_state_change
913 #define	sdpower				ssdpower
914 #define	sdattach			ssdattach
915 #define	sddetach			ssddetach
916 #define	sd_unit_attach			ssd_unit_attach
917 #define	sd_unit_detach			ssd_unit_detach
918 #define	sd_set_unit_attributes		ssd_set_unit_attributes
919 #define	sd_create_errstats		ssd_create_errstats
920 #define	sd_set_errstats			ssd_set_errstats
921 #define	sd_set_pstats			ssd_set_pstats
922 #define	sddump				ssddump
923 #define	sd_scsi_poll			ssd_scsi_poll
924 #define	sd_send_polled_RQS		ssd_send_polled_RQS
925 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
926 #define	sd_init_event_callbacks		ssd_init_event_callbacks
927 #define	sd_event_callback		ssd_event_callback
928 #define	sd_cache_control		ssd_cache_control
929 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
930 #define	sd_get_nv_sup			ssd_get_nv_sup
931 #define	sd_make_device			ssd_make_device
932 #define	sdopen				ssdopen
933 #define	sdclose				ssdclose
934 #define	sd_ready_and_valid		ssd_ready_and_valid
935 #define	sdmin				ssdmin
936 #define	sdread				ssdread
937 #define	sdwrite				ssdwrite
938 #define	sdaread				ssdaread
939 #define	sdawrite			ssdawrite
940 #define	sdstrategy			ssdstrategy
941 #define	sdioctl				ssdioctl
942 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
943 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
944 #define	sd_checksum_iostart		ssd_checksum_iostart
945 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
946 #define	sd_pm_iostart			ssd_pm_iostart
947 #define	sd_core_iostart			ssd_core_iostart
948 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
949 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
950 #define	sd_checksum_iodone		ssd_checksum_iodone
951 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
952 #define	sd_pm_iodone			ssd_pm_iodone
953 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
954 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
955 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
956 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
957 #define	sd_buf_iodone			ssd_buf_iodone
958 #define	sd_uscsi_strategy		ssd_uscsi_strategy
959 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
960 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
961 #define	sd_uscsi_iodone			ssd_uscsi_iodone
962 #define	sd_xbuf_strategy		ssd_xbuf_strategy
963 #define	sd_xbuf_init			ssd_xbuf_init
964 #define	sd_pm_entry			ssd_pm_entry
965 #define	sd_pm_exit			ssd_pm_exit
966 
967 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
968 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
969 
970 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
971 #define	sdintr				ssdintr
972 #define	sd_start_cmds			ssd_start_cmds
973 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
974 #define	sd_bioclone_alloc		ssd_bioclone_alloc
975 #define	sd_bioclone_free		ssd_bioclone_free
976 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
977 #define	sd_shadow_buf_free		ssd_shadow_buf_free
978 #define	sd_print_transport_rejected_message	\
979 					ssd_print_transport_rejected_message
980 #define	sd_retry_command		ssd_retry_command
981 #define	sd_set_retry_bp			ssd_set_retry_bp
982 #define	sd_send_request_sense_command	ssd_send_request_sense_command
983 #define	sd_start_retry_command		ssd_start_retry_command
984 #define	sd_start_direct_priority_command	\
985 					ssd_start_direct_priority_command
986 #define	sd_return_failed_command	ssd_return_failed_command
987 #define	sd_return_failed_command_no_restart	\
988 					ssd_return_failed_command_no_restart
989 #define	sd_return_command		ssd_return_command
990 #define	sd_sync_with_callback		ssd_sync_with_callback
991 #define	sdrunout			ssdrunout
992 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
993 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
994 #define	sd_reduce_throttle		ssd_reduce_throttle
995 #define	sd_restore_throttle		ssd_restore_throttle
996 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
997 #define	sd_init_cdb_limits		ssd_init_cdb_limits
998 #define	sd_pkt_status_good		ssd_pkt_status_good
999 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
1000 #define	sd_pkt_status_busy		ssd_pkt_status_busy
1001 #define	sd_pkt_status_reservation_conflict	\
1002 					ssd_pkt_status_reservation_conflict
1003 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
1004 #define	sd_handle_request_sense		ssd_handle_request_sense
1005 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
1006 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
1007 #define	sd_validate_sense_data		ssd_validate_sense_data
1008 #define	sd_decode_sense			ssd_decode_sense
1009 #define	sd_print_sense_msg		ssd_print_sense_msg
1010 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
1011 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
1012 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
1013 #define	sd_sense_key_medium_or_hardware_error	\
1014 					ssd_sense_key_medium_or_hardware_error
1015 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
1016 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
1017 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
1018 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
1019 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
1020 #define	sd_sense_key_default		ssd_sense_key_default
1021 #define	sd_print_retry_msg		ssd_print_retry_msg
1022 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
1023 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
1024 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
1025 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
1026 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
1027 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
1028 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
1029 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
1030 #define	sd_pkt_reason_default		ssd_pkt_reason_default
1031 #define	sd_reset_target			ssd_reset_target
1032 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
1033 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
1034 #define	sd_taskq_create			ssd_taskq_create
1035 #define	sd_taskq_delete			ssd_taskq_delete
1036 #define	sd_target_change_task		ssd_target_change_task
1037 #define	sd_log_dev_status_event		ssd_log_dev_status_event
1038 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
1039 #define	sd_log_eject_request_event	ssd_log_eject_request_event
1040 #define	sd_media_change_task		ssd_media_change_task
1041 #define	sd_handle_mchange		ssd_handle_mchange
1042 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
1043 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
1044 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
1045 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
1046 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
1047 					sd_send_scsi_feature_GET_CONFIGURATION
1048 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
1049 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
1050 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
1051 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
1052 					ssd_send_scsi_PERSISTENT_RESERVE_IN
1053 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
1054 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
1055 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
1056 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
1057 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1058 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1059 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1060 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1061 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1062 #define	sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION	\
1063 				ssd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
1064 #define	sd_gesn_media_data_valid	ssd_gesn_media_data_valid
1065 #define	sd_alloc_rqs			ssd_alloc_rqs
1066 #define	sd_free_rqs			ssd_free_rqs
1067 #define	sd_dump_memory			ssd_dump_memory
1068 #define	sd_get_media_info_com		ssd_get_media_info_com
1069 #define	sd_get_media_info		ssd_get_media_info
1070 #define	sd_get_media_info_ext		ssd_get_media_info_ext
1071 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1072 #define	sd_nvpair_str_decode		ssd_nvpair_str_decode
1073 #define	sd_strtok_r			ssd_strtok_r
1074 #define	sd_set_properties		ssd_set_properties
1075 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1076 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1077 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1078 #define	sd_check_mhd			ssd_check_mhd
1079 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1080 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1081 #define	sd_sname			ssd_sname
1082 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1083 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1084 #define	sd_take_ownership		ssd_take_ownership
1085 #define	sd_reserve_release		ssd_reserve_release
1086 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1087 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1088 #define	sd_persistent_reservation_in_read_keys	\
1089 					ssd_persistent_reservation_in_read_keys
1090 #define	sd_persistent_reservation_in_read_resv	\
1091 					ssd_persistent_reservation_in_read_resv
1092 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1093 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1094 #define	sd_mhdioc_release		ssd_mhdioc_release
1095 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1096 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1097 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1098 #define	sr_change_blkmode		ssr_change_blkmode
1099 #define	sr_change_speed			ssr_change_speed
1100 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1101 #define	sr_pause_resume			ssr_pause_resume
1102 #define	sr_play_msf			ssr_play_msf
1103 #define	sr_play_trkind			ssr_play_trkind
1104 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1105 #define	sr_read_subchannel		ssr_read_subchannel
1106 #define	sr_read_tocentry		ssr_read_tocentry
1107 #define	sr_read_tochdr			ssr_read_tochdr
1108 #define	sr_read_cdda			ssr_read_cdda
1109 #define	sr_read_cdxa			ssr_read_cdxa
1110 #define	sr_read_mode1			ssr_read_mode1
1111 #define	sr_read_mode2			ssr_read_mode2
1112 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1113 #define	sr_sector_mode			ssr_sector_mode
1114 #define	sr_eject			ssr_eject
1115 #define	sr_ejected			ssr_ejected
1116 #define	sr_check_wp			ssr_check_wp
1117 #define	sd_watch_request_submit		ssd_watch_request_submit
1118 #define	sd_check_media			ssd_check_media
1119 #define	sd_media_watch_cb		ssd_media_watch_cb
1120 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1121 #define	sr_volume_ctrl			ssr_volume_ctrl
1122 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1123 #define	sd_log_page_supported		ssd_log_page_supported
1124 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1125 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1126 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1127 #define	sd_range_lock			ssd_range_lock
1128 #define	sd_get_range			ssd_get_range
1129 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1130 #define	sd_range_unlock			ssd_range_unlock
1131 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1132 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1133 
1134 #define	sd_iostart_chain		ssd_iostart_chain
1135 #define	sd_iodone_chain			ssd_iodone_chain
1136 #define	sd_initpkt_map			ssd_initpkt_map
1137 #define	sd_destroypkt_map		ssd_destroypkt_map
1138 #define	sd_chain_type_map		ssd_chain_type_map
1139 #define	sd_chain_index_map		ssd_chain_index_map
1140 
1141 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1142 #define	sd_failfast_flushq		ssd_failfast_flushq
1143 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1144 
1145 #define	sd_is_lsi			ssd_is_lsi
1146 #define	sd_tg_rdwr			ssd_tg_rdwr
1147 #define	sd_tg_getinfo			ssd_tg_getinfo
1148 #define	sd_rmw_msg_print_handler	ssd_rmw_msg_print_handler
1149 
1150 #endif	/* #if (defined(__fibre)) */
1151 
1152 
1153 int _init(void);
1154 int _fini(void);
1155 int _info(struct modinfo *modinfop);
1156 
1157 /*PRINTFLIKE3*/
1158 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1159 /*PRINTFLIKE3*/
1160 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1161 /*PRINTFLIKE3*/
1162 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1163 
1164 static int sdprobe(dev_info_t *devi);
1165 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1166     void **result);
1167 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1168     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1169 
1170 /*
1171  * Smart probe for parallel scsi
1172  */
1173 static void sd_scsi_probe_cache_init(void);
1174 static void sd_scsi_probe_cache_fini(void);
1175 static void sd_scsi_clear_probe_cache(void);
1176 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1177 
1178 /*
1179  * Attached luns on target for parallel scsi
1180  */
1181 static void sd_scsi_target_lun_init(void);
1182 static void sd_scsi_target_lun_fini(void);
1183 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1184 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1185 
1186 static int	sd_spin_up_unit(sd_ssc_t *ssc);
1187 
1188 /*
1189  * Using sd_ssc_init to establish sd_ssc_t struct
1190  * Using sd_ssc_send to send uscsi internal command
1191  * Using sd_ssc_fini to free sd_ssc_t struct
1192  */
1193 static sd_ssc_t *sd_ssc_init(struct sd_lun *un);
1194 static int sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd,
1195     int flag, enum uio_seg dataspace, int path_flag);
1196 static void sd_ssc_fini(sd_ssc_t *ssc);
1197 
1198 /*
1199  * Using sd_ssc_assessment to set correct type-of-assessment
1200  * Using sd_ssc_post to post ereport & system log
1201  *       sd_ssc_post will call sd_ssc_print to print system log
1202  *       sd_ssc_post will call sd_ssd_ereport_post to post ereport
1203  */
1204 static void sd_ssc_assessment(sd_ssc_t *ssc,
1205     enum sd_type_assessment tp_assess);
1206 
1207 static void sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess);
1208 static void sd_ssc_print(sd_ssc_t *ssc, int sd_severity);
1209 static void sd_ssc_ereport_post(sd_ssc_t *ssc,
1210     enum sd_driver_assessment drv_assess);
1211 
1212 /*
1213  * Using sd_ssc_set_info to mark an un-decodable-data error.
1214  * Using sd_ssc_extract_info to transfer information from internal
1215  *       data structures to sd_ssc_t.
1216  */
1217 static void sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp,
1218     const char *fmt, ...);
1219 static void sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un,
1220     struct scsi_pkt *pktp, struct buf *bp, struct sd_xbuf *xp);
1221 
1222 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1223     enum uio_seg dataspace, int path_flag);
1224 
1225 #ifdef _LP64
1226 static void	sd_enable_descr_sense(sd_ssc_t *ssc);
1227 static void	sd_reenable_dsense_task(void *arg);
1228 #endif /* _LP64 */
1229 
1230 static void	sd_set_mmc_caps(sd_ssc_t *ssc);
1231 
1232 static void sd_read_unit_properties(struct sd_lun *un);
1233 static int  sd_process_sdconf_file(struct sd_lun *un);
1234 static void sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str);
1235 static char *sd_strtok_r(char *string, const char *sepset, char **lasts);
1236 static void sd_set_properties(struct sd_lun *un, char *name, char *value);
1237 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1238     int *data_list, sd_tunables *values);
1239 static void sd_process_sdconf_table(struct sd_lun *un);
1240 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1241 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1242 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1243 	int list_len, char *dataname_ptr);
1244 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1245     sd_tunables *prop_list);
1246 
1247 static void sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi,
1248     int reservation_flag);
1249 static int  sd_get_devid(sd_ssc_t *ssc);
1250 static ddi_devid_t sd_create_devid(sd_ssc_t *ssc);
1251 static int  sd_write_deviceid(sd_ssc_t *ssc);
1252 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1253 static int  sd_check_vpd_page_support(sd_ssc_t *ssc);
1254 
1255 static void sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi);
1256 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1257 
1258 static int  sd_ddi_suspend(dev_info_t *devi);
1259 static int  sd_ddi_resume(dev_info_t *devi);
1260 static int  sd_pm_state_change(struct sd_lun *un, int level, int flag);
1261 static int  sdpower(dev_info_t *devi, int component, int level);
1262 
1263 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1264 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1265 static int  sd_unit_attach(dev_info_t *devi);
1266 static int  sd_unit_detach(dev_info_t *devi);
1267 
1268 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1269 static void sd_create_errstats(struct sd_lun *un, int instance);
1270 static void sd_set_errstats(struct sd_lun *un);
1271 static void sd_set_pstats(struct sd_lun *un);
1272 
1273 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1274 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1275 static int  sd_send_polled_RQS(struct sd_lun *un);
1276 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1277 
1278 #if (defined(__fibre))
1279 /*
1280  * Event callbacks (photon)
1281  */
1282 static void sd_init_event_callbacks(struct sd_lun *un);
1283 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1284 #endif
1285 
1286 /*
1287  * Defines for sd_cache_control
1288  */
1289 
1290 #define	SD_CACHE_ENABLE		1
1291 #define	SD_CACHE_DISABLE	0
1292 #define	SD_CACHE_NOCHANGE	-1
1293 
1294 static int   sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag);
1295 static int   sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled);
1296 static void  sd_get_nv_sup(sd_ssc_t *ssc);
1297 static dev_t sd_make_device(dev_info_t *devi);
1298 static void  sd_check_solid_state(sd_ssc_t *ssc);
1299 static void  sd_check_emulation_mode(sd_ssc_t *ssc);
1300 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1301 	uint64_t capacity);
1302 
1303 /*
1304  * Driver entry point functions.
1305  */
1306 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1307 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1308 static int  sd_ready_and_valid(sd_ssc_t *ssc, int part);
1309 
1310 static void sdmin(struct buf *bp);
1311 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1312 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1313 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1314 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1315 
1316 static int sdstrategy(struct buf *bp);
1317 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1318 
1319 /*
1320  * Function prototypes for layering functions in the iostart chain.
1321  */
1322 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1323 	struct buf *bp);
1324 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1325 	struct buf *bp);
1326 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1327 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1328 	struct buf *bp);
1329 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1330 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1331 
1332 /*
1333  * Function prototypes for layering functions in the iodone chain.
1334  */
1335 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1336 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1337 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1338 	struct buf *bp);
1339 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1340 	struct buf *bp);
1341 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1342 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1343 	struct buf *bp);
1344 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1345 
1346 /*
1347  * Prototypes for functions to support buf(9S) based IO.
1348  */
1349 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1350 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1351 static void sd_destroypkt_for_buf(struct buf *);
1352 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1353 	struct buf *bp, int flags,
1354 	int (*callback)(caddr_t), caddr_t callback_arg,
1355 	diskaddr_t lba, uint32_t blockcount);
1356 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1357 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1358 
1359 /*
1360  * Prototypes for functions to support USCSI IO.
1361  */
1362 static int sd_uscsi_strategy(struct buf *bp);
1363 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1364 static void sd_destroypkt_for_uscsi(struct buf *);
1365 
1366 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1367 	uchar_t chain_type, void *pktinfop);
1368 
1369 static int  sd_pm_entry(struct sd_lun *un);
1370 static void sd_pm_exit(struct sd_lun *un);
1371 
1372 static void sd_pm_idletimeout_handler(void *arg);
1373 
1374 /*
1375  * sd_core internal functions (used at the sd_core_io layer).
1376  */
1377 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1378 static void sdintr(struct scsi_pkt *pktp);
1379 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1380 
1381 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1382 	enum uio_seg dataspace, int path_flag);
1383 
1384 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1385 	daddr_t blkno, int (*func)(struct buf *));
1386 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1387 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1388 static void sd_bioclone_free(struct buf *bp);
1389 static void sd_shadow_buf_free(struct buf *bp);
1390 
1391 static void sd_print_transport_rejected_message(struct sd_lun *un,
1392 	struct sd_xbuf *xp, int code);
1393 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1394     void *arg, int code);
1395 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1396     void *arg, int code);
1397 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1398     void *arg, int code);
1399 
1400 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1401 	int retry_check_flag,
1402 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1403 		int c),
1404 	void *user_arg, int failure_code,  clock_t retry_delay,
1405 	void (*statp)(kstat_io_t *));
1406 
1407 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1408 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1409 
1410 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1411 	struct scsi_pkt *pktp);
1412 static void sd_start_retry_command(void *arg);
1413 static void sd_start_direct_priority_command(void *arg);
1414 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1415 	int errcode);
1416 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1417 	struct buf *bp, int errcode);
1418 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1419 static void sd_sync_with_callback(struct sd_lun *un);
1420 static int sdrunout(caddr_t arg);
1421 
1422 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1423 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1424 
1425 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1426 static void sd_restore_throttle(void *arg);
1427 
1428 static void sd_init_cdb_limits(struct sd_lun *un);
1429 
1430 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1431 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1432 
1433 /*
1434  * Error handling functions
1435  */
1436 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1437 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1438 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1439 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1440 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1441 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1442 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1443 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1444 
1445 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1446 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1447 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1448 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1449 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1450 	struct sd_xbuf *xp, size_t actual_len);
1451 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1452 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1453 
1454 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1455 	void *arg, int code);
1456 
1457 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1458 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1459 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1460 	uint8_t *sense_datap,
1461 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1462 static void sd_sense_key_not_ready(struct sd_lun *un,
1463 	uint8_t *sense_datap,
1464 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1465 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1466 	uint8_t *sense_datap,
1467 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1468 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1469 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1470 static void sd_sense_key_unit_attention(struct sd_lun *un,
1471 	uint8_t *sense_datap,
1472 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1473 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1474 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1475 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1476 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1477 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1478 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1479 static void sd_sense_key_default(struct sd_lun *un,
1480 	uint8_t *sense_datap,
1481 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1482 
1483 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1484 	void *arg, int flag);
1485 
1486 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1487 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1488 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1489 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1490 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1491 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1492 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1493 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1494 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1495 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1496 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1497 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1498 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1499 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1500 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1501 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1502 
1503 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1504 
1505 static void sd_start_stop_unit_callback(void *arg);
1506 static void sd_start_stop_unit_task(void *arg);
1507 
1508 static void sd_taskq_create(void);
1509 static void sd_taskq_delete(void);
1510 static void sd_target_change_task(void *arg);
1511 static void sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag);
1512 static void sd_log_lun_expansion_event(struct sd_lun *un, int km_flag);
1513 static void sd_log_eject_request_event(struct sd_lun *un, int km_flag);
1514 static void sd_media_change_task(void *arg);
1515 
1516 static int sd_handle_mchange(struct sd_lun *un);
1517 static int sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag);
1518 static int sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp,
1519 	uint32_t *lbap, int path_flag);
1520 static int sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
1521 	uint32_t *lbap, uint32_t *psp, int path_flag);
1522 static int sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag,
1523 	int flag, int path_flag);
1524 static int sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr,
1525 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1526 static int sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag);
1527 static int sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc,
1528 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1529 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc,
1530 	uchar_t usr_cmd, uchar_t *usr_bufp);
1531 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1532 	struct dk_callback *dkc);
1533 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1534 static int sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc,
1535 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1536 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1537 static int sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
1538 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1539 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1540 static int sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize,
1541 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1542 static int sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize,
1543 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1544 static int sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
1545 	size_t buflen, daddr_t start_block, int path_flag);
1546 #define	sd_send_scsi_READ(ssc, bufaddr, buflen, start_block, path_flag)	\
1547 	sd_send_scsi_RDWR(ssc, SCMD_READ, bufaddr, buflen, start_block, \
1548 	path_flag)
1549 #define	sd_send_scsi_WRITE(ssc, bufaddr, buflen, start_block, path_flag)\
1550 	sd_send_scsi_RDWR(ssc, SCMD_WRITE, bufaddr, buflen, start_block,\
1551 	path_flag)
1552 
1553 static int sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr,
1554 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1555 	uint16_t param_ptr, int path_flag);
1556 static int sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc,
1557 	uchar_t *bufaddr, size_t buflen, uchar_t class_req);
1558 static boolean_t sd_gesn_media_data_valid(uchar_t *data);
1559 
1560 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1561 static void sd_free_rqs(struct sd_lun *un);
1562 
1563 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1564 	uchar_t *data, int len, int fmt);
1565 static void sd_panic_for_res_conflict(struct sd_lun *un);
1566 
1567 /*
1568  * Disk Ioctl Function Prototypes
1569  */
1570 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1571 static int sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag);
1572 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1573 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1574 
1575 /*
1576  * Multi-host Ioctl Prototypes
1577  */
1578 static int sd_check_mhd(dev_t dev, int interval);
1579 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1580 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1581 static char *sd_sname(uchar_t status);
1582 static void sd_mhd_resvd_recover(void *arg);
1583 static void sd_resv_reclaim_thread();
1584 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1585 static int sd_reserve_release(dev_t dev, int cmd);
1586 static void sd_rmv_resv_reclaim_req(dev_t dev);
1587 static void sd_mhd_reset_notify_cb(caddr_t arg);
1588 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1589 	mhioc_inkeys_t *usrp, int flag);
1590 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1591 	mhioc_inresvs_t *usrp, int flag);
1592 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1593 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1594 static int sd_mhdioc_release(dev_t dev);
1595 static int sd_mhdioc_register_devid(dev_t dev);
1596 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1597 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1598 
1599 /*
1600  * SCSI removable prototypes
1601  */
1602 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1603 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1604 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1605 static int sr_pause_resume(dev_t dev, int mode);
1606 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1607 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1608 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1609 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1610 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1611 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1612 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1613 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1614 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1615 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1616 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1617 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1618 static int sr_eject(dev_t dev);
1619 static void sr_ejected(register struct sd_lun *un);
1620 static int sr_check_wp(dev_t dev);
1621 static opaque_t sd_watch_request_submit(struct sd_lun *un);
1622 static int sd_check_media(dev_t dev, enum dkio_state state);
1623 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1624 static void sd_delayed_cv_broadcast(void *arg);
1625 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1626 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1627 
1628 static int sd_log_page_supported(sd_ssc_t *ssc, int log_page);
1629 
1630 /*
1631  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1632  */
1633 static void sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag);
1634 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1635 static void sd_wm_cache_destructor(void *wm, void *un);
1636 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1637 	daddr_t endb, ushort_t typ);
1638 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1639 	daddr_t endb);
1640 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1641 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1642 static void sd_read_modify_write_task(void * arg);
1643 static int
1644 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1645 	struct buf **bpp);
1646 
1647 
1648 /*
1649  * Function prototypes for failfast support.
1650  */
1651 static void sd_failfast_flushq(struct sd_lun *un);
1652 static int sd_failfast_flushq_callback(struct buf *bp);
1653 
1654 /*
1655  * Function prototypes to check for lsi devices
1656  */
1657 static void sd_is_lsi(struct sd_lun *un);
1658 
1659 /*
1660  * Function prototypes for partial DMA support
1661  */
1662 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1663 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1664 
1665 
1666 /* Function prototypes for cmlb */
1667 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1668     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1669 
1670 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1671 
1672 /*
1673  * For printing RMW warning message timely
1674  */
1675 static void sd_rmw_msg_print_handler(void *arg);
1676 
1677 /*
1678  * Constants for failfast support:
1679  *
1680  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1681  * failfast processing being performed.
1682  *
1683  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1684  * failfast processing on all bufs with B_FAILFAST set.
1685  */
1686 
1687 #define	SD_FAILFAST_INACTIVE		0
1688 #define	SD_FAILFAST_ACTIVE		1
1689 
1690 /*
1691  * Bitmask to control behavior of buf(9S) flushes when a transition to
1692  * the failfast state occurs. Optional bits include:
1693  *
1694  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1695  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1696  * be flushed.
1697  *
1698  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1699  * driver, in addition to the regular wait queue. This includes the xbuf
1700  * queues. When clear, only the driver's wait queue will be flushed.
1701  */
1702 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1703 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1704 
1705 /*
1706  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1707  * to flush all queues within the driver.
1708  */
1709 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1710 
1711 
1712 /*
1713  * SD Testing Fault Injection
1714  */
1715 #ifdef SD_FAULT_INJECTION
1716 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1717 static void sd_faultinjection(struct scsi_pkt *pktp);
1718 static void sd_injection_log(char *buf, struct sd_lun *un);
1719 #endif
1720 
1721 /*
1722  * Device driver ops vector
1723  */
1724 static struct cb_ops sd_cb_ops = {
1725 	sdopen,			/* open */
1726 	sdclose,		/* close */
1727 	sdstrategy,		/* strategy */
1728 	nodev,			/* print */
1729 	sddump,			/* dump */
1730 	sdread,			/* read */
1731 	sdwrite,		/* write */
1732 	sdioctl,		/* ioctl */
1733 	nodev,			/* devmap */
1734 	nodev,			/* mmap */
1735 	nodev,			/* segmap */
1736 	nochpoll,		/* poll */
1737 	sd_prop_op,		/* cb_prop_op */
1738 	0,			/* streamtab  */
1739 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1740 	CB_REV,			/* cb_rev */
1741 	sdaread, 		/* async I/O read entry point */
1742 	sdawrite		/* async I/O write entry point */
1743 };
1744 
1745 struct dev_ops sd_ops = {
1746 	DEVO_REV,		/* devo_rev, */
1747 	0,			/* refcnt  */
1748 	sdinfo,			/* info */
1749 	nulldev,		/* identify */
1750 	sdprobe,		/* probe */
1751 	sdattach,		/* attach */
1752 	sddetach,		/* detach */
1753 	nodev,			/* reset */
1754 	&sd_cb_ops,		/* driver operations */
1755 	NULL,			/* bus operations */
1756 	sdpower,		/* power */
1757 	ddi_quiesce_not_needed,		/* quiesce */
1758 };
1759 
1760 /*
1761  * This is the loadable module wrapper.
1762  */
1763 #include <sys/modctl.h>
1764 
1765 #ifndef XPV_HVM_DRIVER
1766 static struct modldrv modldrv = {
1767 	&mod_driverops,		/* Type of module. This one is a driver */
1768 	SD_MODULE_NAME,		/* Module name. */
1769 	&sd_ops			/* driver ops */
1770 };
1771 
1772 static struct modlinkage modlinkage = {
1773 	MODREV_1, &modldrv, NULL
1774 };
1775 
1776 #else /* XPV_HVM_DRIVER */
1777 static struct modlmisc modlmisc = {
1778 	&mod_miscops,		/* Type of module. This one is a misc */
1779 	"HVM " SD_MODULE_NAME,		/* Module name. */
1780 };
1781 
1782 static struct modlinkage modlinkage = {
1783 	MODREV_1, &modlmisc, NULL
1784 };
1785 
1786 #endif /* XPV_HVM_DRIVER */
1787 
1788 static cmlb_tg_ops_t sd_tgops = {
1789 	TG_DK_OPS_VERSION_1,
1790 	sd_tg_rdwr,
1791 	sd_tg_getinfo
1792 };
1793 
1794 static struct scsi_asq_key_strings sd_additional_codes[] = {
1795 	0x81, 0, "Logical Unit is Reserved",
1796 	0x85, 0, "Audio Address Not Valid",
1797 	0xb6, 0, "Media Load Mechanism Failed",
1798 	0xB9, 0, "Audio Play Operation Aborted",
1799 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1800 	0x53, 2, "Medium removal prevented",
1801 	0x6f, 0, "Authentication failed during key exchange",
1802 	0x6f, 1, "Key not present",
1803 	0x6f, 2, "Key not established",
1804 	0x6f, 3, "Read without proper authentication",
1805 	0x6f, 4, "Mismatched region to this logical unit",
1806 	0x6f, 5, "Region reset count error",
1807 	0xffff, 0x0, NULL
1808 };
1809 
1810 
1811 /*
1812  * Struct for passing printing information for sense data messages
1813  */
1814 struct sd_sense_info {
1815 	int	ssi_severity;
1816 	int	ssi_pfa_flag;
1817 };
1818 
1819 /*
1820  * Table of function pointers for iostart-side routines. Separate "chains"
1821  * of layered function calls are formed by placing the function pointers
1822  * sequentially in the desired order. Functions are called according to an
1823  * incrementing table index ordering. The last function in each chain must
1824  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1825  * in the sd_iodone_chain[] array.
1826  *
1827  * Note: It may seem more natural to organize both the iostart and iodone
1828  * functions together, into an array of structures (or some similar
1829  * organization) with a common index, rather than two separate arrays which
1830  * must be maintained in synchronization. The purpose of this division is
1831  * to achieve improved performance: individual arrays allows for more
1832  * effective cache line utilization on certain platforms.
1833  */
1834 
1835 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1836 
1837 
1838 static sd_chain_t sd_iostart_chain[] = {
1839 
1840 	/* Chain for buf IO for disk drive targets (PM enabled) */
1841 	sd_mapblockaddr_iostart,	/* Index: 0 */
1842 	sd_pm_iostart,			/* Index: 1 */
1843 	sd_core_iostart,		/* Index: 2 */
1844 
1845 	/* Chain for buf IO for disk drive targets (PM disabled) */
1846 	sd_mapblockaddr_iostart,	/* Index: 3 */
1847 	sd_core_iostart,		/* Index: 4 */
1848 
1849 	/*
1850 	 * Chain for buf IO for removable-media or large sector size
1851 	 * disk drive targets with RMW needed (PM enabled)
1852 	 */
1853 	sd_mapblockaddr_iostart,	/* Index: 5 */
1854 	sd_mapblocksize_iostart,	/* Index: 6 */
1855 	sd_pm_iostart,			/* Index: 7 */
1856 	sd_core_iostart,		/* Index: 8 */
1857 
1858 	/*
1859 	 * Chain for buf IO for removable-media or large sector size
1860 	 * disk drive targets with RMW needed (PM disabled)
1861 	 */
1862 	sd_mapblockaddr_iostart,	/* Index: 9 */
1863 	sd_mapblocksize_iostart,	/* Index: 10 */
1864 	sd_core_iostart,		/* Index: 11 */
1865 
1866 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1867 	sd_mapblockaddr_iostart,	/* Index: 12 */
1868 	sd_checksum_iostart,		/* Index: 13 */
1869 	sd_pm_iostart,			/* Index: 14 */
1870 	sd_core_iostart,		/* Index: 15 */
1871 
1872 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1873 	sd_mapblockaddr_iostart,	/* Index: 16 */
1874 	sd_checksum_iostart,		/* Index: 17 */
1875 	sd_core_iostart,		/* Index: 18 */
1876 
1877 	/* Chain for USCSI commands (all targets) */
1878 	sd_pm_iostart,			/* Index: 19 */
1879 	sd_core_iostart,		/* Index: 20 */
1880 
1881 	/* Chain for checksumming USCSI commands (all targets) */
1882 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1883 	sd_pm_iostart,			/* Index: 22 */
1884 	sd_core_iostart,		/* Index: 23 */
1885 
1886 	/* Chain for "direct" USCSI commands (all targets) */
1887 	sd_core_iostart,		/* Index: 24 */
1888 
1889 	/* Chain for "direct priority" USCSI commands (all targets) */
1890 	sd_core_iostart,		/* Index: 25 */
1891 
1892 	/*
1893 	 * Chain for buf IO for large sector size disk drive targets
1894 	 * with RMW needed with checksumming (PM enabled)
1895 	 */
1896 	sd_mapblockaddr_iostart,	/* Index: 26 */
1897 	sd_mapblocksize_iostart,	/* Index: 27 */
1898 	sd_checksum_iostart,		/* Index: 28 */
1899 	sd_pm_iostart,			/* Index: 29 */
1900 	sd_core_iostart,		/* Index: 30 */
1901 
1902 	/*
1903 	 * Chain for buf IO for large sector size disk drive targets
1904 	 * with RMW needed with checksumming (PM disabled)
1905 	 */
1906 	sd_mapblockaddr_iostart,	/* Index: 31 */
1907 	sd_mapblocksize_iostart,	/* Index: 32 */
1908 	sd_checksum_iostart,		/* Index: 33 */
1909 	sd_core_iostart,		/* Index: 34 */
1910 
1911 };
1912 
1913 /*
1914  * Macros to locate the first function of each iostart chain in the
1915  * sd_iostart_chain[] array. These are located by the index in the array.
1916  */
1917 #define	SD_CHAIN_DISK_IOSTART			0
1918 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1919 #define	SD_CHAIN_MSS_DISK_IOSTART		5
1920 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1921 #define	SD_CHAIN_MSS_DISK_IOSTART_NO_PM		9
1922 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1923 #define	SD_CHAIN_CHKSUM_IOSTART			12
1924 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1925 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1926 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1927 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1928 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1929 #define	SD_CHAIN_MSS_CHKSUM_IOSTART		26
1930 #define	SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM	31
1931 
1932 
1933 /*
1934  * Table of function pointers for the iodone-side routines for the driver-
1935  * internal layering mechanism.  The calling sequence for iodone routines
1936  * uses a decrementing table index, so the last routine called in a chain
1937  * must be at the lowest array index location for that chain.  The last
1938  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1939  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1940  * of the functions in an iodone side chain must correspond to the ordering
1941  * of the iostart routines for that chain.  Note that there is no iodone
1942  * side routine that corresponds to sd_core_iostart(), so there is no
1943  * entry in the table for this.
1944  */
1945 
1946 static sd_chain_t sd_iodone_chain[] = {
1947 
1948 	/* Chain for buf IO for disk drive targets (PM enabled) */
1949 	sd_buf_iodone,			/* Index: 0 */
1950 	sd_mapblockaddr_iodone,		/* Index: 1 */
1951 	sd_pm_iodone,			/* Index: 2 */
1952 
1953 	/* Chain for buf IO for disk drive targets (PM disabled) */
1954 	sd_buf_iodone,			/* Index: 3 */
1955 	sd_mapblockaddr_iodone,		/* Index: 4 */
1956 
1957 	/*
1958 	 * Chain for buf IO for removable-media or large sector size
1959 	 * disk drive targets with RMW needed (PM enabled)
1960 	 */
1961 	sd_buf_iodone,			/* Index: 5 */
1962 	sd_mapblockaddr_iodone,		/* Index: 6 */
1963 	sd_mapblocksize_iodone,		/* Index: 7 */
1964 	sd_pm_iodone,			/* Index: 8 */
1965 
1966 	/*
1967 	 * Chain for buf IO for removable-media or large sector size
1968 	 * disk drive targets with RMW needed (PM disabled)
1969 	 */
1970 	sd_buf_iodone,			/* Index: 9 */
1971 	sd_mapblockaddr_iodone,		/* Index: 10 */
1972 	sd_mapblocksize_iodone,		/* Index: 11 */
1973 
1974 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1975 	sd_buf_iodone,			/* Index: 12 */
1976 	sd_mapblockaddr_iodone,		/* Index: 13 */
1977 	sd_checksum_iodone,		/* Index: 14 */
1978 	sd_pm_iodone,			/* Index: 15 */
1979 
1980 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1981 	sd_buf_iodone,			/* Index: 16 */
1982 	sd_mapblockaddr_iodone,		/* Index: 17 */
1983 	sd_checksum_iodone,		/* Index: 18 */
1984 
1985 	/* Chain for USCSI commands (non-checksum targets) */
1986 	sd_uscsi_iodone,		/* Index: 19 */
1987 	sd_pm_iodone,			/* Index: 20 */
1988 
1989 	/* Chain for USCSI commands (checksum targets) */
1990 	sd_uscsi_iodone,		/* Index: 21 */
1991 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1992 	sd_pm_iodone,			/* Index: 22 */
1993 
1994 	/* Chain for "direct" USCSI commands (all targets) */
1995 	sd_uscsi_iodone,		/* Index: 24 */
1996 
1997 	/* Chain for "direct priority" USCSI commands (all targets) */
1998 	sd_uscsi_iodone,		/* Index: 25 */
1999 
2000 	/*
2001 	 * Chain for buf IO for large sector size disk drive targets
2002 	 * with checksumming (PM enabled)
2003 	 */
2004 	sd_buf_iodone,			/* Index: 26 */
2005 	sd_mapblockaddr_iodone,		/* Index: 27 */
2006 	sd_mapblocksize_iodone,		/* Index: 28 */
2007 	sd_checksum_iodone,		/* Index: 29 */
2008 	sd_pm_iodone,			/* Index: 30 */
2009 
2010 	/*
2011 	 * Chain for buf IO for large sector size disk drive targets
2012 	 * with checksumming (PM disabled)
2013 	 */
2014 	sd_buf_iodone,			/* Index: 31 */
2015 	sd_mapblockaddr_iodone,		/* Index: 32 */
2016 	sd_mapblocksize_iodone,		/* Index: 33 */
2017 	sd_checksum_iodone,		/* Index: 34 */
2018 };
2019 
2020 
2021 /*
2022  * Macros to locate the "first" function in the sd_iodone_chain[] array for
2023  * each iodone-side chain. These are located by the array index, but as the
2024  * iodone side functions are called in a decrementing-index order, the
2025  * highest index number in each chain must be specified (as these correspond
2026  * to the first function in the iodone chain that will be called by the core
2027  * at IO completion time).
2028  */
2029 
2030 #define	SD_CHAIN_DISK_IODONE			2
2031 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
2032 #define	SD_CHAIN_RMMEDIA_IODONE			8
2033 #define	SD_CHAIN_MSS_DISK_IODONE		8
2034 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
2035 #define	SD_CHAIN_MSS_DISK_IODONE_NO_PM		11
2036 #define	SD_CHAIN_CHKSUM_IODONE			15
2037 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
2038 #define	SD_CHAIN_USCSI_CMD_IODONE		20
2039 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
2040 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
2041 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
2042 #define	SD_CHAIN_MSS_CHKSUM_IODONE		30
2043 #define	SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM	34
2044 
2045 
2046 
2047 /*
2048  * Array to map a layering chain index to the appropriate initpkt routine.
2049  * The redundant entries are present so that the index used for accessing
2050  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2051  * with this table as well.
2052  */
2053 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
2054 
2055 static sd_initpkt_t	sd_initpkt_map[] = {
2056 
2057 	/* Chain for buf IO for disk drive targets (PM enabled) */
2058 	sd_initpkt_for_buf,		/* Index: 0 */
2059 	sd_initpkt_for_buf,		/* Index: 1 */
2060 	sd_initpkt_for_buf,		/* Index: 2 */
2061 
2062 	/* Chain for buf IO for disk drive targets (PM disabled) */
2063 	sd_initpkt_for_buf,		/* Index: 3 */
2064 	sd_initpkt_for_buf,		/* Index: 4 */
2065 
2066 	/*
2067 	 * Chain for buf IO for removable-media or large sector size
2068 	 * disk drive targets (PM enabled)
2069 	 */
2070 	sd_initpkt_for_buf,		/* Index: 5 */
2071 	sd_initpkt_for_buf,		/* Index: 6 */
2072 	sd_initpkt_for_buf,		/* Index: 7 */
2073 	sd_initpkt_for_buf,		/* Index: 8 */
2074 
2075 	/*
2076 	 * Chain for buf IO for removable-media or large sector size
2077 	 * disk drive targets (PM disabled)
2078 	 */
2079 	sd_initpkt_for_buf,		/* Index: 9 */
2080 	sd_initpkt_for_buf,		/* Index: 10 */
2081 	sd_initpkt_for_buf,		/* Index: 11 */
2082 
2083 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2084 	sd_initpkt_for_buf,		/* Index: 12 */
2085 	sd_initpkt_for_buf,		/* Index: 13 */
2086 	sd_initpkt_for_buf,		/* Index: 14 */
2087 	sd_initpkt_for_buf,		/* Index: 15 */
2088 
2089 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2090 	sd_initpkt_for_buf,		/* Index: 16 */
2091 	sd_initpkt_for_buf,		/* Index: 17 */
2092 	sd_initpkt_for_buf,		/* Index: 18 */
2093 
2094 	/* Chain for USCSI commands (non-checksum targets) */
2095 	sd_initpkt_for_uscsi,		/* Index: 19 */
2096 	sd_initpkt_for_uscsi,		/* Index: 20 */
2097 
2098 	/* Chain for USCSI commands (checksum targets) */
2099 	sd_initpkt_for_uscsi,		/* Index: 21 */
2100 	sd_initpkt_for_uscsi,		/* Index: 22 */
2101 	sd_initpkt_for_uscsi,		/* Index: 22 */
2102 
2103 	/* Chain for "direct" USCSI commands (all targets) */
2104 	sd_initpkt_for_uscsi,		/* Index: 24 */
2105 
2106 	/* Chain for "direct priority" USCSI commands (all targets) */
2107 	sd_initpkt_for_uscsi,		/* Index: 25 */
2108 
2109 	/*
2110 	 * Chain for buf IO for large sector size disk drive targets
2111 	 * with checksumming (PM enabled)
2112 	 */
2113 	sd_initpkt_for_buf,		/* Index: 26 */
2114 	sd_initpkt_for_buf,		/* Index: 27 */
2115 	sd_initpkt_for_buf,		/* Index: 28 */
2116 	sd_initpkt_for_buf,		/* Index: 29 */
2117 	sd_initpkt_for_buf,		/* Index: 30 */
2118 
2119 	/*
2120 	 * Chain for buf IO for large sector size disk drive targets
2121 	 * with checksumming (PM disabled)
2122 	 */
2123 	sd_initpkt_for_buf,		/* Index: 31 */
2124 	sd_initpkt_for_buf,		/* Index: 32 */
2125 	sd_initpkt_for_buf,		/* Index: 33 */
2126 	sd_initpkt_for_buf,		/* Index: 34 */
2127 };
2128 
2129 
2130 /*
2131  * Array to map a layering chain index to the appropriate destroypktpkt routine.
2132  * The redundant entries are present so that the index used for accessing
2133  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2134  * with this table as well.
2135  */
2136 typedef void (*sd_destroypkt_t)(struct buf *);
2137 
2138 static sd_destroypkt_t	sd_destroypkt_map[] = {
2139 
2140 	/* Chain for buf IO for disk drive targets (PM enabled) */
2141 	sd_destroypkt_for_buf,		/* Index: 0 */
2142 	sd_destroypkt_for_buf,		/* Index: 1 */
2143 	sd_destroypkt_for_buf,		/* Index: 2 */
2144 
2145 	/* Chain for buf IO for disk drive targets (PM disabled) */
2146 	sd_destroypkt_for_buf,		/* Index: 3 */
2147 	sd_destroypkt_for_buf,		/* Index: 4 */
2148 
2149 	/*
2150 	 * Chain for buf IO for removable-media or large sector size
2151 	 * disk drive targets (PM enabled)
2152 	 */
2153 	sd_destroypkt_for_buf,		/* Index: 5 */
2154 	sd_destroypkt_for_buf,		/* Index: 6 */
2155 	sd_destroypkt_for_buf,		/* Index: 7 */
2156 	sd_destroypkt_for_buf,		/* Index: 8 */
2157 
2158 	/*
2159 	 * Chain for buf IO for removable-media or large sector size
2160 	 * disk drive targets (PM disabled)
2161 	 */
2162 	sd_destroypkt_for_buf,		/* Index: 9 */
2163 	sd_destroypkt_for_buf,		/* Index: 10 */
2164 	sd_destroypkt_for_buf,		/* Index: 11 */
2165 
2166 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2167 	sd_destroypkt_for_buf,		/* Index: 12 */
2168 	sd_destroypkt_for_buf,		/* Index: 13 */
2169 	sd_destroypkt_for_buf,		/* Index: 14 */
2170 	sd_destroypkt_for_buf,		/* Index: 15 */
2171 
2172 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2173 	sd_destroypkt_for_buf,		/* Index: 16 */
2174 	sd_destroypkt_for_buf,		/* Index: 17 */
2175 	sd_destroypkt_for_buf,		/* Index: 18 */
2176 
2177 	/* Chain for USCSI commands (non-checksum targets) */
2178 	sd_destroypkt_for_uscsi,	/* Index: 19 */
2179 	sd_destroypkt_for_uscsi,	/* Index: 20 */
2180 
2181 	/* Chain for USCSI commands (checksum targets) */
2182 	sd_destroypkt_for_uscsi,	/* Index: 21 */
2183 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2184 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2185 
2186 	/* Chain for "direct" USCSI commands (all targets) */
2187 	sd_destroypkt_for_uscsi,	/* Index: 24 */
2188 
2189 	/* Chain for "direct priority" USCSI commands (all targets) */
2190 	sd_destroypkt_for_uscsi,	/* Index: 25 */
2191 
2192 	/*
2193 	 * Chain for buf IO for large sector size disk drive targets
2194 	 * with checksumming (PM disabled)
2195 	 */
2196 	sd_destroypkt_for_buf,		/* Index: 26 */
2197 	sd_destroypkt_for_buf,		/* Index: 27 */
2198 	sd_destroypkt_for_buf,		/* Index: 28 */
2199 	sd_destroypkt_for_buf,		/* Index: 29 */
2200 	sd_destroypkt_for_buf,		/* Index: 30 */
2201 
2202 	/*
2203 	 * Chain for buf IO for large sector size disk drive targets
2204 	 * with checksumming (PM enabled)
2205 	 */
2206 	sd_destroypkt_for_buf,		/* Index: 31 */
2207 	sd_destroypkt_for_buf,		/* Index: 32 */
2208 	sd_destroypkt_for_buf,		/* Index: 33 */
2209 	sd_destroypkt_for_buf,		/* Index: 34 */
2210 };
2211 
2212 
2213 
2214 /*
2215  * Array to map a layering chain index to the appropriate chain "type".
2216  * The chain type indicates a specific property/usage of the chain.
2217  * The redundant entries are present so that the index used for accessing
2218  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2219  * with this table as well.
2220  */
2221 
2222 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2223 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2224 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2225 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2226 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2227 						/* (for error recovery) */
2228 
2229 static int sd_chain_type_map[] = {
2230 
2231 	/* Chain for buf IO for disk drive targets (PM enabled) */
2232 	SD_CHAIN_BUFIO,			/* Index: 0 */
2233 	SD_CHAIN_BUFIO,			/* Index: 1 */
2234 	SD_CHAIN_BUFIO,			/* Index: 2 */
2235 
2236 	/* Chain for buf IO for disk drive targets (PM disabled) */
2237 	SD_CHAIN_BUFIO,			/* Index: 3 */
2238 	SD_CHAIN_BUFIO,			/* Index: 4 */
2239 
2240 	/*
2241 	 * Chain for buf IO for removable-media or large sector size
2242 	 * disk drive targets (PM enabled)
2243 	 */
2244 	SD_CHAIN_BUFIO,			/* Index: 5 */
2245 	SD_CHAIN_BUFIO,			/* Index: 6 */
2246 	SD_CHAIN_BUFIO,			/* Index: 7 */
2247 	SD_CHAIN_BUFIO,			/* Index: 8 */
2248 
2249 	/*
2250 	 * Chain for buf IO for removable-media or large sector size
2251 	 * disk drive targets (PM disabled)
2252 	 */
2253 	SD_CHAIN_BUFIO,			/* Index: 9 */
2254 	SD_CHAIN_BUFIO,			/* Index: 10 */
2255 	SD_CHAIN_BUFIO,			/* Index: 11 */
2256 
2257 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2258 	SD_CHAIN_BUFIO,			/* Index: 12 */
2259 	SD_CHAIN_BUFIO,			/* Index: 13 */
2260 	SD_CHAIN_BUFIO,			/* Index: 14 */
2261 	SD_CHAIN_BUFIO,			/* Index: 15 */
2262 
2263 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2264 	SD_CHAIN_BUFIO,			/* Index: 16 */
2265 	SD_CHAIN_BUFIO,			/* Index: 17 */
2266 	SD_CHAIN_BUFIO,			/* Index: 18 */
2267 
2268 	/* Chain for USCSI commands (non-checksum targets) */
2269 	SD_CHAIN_USCSI,			/* Index: 19 */
2270 	SD_CHAIN_USCSI,			/* Index: 20 */
2271 
2272 	/* Chain for USCSI commands (checksum targets) */
2273 	SD_CHAIN_USCSI,			/* Index: 21 */
2274 	SD_CHAIN_USCSI,			/* Index: 22 */
2275 	SD_CHAIN_USCSI,			/* Index: 23 */
2276 
2277 	/* Chain for "direct" USCSI commands (all targets) */
2278 	SD_CHAIN_DIRECT,		/* Index: 24 */
2279 
2280 	/* Chain for "direct priority" USCSI commands (all targets) */
2281 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2282 
2283 	/*
2284 	 * Chain for buf IO for large sector size disk drive targets
2285 	 * with checksumming (PM enabled)
2286 	 */
2287 	SD_CHAIN_BUFIO,			/* Index: 26 */
2288 	SD_CHAIN_BUFIO,			/* Index: 27 */
2289 	SD_CHAIN_BUFIO,			/* Index: 28 */
2290 	SD_CHAIN_BUFIO,			/* Index: 29 */
2291 	SD_CHAIN_BUFIO,			/* Index: 30 */
2292 
2293 	/*
2294 	 * Chain for buf IO for large sector size disk drive targets
2295 	 * with checksumming (PM disabled)
2296 	 */
2297 	SD_CHAIN_BUFIO,			/* Index: 31 */
2298 	SD_CHAIN_BUFIO,			/* Index: 32 */
2299 	SD_CHAIN_BUFIO,			/* Index: 33 */
2300 	SD_CHAIN_BUFIO,			/* Index: 34 */
2301 };
2302 
2303 
2304 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2305 #define	SD_IS_BUFIO(xp)			\
2306 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2307 
2308 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2309 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2310 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2311 
2312 
2313 
2314 /*
2315  * Struct, array, and macros to map a specific chain to the appropriate
2316  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2317  *
2318  * The sd_chain_index_map[] array is used at attach time to set the various
2319  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2320  * chain to be used with the instance. This allows different instances to use
2321  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2322  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2323  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2324  * dynamically & without the use of locking; and (2) a layer may update the
2325  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2326  * to allow for deferred processing of an IO within the same chain from a
2327  * different execution context.
2328  */
2329 
2330 struct sd_chain_index {
2331 	int	sci_iostart_index;
2332 	int	sci_iodone_index;
2333 };
2334 
2335 static struct sd_chain_index	sd_chain_index_map[] = {
2336 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2337 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2338 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2339 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2340 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2341 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2342 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2343 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2344 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2345 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2346 	{ SD_CHAIN_MSS_CHKSUM_IOSTART,		SD_CHAIN_MSS_CHKSUM_IODONE },
2347 	{ SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM, SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM },
2348 
2349 };
2350 
2351 
2352 /*
2353  * The following are indexes into the sd_chain_index_map[] array.
2354  */
2355 
2356 /* un->un_buf_chain_type must be set to one of these */
2357 #define	SD_CHAIN_INFO_DISK		0
2358 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2359 #define	SD_CHAIN_INFO_RMMEDIA		2
2360 #define	SD_CHAIN_INFO_MSS_DISK		2
2361 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2362 #define	SD_CHAIN_INFO_MSS_DSK_NO_PM	3
2363 #define	SD_CHAIN_INFO_CHKSUM		4
2364 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2365 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM	10
2366 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM_NO_PM	11
2367 
2368 /* un->un_uscsi_chain_type must be set to one of these */
2369 #define	SD_CHAIN_INFO_USCSI_CMD		6
2370 /* USCSI with PM disabled is the same as DIRECT */
2371 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2372 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2373 
2374 /* un->un_direct_chain_type must be set to one of these */
2375 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2376 
2377 /* un->un_priority_chain_type must be set to one of these */
2378 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2379 
2380 /* size for devid inquiries */
2381 #define	MAX_INQUIRY_SIZE		0xF0
2382 
2383 /*
2384  * Macros used by functions to pass a given buf(9S) struct along to the
2385  * next function in the layering chain for further processing.
2386  *
2387  * In the following macros, passing more than three arguments to the called
2388  * routines causes the optimizer for the SPARC compiler to stop doing tail
2389  * call elimination which results in significant performance degradation.
2390  */
2391 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2392 	((*(sd_iostart_chain[index]))(index, un, bp))
2393 
2394 #define	SD_BEGIN_IODONE(index, un, bp)	\
2395 	((*(sd_iodone_chain[index]))(index, un, bp))
2396 
2397 #define	SD_NEXT_IOSTART(index, un, bp)				\
2398 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2399 
2400 #define	SD_NEXT_IODONE(index, un, bp)				\
2401 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2402 
2403 /*
2404  *    Function: _init
2405  *
2406  * Description: This is the driver _init(9E) entry point.
2407  *
2408  * Return Code: Returns the value from mod_install(9F) or
2409  *		ddi_soft_state_init(9F) as appropriate.
2410  *
2411  *     Context: Called when driver module loaded.
2412  */
2413 
2414 int
2415 _init(void)
2416 {
2417 	int	err;
2418 
2419 	/* establish driver name from module name */
2420 	sd_label = (char *)mod_modname(&modlinkage);
2421 
2422 #ifndef XPV_HVM_DRIVER
2423 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2424 	    SD_MAXUNIT);
2425 	if (err != 0) {
2426 		return (err);
2427 	}
2428 
2429 #else /* XPV_HVM_DRIVER */
2430 	/* Remove the leading "hvm_" from the module name */
2431 	ASSERT(strncmp(sd_label, "hvm_", strlen("hvm_")) == 0);
2432 	sd_label += strlen("hvm_");
2433 
2434 #endif /* XPV_HVM_DRIVER */
2435 
2436 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2437 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2438 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2439 
2440 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2441 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2442 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2443 
2444 	/*
2445 	 * it's ok to init here even for fibre device
2446 	 */
2447 	sd_scsi_probe_cache_init();
2448 
2449 	sd_scsi_target_lun_init();
2450 
2451 	/*
2452 	 * Creating taskq before mod_install ensures that all callers (threads)
2453 	 * that enter the module after a successful mod_install encounter
2454 	 * a valid taskq.
2455 	 */
2456 	sd_taskq_create();
2457 
2458 	err = mod_install(&modlinkage);
2459 	if (err != 0) {
2460 		/* delete taskq if install fails */
2461 		sd_taskq_delete();
2462 
2463 		mutex_destroy(&sd_detach_mutex);
2464 		mutex_destroy(&sd_log_mutex);
2465 		mutex_destroy(&sd_label_mutex);
2466 
2467 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2468 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2469 		cv_destroy(&sd_tr.srq_inprocess_cv);
2470 
2471 		sd_scsi_probe_cache_fini();
2472 
2473 		sd_scsi_target_lun_fini();
2474 
2475 #ifndef XPV_HVM_DRIVER
2476 		ddi_soft_state_fini(&sd_state);
2477 #endif /* !XPV_HVM_DRIVER */
2478 		return (err);
2479 	}
2480 
2481 	return (err);
2482 }
2483 
2484 
2485 /*
2486  *    Function: _fini
2487  *
2488  * Description: This is the driver _fini(9E) entry point.
2489  *
2490  * Return Code: Returns the value from mod_remove(9F)
2491  *
2492  *     Context: Called when driver module is unloaded.
2493  */
2494 
2495 int
2496 _fini(void)
2497 {
2498 	int err;
2499 
2500 	if ((err = mod_remove(&modlinkage)) != 0) {
2501 		return (err);
2502 	}
2503 
2504 	sd_taskq_delete();
2505 
2506 	mutex_destroy(&sd_detach_mutex);
2507 	mutex_destroy(&sd_log_mutex);
2508 	mutex_destroy(&sd_label_mutex);
2509 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2510 
2511 	sd_scsi_probe_cache_fini();
2512 
2513 	sd_scsi_target_lun_fini();
2514 
2515 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2516 	cv_destroy(&sd_tr.srq_inprocess_cv);
2517 
2518 #ifndef XPV_HVM_DRIVER
2519 	ddi_soft_state_fini(&sd_state);
2520 #endif /* !XPV_HVM_DRIVER */
2521 
2522 	return (err);
2523 }
2524 
2525 
2526 /*
2527  *    Function: _info
2528  *
2529  * Description: This is the driver _info(9E) entry point.
2530  *
2531  *   Arguments: modinfop - pointer to the driver modinfo structure
2532  *
2533  * Return Code: Returns the value from mod_info(9F).
2534  *
2535  *     Context: Kernel thread context
2536  */
2537 
2538 int
2539 _info(struct modinfo *modinfop)
2540 {
2541 	return (mod_info(&modlinkage, modinfop));
2542 }
2543 
2544 
2545 /*
2546  * The following routines implement the driver message logging facility.
2547  * They provide component- and level- based debug output filtering.
2548  * Output may also be restricted to messages for a single instance by
2549  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2550  * to NULL, then messages for all instances are printed.
2551  *
2552  * These routines have been cloned from each other due to the language
2553  * constraints of macros and variable argument list processing.
2554  */
2555 
2556 
2557 /*
2558  *    Function: sd_log_err
2559  *
2560  * Description: This routine is called by the SD_ERROR macro for debug
2561  *		logging of error conditions.
2562  *
2563  *   Arguments: comp - driver component being logged
2564  *		dev  - pointer to driver info structure
2565  *		fmt  - error string and format to be logged
2566  */
2567 
2568 static void
2569 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2570 {
2571 	va_list		ap;
2572 	dev_info_t	*dev;
2573 
2574 	ASSERT(un != NULL);
2575 	dev = SD_DEVINFO(un);
2576 	ASSERT(dev != NULL);
2577 
2578 	/*
2579 	 * Filter messages based on the global component and level masks.
2580 	 * Also print if un matches the value of sd_debug_un, or if
2581 	 * sd_debug_un is set to NULL.
2582 	 */
2583 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2584 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2585 		mutex_enter(&sd_log_mutex);
2586 		va_start(ap, fmt);
2587 		(void) vsprintf(sd_log_buf, fmt, ap);
2588 		va_end(ap);
2589 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2590 		mutex_exit(&sd_log_mutex);
2591 	}
2592 #ifdef SD_FAULT_INJECTION
2593 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2594 	if (un->sd_injection_mask & comp) {
2595 		mutex_enter(&sd_log_mutex);
2596 		va_start(ap, fmt);
2597 		(void) vsprintf(sd_log_buf, fmt, ap);
2598 		va_end(ap);
2599 		sd_injection_log(sd_log_buf, un);
2600 		mutex_exit(&sd_log_mutex);
2601 	}
2602 #endif
2603 }
2604 
2605 
2606 /*
2607  *    Function: sd_log_info
2608  *
2609  * Description: This routine is called by the SD_INFO macro for debug
2610  *		logging of general purpose informational conditions.
2611  *
2612  *   Arguments: comp - driver component being logged
2613  *		dev  - pointer to driver info structure
2614  *		fmt  - info string and format to be logged
2615  */
2616 
2617 static void
2618 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2619 {
2620 	va_list		ap;
2621 	dev_info_t	*dev;
2622 
2623 	ASSERT(un != NULL);
2624 	dev = SD_DEVINFO(un);
2625 	ASSERT(dev != NULL);
2626 
2627 	/*
2628 	 * Filter messages based on the global component and level masks.
2629 	 * Also print if un matches the value of sd_debug_un, or if
2630 	 * sd_debug_un is set to NULL.
2631 	 */
2632 	if ((sd_component_mask & component) &&
2633 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2634 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2635 		mutex_enter(&sd_log_mutex);
2636 		va_start(ap, fmt);
2637 		(void) vsprintf(sd_log_buf, fmt, ap);
2638 		va_end(ap);
2639 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2640 		mutex_exit(&sd_log_mutex);
2641 	}
2642 #ifdef SD_FAULT_INJECTION
2643 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2644 	if (un->sd_injection_mask & component) {
2645 		mutex_enter(&sd_log_mutex);
2646 		va_start(ap, fmt);
2647 		(void) vsprintf(sd_log_buf, fmt, ap);
2648 		va_end(ap);
2649 		sd_injection_log(sd_log_buf, un);
2650 		mutex_exit(&sd_log_mutex);
2651 	}
2652 #endif
2653 }
2654 
2655 
2656 /*
2657  *    Function: sd_log_trace
2658  *
2659  * Description: This routine is called by the SD_TRACE macro for debug
2660  *		logging of trace conditions (i.e. function entry/exit).
2661  *
2662  *   Arguments: comp - driver component being logged
2663  *		dev  - pointer to driver info structure
2664  *		fmt  - trace string and format to be logged
2665  */
2666 
2667 static void
2668 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2669 {
2670 	va_list		ap;
2671 	dev_info_t	*dev;
2672 
2673 	ASSERT(un != NULL);
2674 	dev = SD_DEVINFO(un);
2675 	ASSERT(dev != NULL);
2676 
2677 	/*
2678 	 * Filter messages based on the global component and level masks.
2679 	 * Also print if un matches the value of sd_debug_un, or if
2680 	 * sd_debug_un is set to NULL.
2681 	 */
2682 	if ((sd_component_mask & component) &&
2683 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2684 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2685 		mutex_enter(&sd_log_mutex);
2686 		va_start(ap, fmt);
2687 		(void) vsprintf(sd_log_buf, fmt, ap);
2688 		va_end(ap);
2689 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2690 		mutex_exit(&sd_log_mutex);
2691 	}
2692 #ifdef SD_FAULT_INJECTION
2693 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2694 	if (un->sd_injection_mask & component) {
2695 		mutex_enter(&sd_log_mutex);
2696 		va_start(ap, fmt);
2697 		(void) vsprintf(sd_log_buf, fmt, ap);
2698 		va_end(ap);
2699 		sd_injection_log(sd_log_buf, un);
2700 		mutex_exit(&sd_log_mutex);
2701 	}
2702 #endif
2703 }
2704 
2705 
2706 /*
2707  *    Function: sdprobe
2708  *
2709  * Description: This is the driver probe(9e) entry point function.
2710  *
2711  *   Arguments: devi - opaque device info handle
2712  *
2713  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2714  *              DDI_PROBE_FAILURE: If the probe failed.
2715  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2716  *				   but may be present in the future.
2717  */
2718 
2719 static int
2720 sdprobe(dev_info_t *devi)
2721 {
2722 	struct scsi_device	*devp;
2723 	int			rval;
2724 #ifndef XPV_HVM_DRIVER
2725 	int			instance = ddi_get_instance(devi);
2726 #endif /* !XPV_HVM_DRIVER */
2727 
2728 	/*
2729 	 * if it wasn't for pln, sdprobe could actually be nulldev
2730 	 * in the "__fibre" case.
2731 	 */
2732 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2733 		return (DDI_PROBE_DONTCARE);
2734 	}
2735 
2736 	devp = ddi_get_driver_private(devi);
2737 
2738 	if (devp == NULL) {
2739 		/* Ooops... nexus driver is mis-configured... */
2740 		return (DDI_PROBE_FAILURE);
2741 	}
2742 
2743 #ifndef XPV_HVM_DRIVER
2744 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2745 		return (DDI_PROBE_PARTIAL);
2746 	}
2747 #endif /* !XPV_HVM_DRIVER */
2748 
2749 	/*
2750 	 * Call the SCSA utility probe routine to see if we actually
2751 	 * have a target at this SCSI nexus.
2752 	 */
2753 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2754 	case SCSIPROBE_EXISTS:
2755 		switch (devp->sd_inq->inq_dtype) {
2756 		case DTYPE_DIRECT:
2757 			rval = DDI_PROBE_SUCCESS;
2758 			break;
2759 		case DTYPE_RODIRECT:
2760 			/* CDs etc. Can be removable media */
2761 			rval = DDI_PROBE_SUCCESS;
2762 			break;
2763 		case DTYPE_OPTICAL:
2764 			/*
2765 			 * Rewritable optical driver HP115AA
2766 			 * Can also be removable media
2767 			 */
2768 
2769 			/*
2770 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2771 			 * pre solaris 9 sparc sd behavior is required
2772 			 *
2773 			 * If first time through and sd_dtype_optical_bind
2774 			 * has not been set in /etc/system check properties
2775 			 */
2776 
2777 			if (sd_dtype_optical_bind  < 0) {
2778 				sd_dtype_optical_bind = ddi_prop_get_int
2779 				    (DDI_DEV_T_ANY, devi, 0,
2780 				    "optical-device-bind", 1);
2781 			}
2782 
2783 			if (sd_dtype_optical_bind == 0) {
2784 				rval = DDI_PROBE_FAILURE;
2785 			} else {
2786 				rval = DDI_PROBE_SUCCESS;
2787 			}
2788 			break;
2789 
2790 		case DTYPE_NOTPRESENT:
2791 		default:
2792 			rval = DDI_PROBE_FAILURE;
2793 			break;
2794 		}
2795 		break;
2796 	default:
2797 		rval = DDI_PROBE_PARTIAL;
2798 		break;
2799 	}
2800 
2801 	/*
2802 	 * This routine checks for resource allocation prior to freeing,
2803 	 * so it will take care of the "smart probing" case where a
2804 	 * scsi_probe() may or may not have been issued and will *not*
2805 	 * free previously-freed resources.
2806 	 */
2807 	scsi_unprobe(devp);
2808 	return (rval);
2809 }
2810 
2811 
2812 /*
2813  *    Function: sdinfo
2814  *
2815  * Description: This is the driver getinfo(9e) entry point function.
2816  * 		Given the device number, return the devinfo pointer from
2817  *		the scsi_device structure or the instance number
2818  *		associated with the dev_t.
2819  *
2820  *   Arguments: dip     - pointer to device info structure
2821  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2822  *			  DDI_INFO_DEVT2INSTANCE)
2823  *		arg     - driver dev_t
2824  *		resultp - user buffer for request response
2825  *
2826  * Return Code: DDI_SUCCESS
2827  *              DDI_FAILURE
2828  */
2829 /* ARGSUSED */
2830 static int
2831 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2832 {
2833 	struct sd_lun	*un;
2834 	dev_t		dev;
2835 	int		instance;
2836 	int		error;
2837 
2838 	switch (infocmd) {
2839 	case DDI_INFO_DEVT2DEVINFO:
2840 		dev = (dev_t)arg;
2841 		instance = SDUNIT(dev);
2842 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2843 			return (DDI_FAILURE);
2844 		}
2845 		*result = (void *) SD_DEVINFO(un);
2846 		error = DDI_SUCCESS;
2847 		break;
2848 	case DDI_INFO_DEVT2INSTANCE:
2849 		dev = (dev_t)arg;
2850 		instance = SDUNIT(dev);
2851 		*result = (void *)(uintptr_t)instance;
2852 		error = DDI_SUCCESS;
2853 		break;
2854 	default:
2855 		error = DDI_FAILURE;
2856 	}
2857 	return (error);
2858 }
2859 
2860 /*
2861  *    Function: sd_prop_op
2862  *
2863  * Description: This is the driver prop_op(9e) entry point function.
2864  *		Return the number of blocks for the partition in question
2865  *		or forward the request to the property facilities.
2866  *
2867  *   Arguments: dev       - device number
2868  *		dip       - pointer to device info structure
2869  *		prop_op   - property operator
2870  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2871  *		name      - pointer to property name
2872  *		valuep    - pointer or address of the user buffer
2873  *		lengthp   - property length
2874  *
2875  * Return Code: DDI_PROP_SUCCESS
2876  *              DDI_PROP_NOT_FOUND
2877  *              DDI_PROP_UNDEFINED
2878  *              DDI_PROP_NO_MEMORY
2879  *              DDI_PROP_BUF_TOO_SMALL
2880  */
2881 
2882 static int
2883 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2884 	char *name, caddr_t valuep, int *lengthp)
2885 {
2886 	struct sd_lun	*un;
2887 
2888 	if ((un = ddi_get_soft_state(sd_state, ddi_get_instance(dip))) == NULL)
2889 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2890 		    name, valuep, lengthp));
2891 
2892 	return (cmlb_prop_op(un->un_cmlbhandle,
2893 	    dev, dip, prop_op, mod_flags, name, valuep, lengthp,
2894 	    SDPART(dev), (void *)SD_PATH_DIRECT));
2895 }
2896 
2897 /*
2898  * The following functions are for smart probing:
2899  * sd_scsi_probe_cache_init()
2900  * sd_scsi_probe_cache_fini()
2901  * sd_scsi_clear_probe_cache()
2902  * sd_scsi_probe_with_cache()
2903  */
2904 
2905 /*
2906  *    Function: sd_scsi_probe_cache_init
2907  *
2908  * Description: Initializes the probe response cache mutex and head pointer.
2909  *
2910  *     Context: Kernel thread context
2911  */
2912 
2913 static void
2914 sd_scsi_probe_cache_init(void)
2915 {
2916 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2917 	sd_scsi_probe_cache_head = NULL;
2918 }
2919 
2920 
2921 /*
2922  *    Function: sd_scsi_probe_cache_fini
2923  *
2924  * Description: Frees all resources associated with the probe response cache.
2925  *
2926  *     Context: Kernel thread context
2927  */
2928 
2929 static void
2930 sd_scsi_probe_cache_fini(void)
2931 {
2932 	struct sd_scsi_probe_cache *cp;
2933 	struct sd_scsi_probe_cache *ncp;
2934 
2935 	/* Clean up our smart probing linked list */
2936 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2937 		ncp = cp->next;
2938 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2939 	}
2940 	sd_scsi_probe_cache_head = NULL;
2941 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2942 }
2943 
2944 
2945 /*
2946  *    Function: sd_scsi_clear_probe_cache
2947  *
2948  * Description: This routine clears the probe response cache. This is
2949  *		done when open() returns ENXIO so that when deferred
2950  *		attach is attempted (possibly after a device has been
2951  *		turned on) we will retry the probe. Since we don't know
2952  *		which target we failed to open, we just clear the
2953  *		entire cache.
2954  *
2955  *     Context: Kernel thread context
2956  */
2957 
2958 static void
2959 sd_scsi_clear_probe_cache(void)
2960 {
2961 	struct sd_scsi_probe_cache	*cp;
2962 	int				i;
2963 
2964 	mutex_enter(&sd_scsi_probe_cache_mutex);
2965 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2966 		/*
2967 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2968 		 * force probing to be performed the next time
2969 		 * sd_scsi_probe_with_cache is called.
2970 		 */
2971 		for (i = 0; i < NTARGETS_WIDE; i++) {
2972 			cp->cache[i] = SCSIPROBE_EXISTS;
2973 		}
2974 	}
2975 	mutex_exit(&sd_scsi_probe_cache_mutex);
2976 }
2977 
2978 
2979 /*
2980  *    Function: sd_scsi_probe_with_cache
2981  *
2982  * Description: This routine implements support for a scsi device probe
2983  *		with cache. The driver maintains a cache of the target
2984  *		responses to scsi probes. If we get no response from a
2985  *		target during a probe inquiry, we remember that, and we
2986  *		avoid additional calls to scsi_probe on non-zero LUNs
2987  *		on the same target until the cache is cleared. By doing
2988  *		so we avoid the 1/4 sec selection timeout for nonzero
2989  *		LUNs. lun0 of a target is always probed.
2990  *
2991  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2992  *              waitfunc - indicates what the allocator routines should
2993  *			   do when resources are not available. This value
2994  *			   is passed on to scsi_probe() when that routine
2995  *			   is called.
2996  *
2997  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2998  *		otherwise the value returned by scsi_probe(9F).
2999  *
3000  *     Context: Kernel thread context
3001  */
3002 
3003 static int
3004 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
3005 {
3006 	struct sd_scsi_probe_cache	*cp;
3007 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
3008 	int		lun, tgt;
3009 
3010 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
3011 	    SCSI_ADDR_PROP_LUN, 0);
3012 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
3013 	    SCSI_ADDR_PROP_TARGET, -1);
3014 
3015 	/* Make sure caching enabled and target in range */
3016 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
3017 		/* do it the old way (no cache) */
3018 		return (scsi_probe(devp, waitfn));
3019 	}
3020 
3021 	mutex_enter(&sd_scsi_probe_cache_mutex);
3022 
3023 	/* Find the cache for this scsi bus instance */
3024 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
3025 		if (cp->pdip == pdip) {
3026 			break;
3027 		}
3028 	}
3029 
3030 	/* If we can't find a cache for this pdip, create one */
3031 	if (cp == NULL) {
3032 		int i;
3033 
3034 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
3035 		    KM_SLEEP);
3036 		cp->pdip = pdip;
3037 		cp->next = sd_scsi_probe_cache_head;
3038 		sd_scsi_probe_cache_head = cp;
3039 		for (i = 0; i < NTARGETS_WIDE; i++) {
3040 			cp->cache[i] = SCSIPROBE_EXISTS;
3041 		}
3042 	}
3043 
3044 	mutex_exit(&sd_scsi_probe_cache_mutex);
3045 
3046 	/* Recompute the cache for this target if LUN zero */
3047 	if (lun == 0) {
3048 		cp->cache[tgt] = SCSIPROBE_EXISTS;
3049 	}
3050 
3051 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
3052 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
3053 		return (SCSIPROBE_NORESP);
3054 	}
3055 
3056 	/* Do the actual probe; save & return the result */
3057 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
3058 }
3059 
3060 
3061 /*
3062  *    Function: sd_scsi_target_lun_init
3063  *
3064  * Description: Initializes the attached lun chain mutex and head pointer.
3065  *
3066  *     Context: Kernel thread context
3067  */
3068 
3069 static void
3070 sd_scsi_target_lun_init(void)
3071 {
3072 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
3073 	sd_scsi_target_lun_head = NULL;
3074 }
3075 
3076 
3077 /*
3078  *    Function: sd_scsi_target_lun_fini
3079  *
3080  * Description: Frees all resources associated with the attached lun
3081  *              chain
3082  *
3083  *     Context: Kernel thread context
3084  */
3085 
3086 static void
3087 sd_scsi_target_lun_fini(void)
3088 {
3089 	struct sd_scsi_hba_tgt_lun	*cp;
3090 	struct sd_scsi_hba_tgt_lun	*ncp;
3091 
3092 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
3093 		ncp = cp->next;
3094 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
3095 	}
3096 	sd_scsi_target_lun_head = NULL;
3097 	mutex_destroy(&sd_scsi_target_lun_mutex);
3098 }
3099 
3100 
3101 /*
3102  *    Function: sd_scsi_get_target_lun_count
3103  *
3104  * Description: This routine will check in the attached lun chain to see
3105  * 		how many luns are attached on the required SCSI controller
3106  * 		and target. Currently, some capabilities like tagged queue
3107  *		are supported per target based by HBA. So all luns in a
3108  *		target have the same capabilities. Based on this assumption,
3109  * 		sd should only set these capabilities once per target. This
3110  *		function is called when sd needs to decide how many luns
3111  *		already attached on a target.
3112  *
3113  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
3114  *			  controller device.
3115  *              target	- The target ID on the controller's SCSI bus.
3116  *
3117  * Return Code: The number of luns attached on the required target and
3118  *		controller.
3119  *		-1 if target ID is not in parallel SCSI scope or the given
3120  * 		dip is not in the chain.
3121  *
3122  *     Context: Kernel thread context
3123  */
3124 
3125 static int
3126 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
3127 {
3128 	struct sd_scsi_hba_tgt_lun	*cp;
3129 
3130 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
3131 		return (-1);
3132 	}
3133 
3134 	mutex_enter(&sd_scsi_target_lun_mutex);
3135 
3136 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3137 		if (cp->pdip == dip) {
3138 			break;
3139 		}
3140 	}
3141 
3142 	mutex_exit(&sd_scsi_target_lun_mutex);
3143 
3144 	if (cp == NULL) {
3145 		return (-1);
3146 	}
3147 
3148 	return (cp->nlun[target]);
3149 }
3150 
3151 
3152 /*
3153  *    Function: sd_scsi_update_lun_on_target
3154  *
3155  * Description: This routine is used to update the attached lun chain when a
3156  *		lun is attached or detached on a target.
3157  *
3158  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
3159  *                        controller device.
3160  *              target  - The target ID on the controller's SCSI bus.
3161  *		flag	- Indicate the lun is attached or detached.
3162  *
3163  *     Context: Kernel thread context
3164  */
3165 
3166 static void
3167 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
3168 {
3169 	struct sd_scsi_hba_tgt_lun	*cp;
3170 
3171 	mutex_enter(&sd_scsi_target_lun_mutex);
3172 
3173 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3174 		if (cp->pdip == dip) {
3175 			break;
3176 		}
3177 	}
3178 
3179 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
3180 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
3181 		    KM_SLEEP);
3182 		cp->pdip = dip;
3183 		cp->next = sd_scsi_target_lun_head;
3184 		sd_scsi_target_lun_head = cp;
3185 	}
3186 
3187 	mutex_exit(&sd_scsi_target_lun_mutex);
3188 
3189 	if (cp != NULL) {
3190 		if (flag == SD_SCSI_LUN_ATTACH) {
3191 			cp->nlun[target] ++;
3192 		} else {
3193 			cp->nlun[target] --;
3194 		}
3195 	}
3196 }
3197 
3198 
3199 /*
3200  *    Function: sd_spin_up_unit
3201  *
3202  * Description: Issues the following commands to spin-up the device:
3203  *		START STOP UNIT, and INQUIRY.
3204  *
3205  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3206  *                      structure for this target.
3207  *
3208  * Return Code: 0 - success
3209  *		EIO - failure
3210  *		EACCES - reservation conflict
3211  *
3212  *     Context: Kernel thread context
3213  */
3214 
3215 static int
3216 sd_spin_up_unit(sd_ssc_t *ssc)
3217 {
3218 	size_t	resid		= 0;
3219 	int	has_conflict	= FALSE;
3220 	uchar_t *bufaddr;
3221 	int 	status;
3222 	struct sd_lun	*un;
3223 
3224 	ASSERT(ssc != NULL);
3225 	un = ssc->ssc_un;
3226 	ASSERT(un != NULL);
3227 
3228 	/*
3229 	 * Send a throwaway START UNIT command.
3230 	 *
3231 	 * If we fail on this, we don't care presently what precisely
3232 	 * is wrong.  EMC's arrays will also fail this with a check
3233 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
3234 	 * we don't want to fail the attach because it may become
3235 	 * "active" later.
3236 	 * We don't know if power condition is supported or not at
3237 	 * this stage, use START STOP bit.
3238 	 */
3239 	status = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
3240 	    SD_TARGET_START, SD_PATH_DIRECT);
3241 
3242 	if (status != 0) {
3243 		if (status == EACCES)
3244 			has_conflict = TRUE;
3245 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3246 	}
3247 
3248 	/*
3249 	 * Send another INQUIRY command to the target. This is necessary for
3250 	 * non-removable media direct access devices because their INQUIRY data
3251 	 * may not be fully qualified until they are spun up (perhaps via the
3252 	 * START command above).  Note: This seems to be needed for some
3253 	 * legacy devices only.) The INQUIRY command should succeed even if a
3254 	 * Reservation Conflict is present.
3255 	 */
3256 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
3257 
3258 	if (sd_send_scsi_INQUIRY(ssc, bufaddr, SUN_INQSIZE, 0, 0, &resid)
3259 	    != 0) {
3260 		kmem_free(bufaddr, SUN_INQSIZE);
3261 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
3262 		return (EIO);
3263 	}
3264 
3265 	/*
3266 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
3267 	 * Note that this routine does not return a failure here even if the
3268 	 * INQUIRY command did not return any data.  This is a legacy behavior.
3269 	 */
3270 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
3271 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
3272 	}
3273 
3274 	kmem_free(bufaddr, SUN_INQSIZE);
3275 
3276 	/* If we hit a reservation conflict above, tell the caller. */
3277 	if (has_conflict == TRUE) {
3278 		return (EACCES);
3279 	}
3280 
3281 	return (0);
3282 }
3283 
3284 #ifdef _LP64
3285 /*
3286  *    Function: sd_enable_descr_sense
3287  *
3288  * Description: This routine attempts to select descriptor sense format
3289  *		using the Control mode page.  Devices that support 64 bit
3290  *		LBAs (for >2TB luns) should also implement descriptor
3291  *		sense data so we will call this function whenever we see
3292  *		a lun larger than 2TB.  If for some reason the device
3293  *		supports 64 bit LBAs but doesn't support descriptor sense
3294  *		presumably the mode select will fail.  Everything will
3295  *		continue to work normally except that we will not get
3296  *		complete sense data for commands that fail with an LBA
3297  *		larger than 32 bits.
3298  *
3299  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3300  *                      structure for this target.
3301  *
3302  *     Context: Kernel thread context only
3303  */
3304 
3305 static void
3306 sd_enable_descr_sense(sd_ssc_t *ssc)
3307 {
3308 	uchar_t			*header;
3309 	struct mode_control_scsi3 *ctrl_bufp;
3310 	size_t			buflen;
3311 	size_t			bd_len;
3312 	int			status;
3313 	struct sd_lun		*un;
3314 
3315 	ASSERT(ssc != NULL);
3316 	un = ssc->ssc_un;
3317 	ASSERT(un != NULL);
3318 
3319 	/*
3320 	 * Read MODE SENSE page 0xA, Control Mode Page
3321 	 */
3322 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3323 	    sizeof (struct mode_control_scsi3);
3324 	header = kmem_zalloc(buflen, KM_SLEEP);
3325 
3326 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
3327 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT);
3328 
3329 	if (status != 0) {
3330 		SD_ERROR(SD_LOG_COMMON, un,
3331 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3332 		goto eds_exit;
3333 	}
3334 
3335 	/*
3336 	 * Determine size of Block Descriptors in order to locate
3337 	 * the mode page data. ATAPI devices return 0, SCSI devices
3338 	 * should return MODE_BLK_DESC_LENGTH.
3339 	 */
3340 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3341 
3342 	/* Clear the mode data length field for MODE SELECT */
3343 	((struct mode_header *)header)->length = 0;
3344 
3345 	ctrl_bufp = (struct mode_control_scsi3 *)
3346 	    (header + MODE_HEADER_LENGTH + bd_len);
3347 
3348 	/*
3349 	 * If the page length is smaller than the expected value,
3350 	 * the target device doesn't support D_SENSE. Bail out here.
3351 	 */
3352 	if (ctrl_bufp->mode_page.length <
3353 	    sizeof (struct mode_control_scsi3) - 2) {
3354 		SD_ERROR(SD_LOG_COMMON, un,
3355 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3356 		goto eds_exit;
3357 	}
3358 
3359 	/*
3360 	 * Clear PS bit for MODE SELECT
3361 	 */
3362 	ctrl_bufp->mode_page.ps = 0;
3363 
3364 	/*
3365 	 * Set D_SENSE to enable descriptor sense format.
3366 	 */
3367 	ctrl_bufp->d_sense = 1;
3368 
3369 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3370 
3371 	/*
3372 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3373 	 */
3374 	status = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
3375 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT);
3376 
3377 	if (status != 0) {
3378 		SD_INFO(SD_LOG_COMMON, un,
3379 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3380 	} else {
3381 		kmem_free(header, buflen);
3382 		return;
3383 	}
3384 
3385 eds_exit:
3386 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3387 	kmem_free(header, buflen);
3388 }
3389 
3390 /*
3391  *    Function: sd_reenable_dsense_task
3392  *
3393  * Description: Re-enable descriptor sense after device or bus reset
3394  *
3395  *     Context: Executes in a taskq() thread context
3396  */
3397 static void
3398 sd_reenable_dsense_task(void *arg)
3399 {
3400 	struct	sd_lun	*un = arg;
3401 	sd_ssc_t	*ssc;
3402 
3403 	ASSERT(un != NULL);
3404 
3405 	ssc = sd_ssc_init(un);
3406 	sd_enable_descr_sense(ssc);
3407 	sd_ssc_fini(ssc);
3408 }
3409 #endif /* _LP64 */
3410 
3411 /*
3412  *    Function: sd_set_mmc_caps
3413  *
3414  * Description: This routine determines if the device is MMC compliant and if
3415  *		the device supports CDDA via a mode sense of the CDVD
3416  *		capabilities mode page. Also checks if the device is a
3417  *		dvdram writable device.
3418  *
3419  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3420  *                      structure for this target.
3421  *
3422  *     Context: Kernel thread context only
3423  */
3424 
3425 static void
3426 sd_set_mmc_caps(sd_ssc_t *ssc)
3427 {
3428 	struct mode_header_grp2		*sense_mhp;
3429 	uchar_t				*sense_page;
3430 	caddr_t				buf;
3431 	int				bd_len;
3432 	int				status;
3433 	struct uscsi_cmd		com;
3434 	int				rtn;
3435 	uchar_t				*out_data_rw, *out_data_hd;
3436 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3437 	uchar_t				*out_data_gesn;
3438 	int				gesn_len;
3439 	struct sd_lun			*un;
3440 
3441 	ASSERT(ssc != NULL);
3442 	un = ssc->ssc_un;
3443 	ASSERT(un != NULL);
3444 
3445 	/*
3446 	 * The flags which will be set in this function are - mmc compliant,
3447 	 * dvdram writable device, cdda support. Initialize them to FALSE
3448 	 * and if a capability is detected - it will be set to TRUE.
3449 	 */
3450 	un->un_f_mmc_cap = FALSE;
3451 	un->un_f_dvdram_writable_device = FALSE;
3452 	un->un_f_cfg_cdda = FALSE;
3453 
3454 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3455 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3456 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3457 
3458 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3459 
3460 	if (status != 0) {
3461 		/* command failed; just return */
3462 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3463 		return;
3464 	}
3465 	/*
3466 	 * If the mode sense request for the CDROM CAPABILITIES
3467 	 * page (0x2A) succeeds the device is assumed to be MMC.
3468 	 */
3469 	un->un_f_mmc_cap = TRUE;
3470 
3471 	/* See if GET STATUS EVENT NOTIFICATION is supported */
3472 	if (un->un_f_mmc_gesn_polling) {
3473 		gesn_len = SD_GESN_HEADER_LEN + SD_GESN_MEDIA_DATA_LEN;
3474 		out_data_gesn = kmem_zalloc(gesn_len, KM_SLEEP);
3475 
3476 		rtn = sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(ssc,
3477 		    out_data_gesn, gesn_len, 1 << SD_GESN_MEDIA_CLASS);
3478 
3479 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3480 
3481 		if ((rtn != 0) || !sd_gesn_media_data_valid(out_data_gesn)) {
3482 			un->un_f_mmc_gesn_polling = FALSE;
3483 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3484 			    "sd_set_mmc_caps: gesn not supported "
3485 			    "%d %x %x %x %x\n", rtn,
3486 			    out_data_gesn[0], out_data_gesn[1],
3487 			    out_data_gesn[2], out_data_gesn[3]);
3488 		}
3489 
3490 		kmem_free(out_data_gesn, gesn_len);
3491 	}
3492 
3493 	/* Get to the page data */
3494 	sense_mhp = (struct mode_header_grp2 *)buf;
3495 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3496 	    sense_mhp->bdesc_length_lo;
3497 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3498 		/*
3499 		 * We did not get back the expected block descriptor
3500 		 * length so we cannot determine if the device supports
3501 		 * CDDA. However, we still indicate the device is MMC
3502 		 * according to the successful response to the page
3503 		 * 0x2A mode sense request.
3504 		 */
3505 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3506 		    "sd_set_mmc_caps: Mode Sense returned "
3507 		    "invalid block descriptor length\n");
3508 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3509 		return;
3510 	}
3511 
3512 	/* See if read CDDA is supported */
3513 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3514 	    bd_len);
3515 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3516 
3517 	/* See if writing DVD RAM is supported. */
3518 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3519 	if (un->un_f_dvdram_writable_device == TRUE) {
3520 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3521 		return;
3522 	}
3523 
3524 	/*
3525 	 * If the device presents DVD or CD capabilities in the mode
3526 	 * page, we can return here since a RRD will not have
3527 	 * these capabilities.
3528 	 */
3529 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3530 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3531 		return;
3532 	}
3533 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3534 
3535 	/*
3536 	 * If un->un_f_dvdram_writable_device is still FALSE,
3537 	 * check for a Removable Rigid Disk (RRD).  A RRD
3538 	 * device is identified by the features RANDOM_WRITABLE and
3539 	 * HARDWARE_DEFECT_MANAGEMENT.
3540 	 */
3541 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3542 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3543 
3544 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3545 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3546 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3547 
3548 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3549 
3550 	if (rtn != 0) {
3551 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3552 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3553 		return;
3554 	}
3555 
3556 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3557 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3558 
3559 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3560 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3561 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3562 
3563 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3564 
3565 	if (rtn == 0) {
3566 		/*
3567 		 * We have good information, check for random writable
3568 		 * and hardware defect features.
3569 		 */
3570 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3571 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3572 			un->un_f_dvdram_writable_device = TRUE;
3573 		}
3574 	}
3575 
3576 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3577 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3578 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3579 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3580 }
3581 
3582 /*
3583  *    Function: sd_check_for_writable_cd
3584  *
3585  * Description: This routine determines if the media in the device is
3586  *		writable or not. It uses the get configuration command (0x46)
3587  *		to determine if the media is writable
3588  *
3589  *   Arguments: un - driver soft state (unit) structure
3590  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3591  *                           chain and the normal command waitq, or
3592  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3593  *                           "direct" chain and bypass the normal command
3594  *                           waitq.
3595  *
3596  *     Context: Never called at interrupt context.
3597  */
3598 
3599 static void
3600 sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag)
3601 {
3602 	struct uscsi_cmd		com;
3603 	uchar_t				*out_data;
3604 	uchar_t				*rqbuf;
3605 	int				rtn;
3606 	uchar_t				*out_data_rw, *out_data_hd;
3607 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3608 	struct mode_header_grp2		*sense_mhp;
3609 	uchar_t				*sense_page;
3610 	caddr_t				buf;
3611 	int				bd_len;
3612 	int				status;
3613 	struct sd_lun			*un;
3614 
3615 	ASSERT(ssc != NULL);
3616 	un = ssc->ssc_un;
3617 	ASSERT(un != NULL);
3618 	ASSERT(mutex_owned(SD_MUTEX(un)));
3619 
3620 	/*
3621 	 * Initialize the writable media to false, if configuration info.
3622 	 * tells us otherwise then only we will set it.
3623 	 */
3624 	un->un_f_mmc_writable_media = FALSE;
3625 	mutex_exit(SD_MUTEX(un));
3626 
3627 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3628 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3629 
3630 	rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf, SENSE_LENGTH,
3631 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3632 
3633 	if (rtn != 0)
3634 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3635 
3636 	mutex_enter(SD_MUTEX(un));
3637 	if (rtn == 0) {
3638 		/*
3639 		 * We have good information, check for writable DVD.
3640 		 */
3641 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3642 			un->un_f_mmc_writable_media = TRUE;
3643 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3644 			kmem_free(rqbuf, SENSE_LENGTH);
3645 			return;
3646 		}
3647 	}
3648 
3649 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3650 	kmem_free(rqbuf, SENSE_LENGTH);
3651 
3652 	/*
3653 	 * Determine if this is a RRD type device.
3654 	 */
3655 	mutex_exit(SD_MUTEX(un));
3656 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3657 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3658 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3659 
3660 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3661 
3662 	mutex_enter(SD_MUTEX(un));
3663 	if (status != 0) {
3664 		/* command failed; just return */
3665 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3666 		return;
3667 	}
3668 
3669 	/* Get to the page data */
3670 	sense_mhp = (struct mode_header_grp2 *)buf;
3671 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3672 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3673 		/*
3674 		 * We did not get back the expected block descriptor length so
3675 		 * we cannot check the mode page.
3676 		 */
3677 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3678 		    "sd_check_for_writable_cd: Mode Sense returned "
3679 		    "invalid block descriptor length\n");
3680 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3681 		return;
3682 	}
3683 
3684 	/*
3685 	 * If the device presents DVD or CD capabilities in the mode
3686 	 * page, we can return here since a RRD device will not have
3687 	 * these capabilities.
3688 	 */
3689 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3690 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3691 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3692 		return;
3693 	}
3694 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3695 
3696 	/*
3697 	 * If un->un_f_mmc_writable_media is still FALSE,
3698 	 * check for RRD type media.  A RRD device is identified
3699 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3700 	 */
3701 	mutex_exit(SD_MUTEX(un));
3702 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3703 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3704 
3705 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3706 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3707 	    RANDOM_WRITABLE, path_flag);
3708 
3709 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3710 	if (rtn != 0) {
3711 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3712 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3713 		mutex_enter(SD_MUTEX(un));
3714 		return;
3715 	}
3716 
3717 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3718 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3719 
3720 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3721 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3722 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3723 
3724 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3725 	mutex_enter(SD_MUTEX(un));
3726 	if (rtn == 0) {
3727 		/*
3728 		 * We have good information, check for random writable
3729 		 * and hardware defect features as current.
3730 		 */
3731 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3732 		    (out_data_rw[10] & 0x1) &&
3733 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3734 		    (out_data_hd[10] & 0x1)) {
3735 			un->un_f_mmc_writable_media = TRUE;
3736 		}
3737 	}
3738 
3739 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3740 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3741 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3742 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3743 }
3744 
3745 /*
3746  *    Function: sd_read_unit_properties
3747  *
3748  * Description: The following implements a property lookup mechanism.
3749  *		Properties for particular disks (keyed on vendor, model
3750  *		and rev numbers) are sought in the sd.conf file via
3751  *		sd_process_sdconf_file(), and if not found there, are
3752  *		looked for in a list hardcoded in this driver via
3753  *		sd_process_sdconf_table() Once located the properties
3754  *		are used to update the driver unit structure.
3755  *
3756  *   Arguments: un - driver soft state (unit) structure
3757  */
3758 
3759 static void
3760 sd_read_unit_properties(struct sd_lun *un)
3761 {
3762 	/*
3763 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3764 	 * the "sd-config-list" property (from the sd.conf file) or if
3765 	 * there was not a match for the inquiry vid/pid. If this event
3766 	 * occurs the static driver configuration table is searched for
3767 	 * a match.
3768 	 */
3769 	ASSERT(un != NULL);
3770 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3771 		sd_process_sdconf_table(un);
3772 	}
3773 
3774 	/* check for LSI device */
3775 	sd_is_lsi(un);
3776 
3777 
3778 }
3779 
3780 
3781 /*
3782  *    Function: sd_process_sdconf_file
3783  *
3784  * Description: Use ddi_prop_lookup(9F) to obtain the properties from the
3785  *		driver's config file (ie, sd.conf) and update the driver
3786  *		soft state structure accordingly.
3787  *
3788  *   Arguments: un - driver soft state (unit) structure
3789  *
3790  * Return Code: SD_SUCCESS - The properties were successfully set according
3791  *			     to the driver configuration file.
3792  *		SD_FAILURE - The driver config list was not obtained or
3793  *			     there was no vid/pid match. This indicates that
3794  *			     the static config table should be used.
3795  *
3796  * The config file has a property, "sd-config-list". Currently we support
3797  * two kinds of formats. For both formats, the value of this property
3798  * is a list of duplets:
3799  *
3800  *  sd-config-list=
3801  *	<duplet>,
3802  *	[,<duplet>]*;
3803  *
3804  * For the improved format, where
3805  *
3806  *     <duplet>:= "<vid+pid>","<tunable-list>"
3807  *
3808  * and
3809  *
3810  *     <tunable-list>:=   <tunable> [, <tunable> ]*;
3811  *     <tunable> =        <name> : <value>
3812  *
3813  * The <vid+pid> is the string that is returned by the target device on a
3814  * SCSI inquiry command, the <tunable-list> contains one or more tunables
3815  * to apply to all target devices with the specified <vid+pid>.
3816  *
3817  * Each <tunable> is a "<name> : <value>" pair.
3818  *
3819  * For the old format, the structure of each duplet is as follows:
3820  *
3821  *  <duplet>:= "<vid+pid>","<data-property-name_list>"
3822  *
3823  * The first entry of the duplet is the device ID string (the concatenated
3824  * vid & pid; not to be confused with a device_id).  This is defined in
3825  * the same way as in the sd_disk_table.
3826  *
3827  * The second part of the duplet is a string that identifies a
3828  * data-property-name-list. The data-property-name-list is defined as
3829  * follows:
3830  *
3831  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3832  *
3833  * The syntax of <data-property-name> depends on the <version> field.
3834  *
3835  * If version = SD_CONF_VERSION_1 we have the following syntax:
3836  *
3837  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3838  *
3839  * where the prop0 value will be used to set prop0 if bit0 set in the
3840  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3841  *
3842  */
3843 
3844 static int
3845 sd_process_sdconf_file(struct sd_lun *un)
3846 {
3847 	char	**config_list = NULL;
3848 	uint_t	nelements;
3849 	char	*vidptr;
3850 	int	vidlen;
3851 	char	*dnlist_ptr;
3852 	char	*dataname_ptr;
3853 	char	*dataname_lasts;
3854 	int	*data_list = NULL;
3855 	uint_t	data_list_len;
3856 	int	rval = SD_FAILURE;
3857 	int	i;
3858 
3859 	ASSERT(un != NULL);
3860 
3861 	/* Obtain the configuration list associated with the .conf file */
3862 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, SD_DEVINFO(un),
3863 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, sd_config_list,
3864 	    &config_list, &nelements) != DDI_PROP_SUCCESS) {
3865 		return (SD_FAILURE);
3866 	}
3867 
3868 	/*
3869 	 * Compare vids in each duplet to the inquiry vid - if a match is
3870 	 * made, get the data value and update the soft state structure
3871 	 * accordingly.
3872 	 *
3873 	 * Each duplet should show as a pair of strings, return SD_FAILURE
3874 	 * otherwise.
3875 	 */
3876 	if (nelements & 1) {
3877 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3878 		    "sd-config-list should show as pairs of strings.\n");
3879 		if (config_list)
3880 			ddi_prop_free(config_list);
3881 		return (SD_FAILURE);
3882 	}
3883 
3884 	for (i = 0; i < nelements; i += 2) {
3885 		/*
3886 		 * Note: The assumption here is that each vid entry is on
3887 		 * a unique line from its associated duplet.
3888 		 */
3889 		vidptr = config_list[i];
3890 		vidlen = (int)strlen(vidptr);
3891 		if ((vidlen == 0) ||
3892 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3893 			continue;
3894 		}
3895 
3896 		/*
3897 		 * dnlist contains 1 or more blank separated
3898 		 * data-property-name entries
3899 		 */
3900 		dnlist_ptr = config_list[i + 1];
3901 
3902 		if (strchr(dnlist_ptr, ':') != NULL) {
3903 			/*
3904 			 * Decode the improved format sd-config-list.
3905 			 */
3906 			sd_nvpair_str_decode(un, dnlist_ptr);
3907 		} else {
3908 			/*
3909 			 * The old format sd-config-list, loop through all
3910 			 * data-property-name entries in the
3911 			 * data-property-name-list
3912 			 * setting the properties for each.
3913 			 */
3914 			for (dataname_ptr = sd_strtok_r(dnlist_ptr, " \t",
3915 			    &dataname_lasts); dataname_ptr != NULL;
3916 			    dataname_ptr = sd_strtok_r(NULL, " \t",
3917 			    &dataname_lasts)) {
3918 				int version;
3919 
3920 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3921 				    "sd_process_sdconf_file: disk:%s, "
3922 				    "data:%s\n", vidptr, dataname_ptr);
3923 
3924 				/* Get the data list */
3925 				if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY,
3926 				    SD_DEVINFO(un), 0, dataname_ptr, &data_list,
3927 				    &data_list_len) != DDI_PROP_SUCCESS) {
3928 					SD_INFO(SD_LOG_ATTACH_DETACH, un,
3929 					    "sd_process_sdconf_file: data "
3930 					    "property (%s) has no value\n",
3931 					    dataname_ptr);
3932 					continue;
3933 				}
3934 
3935 				version = data_list[0];
3936 
3937 				if (version == SD_CONF_VERSION_1) {
3938 					sd_tunables values;
3939 
3940 					/* Set the properties */
3941 					if (sd_chk_vers1_data(un, data_list[1],
3942 					    &data_list[2], data_list_len,
3943 					    dataname_ptr) == SD_SUCCESS) {
3944 						sd_get_tunables_from_conf(un,
3945 						    data_list[1], &data_list[2],
3946 						    &values);
3947 						sd_set_vers1_properties(un,
3948 						    data_list[1], &values);
3949 						rval = SD_SUCCESS;
3950 					} else {
3951 						rval = SD_FAILURE;
3952 					}
3953 				} else {
3954 					scsi_log(SD_DEVINFO(un), sd_label,
3955 					    CE_WARN, "data property %s version "
3956 					    "0x%x is invalid.",
3957 					    dataname_ptr, version);
3958 					rval = SD_FAILURE;
3959 				}
3960 				if (data_list)
3961 					ddi_prop_free(data_list);
3962 			}
3963 		}
3964 	}
3965 
3966 	/* free up the memory allocated by ddi_prop_lookup_string_array(). */
3967 	if (config_list) {
3968 		ddi_prop_free(config_list);
3969 	}
3970 
3971 	return (rval);
3972 }
3973 
3974 /*
3975  *    Function: sd_nvpair_str_decode()
3976  *
3977  * Description: Parse the improved format sd-config-list to get
3978  *    each entry of tunable, which includes a name-value pair.
3979  *    Then call sd_set_properties() to set the property.
3980  *
3981  *   Arguments: un - driver soft state (unit) structure
3982  *    nvpair_str - the tunable list
3983  */
3984 static void
3985 sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str)
3986 {
3987 	char	*nv, *name, *value, *token;
3988 	char	*nv_lasts, *v_lasts, *x_lasts;
3989 
3990 	for (nv = sd_strtok_r(nvpair_str, ",", &nv_lasts); nv != NULL;
3991 	    nv = sd_strtok_r(NULL, ",", &nv_lasts)) {
3992 		token = sd_strtok_r(nv, ":", &v_lasts);
3993 		name  = sd_strtok_r(token, " \t", &x_lasts);
3994 		token = sd_strtok_r(NULL, ":", &v_lasts);
3995 		value = sd_strtok_r(token, " \t", &x_lasts);
3996 		if (name == NULL || value == NULL) {
3997 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3998 			    "sd_nvpair_str_decode: "
3999 			    "name or value is not valid!\n");
4000 		} else {
4001 			sd_set_properties(un, name, value);
4002 		}
4003 	}
4004 }
4005 
4006 /*
4007  *    Function: sd_strtok_r()
4008  *
4009  * Description: This function uses strpbrk and strspn to break
4010  *    string into tokens on sequentially subsequent calls. Return
4011  *    NULL when no non-separator characters remain. The first
4012  *    argument is NULL for subsequent calls.
4013  */
4014 static char *
4015 sd_strtok_r(char *string, const char *sepset, char **lasts)
4016 {
4017 	char	*q, *r;
4018 
4019 	/* First or subsequent call */
4020 	if (string == NULL)
4021 		string = *lasts;
4022 
4023 	if (string == NULL)
4024 		return (NULL);
4025 
4026 	/* Skip leading separators */
4027 	q = string + strspn(string, sepset);
4028 
4029 	if (*q == '\0')
4030 		return (NULL);
4031 
4032 	if ((r = strpbrk(q, sepset)) == NULL)
4033 		*lasts = NULL;
4034 	else {
4035 		*r = '\0';
4036 		*lasts = r + 1;
4037 	}
4038 	return (q);
4039 }
4040 
4041 /*
4042  *    Function: sd_set_properties()
4043  *
4044  * Description: Set device properties based on the improved
4045  *    format sd-config-list.
4046  *
4047  *   Arguments: un - driver soft state (unit) structure
4048  *    name  - supported tunable name
4049  *    value - tunable value
4050  */
4051 static void
4052 sd_set_properties(struct sd_lun *un, char *name, char *value)
4053 {
4054 	char	*endptr = NULL;
4055 	long	val = 0;
4056 
4057 	if (strcasecmp(name, "cache-nonvolatile") == 0) {
4058 		if (strcasecmp(value, "true") == 0) {
4059 			un->un_f_suppress_cache_flush = TRUE;
4060 		} else if (strcasecmp(value, "false") == 0) {
4061 			un->un_f_suppress_cache_flush = FALSE;
4062 		} else {
4063 			goto value_invalid;
4064 		}
4065 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4066 		    "suppress_cache_flush flag set to %d\n",
4067 		    un->un_f_suppress_cache_flush);
4068 		return;
4069 	}
4070 
4071 	if (strcasecmp(name, "controller-type") == 0) {
4072 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4073 			un->un_ctype = val;
4074 		} else {
4075 			goto value_invalid;
4076 		}
4077 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4078 		    "ctype set to %d\n", un->un_ctype);
4079 		return;
4080 	}
4081 
4082 	if (strcasecmp(name, "delay-busy") == 0) {
4083 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4084 			un->un_busy_timeout = drv_usectohz(val / 1000);
4085 		} else {
4086 			goto value_invalid;
4087 		}
4088 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4089 		    "busy_timeout set to %d\n", un->un_busy_timeout);
4090 		return;
4091 	}
4092 
4093 	if (strcasecmp(name, "disksort") == 0) {
4094 		if (strcasecmp(value, "true") == 0) {
4095 			un->un_f_disksort_disabled = FALSE;
4096 		} else if (strcasecmp(value, "false") == 0) {
4097 			un->un_f_disksort_disabled = TRUE;
4098 		} else {
4099 			goto value_invalid;
4100 		}
4101 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4102 		    "disksort disabled flag set to %d\n",
4103 		    un->un_f_disksort_disabled);
4104 		return;
4105 	}
4106 
4107 	if (strcasecmp(name, "power-condition") == 0) {
4108 		if (strcasecmp(value, "true") == 0) {
4109 			un->un_f_power_condition_disabled = FALSE;
4110 		} else if (strcasecmp(value, "false") == 0) {
4111 			un->un_f_power_condition_disabled = TRUE;
4112 		} else {
4113 			goto value_invalid;
4114 		}
4115 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4116 		    "power condition disabled flag set to %d\n",
4117 		    un->un_f_power_condition_disabled);
4118 		return;
4119 	}
4120 
4121 	if (strcasecmp(name, "timeout-releasereservation") == 0) {
4122 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4123 			un->un_reserve_release_time = val;
4124 		} else {
4125 			goto value_invalid;
4126 		}
4127 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4128 		    "reservation release timeout set to %d\n",
4129 		    un->un_reserve_release_time);
4130 		return;
4131 	}
4132 
4133 	if (strcasecmp(name, "reset-lun") == 0) {
4134 		if (strcasecmp(value, "true") == 0) {
4135 			un->un_f_lun_reset_enabled = TRUE;
4136 		} else if (strcasecmp(value, "false") == 0) {
4137 			un->un_f_lun_reset_enabled = FALSE;
4138 		} else {
4139 			goto value_invalid;
4140 		}
4141 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4142 		    "lun reset enabled flag set to %d\n",
4143 		    un->un_f_lun_reset_enabled);
4144 		return;
4145 	}
4146 
4147 	if (strcasecmp(name, "retries-busy") == 0) {
4148 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4149 			un->un_busy_retry_count = val;
4150 		} else {
4151 			goto value_invalid;
4152 		}
4153 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4154 		    "busy retry count set to %d\n", un->un_busy_retry_count);
4155 		return;
4156 	}
4157 
4158 	if (strcasecmp(name, "retries-timeout") == 0) {
4159 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4160 			un->un_retry_count = val;
4161 		} else {
4162 			goto value_invalid;
4163 		}
4164 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4165 		    "timeout retry count set to %d\n", un->un_retry_count);
4166 		return;
4167 	}
4168 
4169 	if (strcasecmp(name, "retries-notready") == 0) {
4170 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4171 			un->un_notready_retry_count = val;
4172 		} else {
4173 			goto value_invalid;
4174 		}
4175 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4176 		    "notready retry count set to %d\n",
4177 		    un->un_notready_retry_count);
4178 		return;
4179 	}
4180 
4181 	if (strcasecmp(name, "retries-reset") == 0) {
4182 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4183 			un->un_reset_retry_count = val;
4184 		} else {
4185 			goto value_invalid;
4186 		}
4187 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4188 		    "reset retry count set to %d\n",
4189 		    un->un_reset_retry_count);
4190 		return;
4191 	}
4192 
4193 	if (strcasecmp(name, "throttle-max") == 0) {
4194 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4195 			un->un_saved_throttle = un->un_throttle = val;
4196 		} else {
4197 			goto value_invalid;
4198 		}
4199 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4200 		    "throttle set to %d\n", un->un_throttle);
4201 	}
4202 
4203 	if (strcasecmp(name, "throttle-min") == 0) {
4204 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4205 			un->un_min_throttle = val;
4206 		} else {
4207 			goto value_invalid;
4208 		}
4209 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4210 		    "min throttle set to %d\n", un->un_min_throttle);
4211 	}
4212 
4213 	if (strcasecmp(name, "rmw-type") == 0) {
4214 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4215 			un->un_f_rmw_type = val;
4216 		} else {
4217 			goto value_invalid;
4218 		}
4219 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4220 		    "RMW type set to %d\n", un->un_f_rmw_type);
4221 	}
4222 
4223 	/*
4224 	 * Validate the throttle values.
4225 	 * If any of the numbers are invalid, set everything to defaults.
4226 	 */
4227 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4228 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4229 	    (un->un_min_throttle > un->un_throttle)) {
4230 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4231 		un->un_min_throttle = sd_min_throttle;
4232 	}
4233 
4234 	if (strcasecmp(name, "mmc-gesn-polling") == 0) {
4235 		if (strcasecmp(value, "true") == 0) {
4236 			un->un_f_mmc_gesn_polling = TRUE;
4237 		} else if (strcasecmp(value, "false") == 0) {
4238 			un->un_f_mmc_gesn_polling = FALSE;
4239 		} else {
4240 			goto value_invalid;
4241 		}
4242 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4243 		    "mmc-gesn-polling set to %d\n",
4244 		    un->un_f_mmc_gesn_polling);
4245 	}
4246 
4247 	return;
4248 
4249 value_invalid:
4250 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4251 	    "value of prop %s is invalid\n", name);
4252 }
4253 
4254 /*
4255  *    Function: sd_get_tunables_from_conf()
4256  *
4257  *
4258  *    This function reads the data list from the sd.conf file and pulls
4259  *    the values that can have numeric values as arguments and places
4260  *    the values in the appropriate sd_tunables member.
4261  *    Since the order of the data list members varies across platforms
4262  *    This function reads them from the data list in a platform specific
4263  *    order and places them into the correct sd_tunable member that is
4264  *    consistent across all platforms.
4265  */
4266 static void
4267 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
4268     sd_tunables *values)
4269 {
4270 	int i;
4271 	int mask;
4272 
4273 	bzero(values, sizeof (sd_tunables));
4274 
4275 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4276 
4277 		mask = 1 << i;
4278 		if (mask > flags) {
4279 			break;
4280 		}
4281 
4282 		switch (mask & flags) {
4283 		case 0:	/* This mask bit not set in flags */
4284 			continue;
4285 		case SD_CONF_BSET_THROTTLE:
4286 			values->sdt_throttle = data_list[i];
4287 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4288 			    "sd_get_tunables_from_conf: throttle = %d\n",
4289 			    values->sdt_throttle);
4290 			break;
4291 		case SD_CONF_BSET_CTYPE:
4292 			values->sdt_ctype = data_list[i];
4293 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4294 			    "sd_get_tunables_from_conf: ctype = %d\n",
4295 			    values->sdt_ctype);
4296 			break;
4297 		case SD_CONF_BSET_NRR_COUNT:
4298 			values->sdt_not_rdy_retries = data_list[i];
4299 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4300 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
4301 			    values->sdt_not_rdy_retries);
4302 			break;
4303 		case SD_CONF_BSET_BSY_RETRY_COUNT:
4304 			values->sdt_busy_retries = data_list[i];
4305 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4306 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
4307 			    values->sdt_busy_retries);
4308 			break;
4309 		case SD_CONF_BSET_RST_RETRIES:
4310 			values->sdt_reset_retries = data_list[i];
4311 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4312 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
4313 			    values->sdt_reset_retries);
4314 			break;
4315 		case SD_CONF_BSET_RSV_REL_TIME:
4316 			values->sdt_reserv_rel_time = data_list[i];
4317 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4318 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
4319 			    values->sdt_reserv_rel_time);
4320 			break;
4321 		case SD_CONF_BSET_MIN_THROTTLE:
4322 			values->sdt_min_throttle = data_list[i];
4323 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4324 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
4325 			    values->sdt_min_throttle);
4326 			break;
4327 		case SD_CONF_BSET_DISKSORT_DISABLED:
4328 			values->sdt_disk_sort_dis = data_list[i];
4329 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4330 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
4331 			    values->sdt_disk_sort_dis);
4332 			break;
4333 		case SD_CONF_BSET_LUN_RESET_ENABLED:
4334 			values->sdt_lun_reset_enable = data_list[i];
4335 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4336 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
4337 			    "\n", values->sdt_lun_reset_enable);
4338 			break;
4339 		case SD_CONF_BSET_CACHE_IS_NV:
4340 			values->sdt_suppress_cache_flush = data_list[i];
4341 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4342 			    "sd_get_tunables_from_conf: \
4343 			    suppress_cache_flush = %d"
4344 			    "\n", values->sdt_suppress_cache_flush);
4345 			break;
4346 		case SD_CONF_BSET_PC_DISABLED:
4347 			values->sdt_disk_sort_dis = data_list[i];
4348 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4349 			    "sd_get_tunables_from_conf: power_condition_dis = "
4350 			    "%d\n", values->sdt_power_condition_dis);
4351 			break;
4352 		}
4353 	}
4354 }
4355 
4356 /*
4357  *    Function: sd_process_sdconf_table
4358  *
4359  * Description: Search the static configuration table for a match on the
4360  *		inquiry vid/pid and update the driver soft state structure
4361  *		according to the table property values for the device.
4362  *
4363  *		The form of a configuration table entry is:
4364  *		  <vid+pid>,<flags>,<property-data>
4365  *		  "SEAGATE ST42400N",1,0x40000,
4366  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
4367  *
4368  *   Arguments: un - driver soft state (unit) structure
4369  */
4370 
4371 static void
4372 sd_process_sdconf_table(struct sd_lun *un)
4373 {
4374 	char	*id = NULL;
4375 	int	table_index;
4376 	int	idlen;
4377 
4378 	ASSERT(un != NULL);
4379 	for (table_index = 0; table_index < sd_disk_table_size;
4380 	    table_index++) {
4381 		id = sd_disk_table[table_index].device_id;
4382 		idlen = strlen(id);
4383 		if (idlen == 0) {
4384 			continue;
4385 		}
4386 
4387 		/*
4388 		 * The static configuration table currently does not
4389 		 * implement version 10 properties. Additionally,
4390 		 * multiple data-property-name entries are not
4391 		 * implemented in the static configuration table.
4392 		 */
4393 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4394 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4395 			    "sd_process_sdconf_table: disk %s\n", id);
4396 			sd_set_vers1_properties(un,
4397 			    sd_disk_table[table_index].flags,
4398 			    sd_disk_table[table_index].properties);
4399 			break;
4400 		}
4401 	}
4402 }
4403 
4404 
4405 /*
4406  *    Function: sd_sdconf_id_match
4407  *
4408  * Description: This local function implements a case sensitive vid/pid
4409  *		comparison as well as the boundary cases of wild card and
4410  *		multiple blanks.
4411  *
4412  *		Note: An implicit assumption made here is that the scsi
4413  *		inquiry structure will always keep the vid, pid and
4414  *		revision strings in consecutive sequence, so they can be
4415  *		read as a single string. If this assumption is not the
4416  *		case, a separate string, to be used for the check, needs
4417  *		to be built with these strings concatenated.
4418  *
4419  *   Arguments: un - driver soft state (unit) structure
4420  *		id - table or config file vid/pid
4421  *		idlen  - length of the vid/pid (bytes)
4422  *
4423  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4424  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4425  */
4426 
4427 static int
4428 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
4429 {
4430 	struct scsi_inquiry	*sd_inq;
4431 	int 			rval = SD_SUCCESS;
4432 
4433 	ASSERT(un != NULL);
4434 	sd_inq = un->un_sd->sd_inq;
4435 	ASSERT(id != NULL);
4436 
4437 	/*
4438 	 * We use the inq_vid as a pointer to a buffer containing the
4439 	 * vid and pid and use the entire vid/pid length of the table
4440 	 * entry for the comparison. This works because the inq_pid
4441 	 * data member follows inq_vid in the scsi_inquiry structure.
4442 	 */
4443 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
4444 		/*
4445 		 * The user id string is compared to the inquiry vid/pid
4446 		 * using a case insensitive comparison and ignoring
4447 		 * multiple spaces.
4448 		 */
4449 		rval = sd_blank_cmp(un, id, idlen);
4450 		if (rval != SD_SUCCESS) {
4451 			/*
4452 			 * User id strings that start and end with a "*"
4453 			 * are a special case. These do not have a
4454 			 * specific vendor, and the product string can
4455 			 * appear anywhere in the 16 byte PID portion of
4456 			 * the inquiry data. This is a simple strstr()
4457 			 * type search for the user id in the inquiry data.
4458 			 */
4459 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
4460 				char	*pidptr = &id[1];
4461 				int	i;
4462 				int	j;
4463 				int	pidstrlen = idlen - 2;
4464 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
4465 				    pidstrlen;
4466 
4467 				if (j < 0) {
4468 					return (SD_FAILURE);
4469 				}
4470 				for (i = 0; i < j; i++) {
4471 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
4472 					    pidptr, pidstrlen) == 0) {
4473 						rval = SD_SUCCESS;
4474 						break;
4475 					}
4476 				}
4477 			}
4478 		}
4479 	}
4480 	return (rval);
4481 }
4482 
4483 
4484 /*
4485  *    Function: sd_blank_cmp
4486  *
4487  * Description: If the id string starts and ends with a space, treat
4488  *		multiple consecutive spaces as equivalent to a single
4489  *		space. For example, this causes a sd_disk_table entry
4490  *		of " NEC CDROM " to match a device's id string of
4491  *		"NEC       CDROM".
4492  *
4493  *		Note: The success exit condition for this routine is if
4494  *		the pointer to the table entry is '\0' and the cnt of
4495  *		the inquiry length is zero. This will happen if the inquiry
4496  *		string returned by the device is padded with spaces to be
4497  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
4498  *		SCSI spec states that the inquiry string is to be padded with
4499  *		spaces.
4500  *
4501  *   Arguments: un - driver soft state (unit) structure
4502  *		id - table or config file vid/pid
4503  *		idlen  - length of the vid/pid (bytes)
4504  *
4505  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4506  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4507  */
4508 
4509 static int
4510 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
4511 {
4512 	char		*p1;
4513 	char		*p2;
4514 	int		cnt;
4515 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
4516 	    sizeof (SD_INQUIRY(un)->inq_pid);
4517 
4518 	ASSERT(un != NULL);
4519 	p2 = un->un_sd->sd_inq->inq_vid;
4520 	ASSERT(id != NULL);
4521 	p1 = id;
4522 
4523 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
4524 		/*
4525 		 * Note: string p1 is terminated by a NUL but string p2
4526 		 * isn't.  The end of p2 is determined by cnt.
4527 		 */
4528 		for (;;) {
4529 			/* skip over any extra blanks in both strings */
4530 			while ((*p1 != '\0') && (*p1 == ' ')) {
4531 				p1++;
4532 			}
4533 			while ((cnt != 0) && (*p2 == ' ')) {
4534 				p2++;
4535 				cnt--;
4536 			}
4537 
4538 			/* compare the two strings */
4539 			if ((cnt == 0) ||
4540 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
4541 				break;
4542 			}
4543 			while ((cnt > 0) &&
4544 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
4545 				p1++;
4546 				p2++;
4547 				cnt--;
4548 			}
4549 		}
4550 	}
4551 
4552 	/* return SD_SUCCESS if both strings match */
4553 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
4554 }
4555 
4556 
4557 /*
4558  *    Function: sd_chk_vers1_data
4559  *
4560  * Description: Verify the version 1 device properties provided by the
4561  *		user via the configuration file
4562  *
4563  *   Arguments: un	     - driver soft state (unit) structure
4564  *		flags	     - integer mask indicating properties to be set
4565  *		prop_list    - integer list of property values
4566  *		list_len     - number of the elements
4567  *
4568  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
4569  *		SD_FAILURE - Indicates the user provided data is invalid
4570  */
4571 
4572 static int
4573 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
4574     int list_len, char *dataname_ptr)
4575 {
4576 	int i;
4577 	int mask = 1;
4578 	int index = 0;
4579 
4580 	ASSERT(un != NULL);
4581 
4582 	/* Check for a NULL property name and list */
4583 	if (dataname_ptr == NULL) {
4584 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4585 		    "sd_chk_vers1_data: NULL data property name.");
4586 		return (SD_FAILURE);
4587 	}
4588 	if (prop_list == NULL) {
4589 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4590 		    "sd_chk_vers1_data: %s NULL data property list.",
4591 		    dataname_ptr);
4592 		return (SD_FAILURE);
4593 	}
4594 
4595 	/* Display a warning if undefined bits are set in the flags */
4596 	if (flags & ~SD_CONF_BIT_MASK) {
4597 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4598 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
4599 		    "Properties not set.",
4600 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
4601 		return (SD_FAILURE);
4602 	}
4603 
4604 	/*
4605 	 * Verify the length of the list by identifying the highest bit set
4606 	 * in the flags and validating that the property list has a length
4607 	 * up to the index of this bit.
4608 	 */
4609 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4610 		if (flags & mask) {
4611 			index++;
4612 		}
4613 		mask = 1 << i;
4614 	}
4615 	if (list_len < (index + 2)) {
4616 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4617 		    "sd_chk_vers1_data: "
4618 		    "Data property list %s size is incorrect. "
4619 		    "Properties not set.", dataname_ptr);
4620 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
4621 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
4622 		return (SD_FAILURE);
4623 	}
4624 	return (SD_SUCCESS);
4625 }
4626 
4627 
4628 /*
4629  *    Function: sd_set_vers1_properties
4630  *
4631  * Description: Set version 1 device properties based on a property list
4632  *		retrieved from the driver configuration file or static
4633  *		configuration table. Version 1 properties have the format:
4634  *
4635  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
4636  *
4637  *		where the prop0 value will be used to set prop0 if bit0
4638  *		is set in the flags
4639  *
4640  *   Arguments: un	     - driver soft state (unit) structure
4641  *		flags	     - integer mask indicating properties to be set
4642  *		prop_list    - integer list of property values
4643  */
4644 
4645 static void
4646 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4647 {
4648 	ASSERT(un != NULL);
4649 
4650 	/*
4651 	 * Set the flag to indicate cache is to be disabled. An attempt
4652 	 * to disable the cache via sd_cache_control() will be made
4653 	 * later during attach once the basic initialization is complete.
4654 	 */
4655 	if (flags & SD_CONF_BSET_NOCACHE) {
4656 		un->un_f_opt_disable_cache = TRUE;
4657 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4658 		    "sd_set_vers1_properties: caching disabled flag set\n");
4659 	}
4660 
4661 	/* CD-specific configuration parameters */
4662 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4663 		un->un_f_cfg_playmsf_bcd = TRUE;
4664 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4665 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4666 	}
4667 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4668 		un->un_f_cfg_readsub_bcd = TRUE;
4669 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4670 		    "sd_set_vers1_properties: readsub_bcd set\n");
4671 	}
4672 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4673 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4674 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4675 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4676 	}
4677 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4678 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4679 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4680 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4681 	}
4682 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4683 		un->un_f_cfg_no_read_header = TRUE;
4684 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4685 		    "sd_set_vers1_properties: no_read_header set\n");
4686 	}
4687 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4688 		un->un_f_cfg_read_cd_xd4 = TRUE;
4689 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4690 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4691 	}
4692 
4693 	/* Support for devices which do not have valid/unique serial numbers */
4694 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4695 		un->un_f_opt_fab_devid = TRUE;
4696 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4697 		    "sd_set_vers1_properties: fab_devid bit set\n");
4698 	}
4699 
4700 	/* Support for user throttle configuration */
4701 	if (flags & SD_CONF_BSET_THROTTLE) {
4702 		ASSERT(prop_list != NULL);
4703 		un->un_saved_throttle = un->un_throttle =
4704 		    prop_list->sdt_throttle;
4705 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4706 		    "sd_set_vers1_properties: throttle set to %d\n",
4707 		    prop_list->sdt_throttle);
4708 	}
4709 
4710 	/* Set the per disk retry count according to the conf file or table. */
4711 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4712 		ASSERT(prop_list != NULL);
4713 		if (prop_list->sdt_not_rdy_retries) {
4714 			un->un_notready_retry_count =
4715 			    prop_list->sdt_not_rdy_retries;
4716 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4717 			    "sd_set_vers1_properties: not ready retry count"
4718 			    " set to %d\n", un->un_notready_retry_count);
4719 		}
4720 	}
4721 
4722 	/* The controller type is reported for generic disk driver ioctls */
4723 	if (flags & SD_CONF_BSET_CTYPE) {
4724 		ASSERT(prop_list != NULL);
4725 		switch (prop_list->sdt_ctype) {
4726 		case CTYPE_CDROM:
4727 			un->un_ctype = prop_list->sdt_ctype;
4728 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4729 			    "sd_set_vers1_properties: ctype set to "
4730 			    "CTYPE_CDROM\n");
4731 			break;
4732 		case CTYPE_CCS:
4733 			un->un_ctype = prop_list->sdt_ctype;
4734 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4735 			    "sd_set_vers1_properties: ctype set to "
4736 			    "CTYPE_CCS\n");
4737 			break;
4738 		case CTYPE_ROD:		/* RW optical */
4739 			un->un_ctype = prop_list->sdt_ctype;
4740 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4741 			    "sd_set_vers1_properties: ctype set to "
4742 			    "CTYPE_ROD\n");
4743 			break;
4744 		default:
4745 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4746 			    "sd_set_vers1_properties: Could not set "
4747 			    "invalid ctype value (%d)",
4748 			    prop_list->sdt_ctype);
4749 		}
4750 	}
4751 
4752 	/* Purple failover timeout */
4753 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4754 		ASSERT(prop_list != NULL);
4755 		un->un_busy_retry_count =
4756 		    prop_list->sdt_busy_retries;
4757 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4758 		    "sd_set_vers1_properties: "
4759 		    "busy retry count set to %d\n",
4760 		    un->un_busy_retry_count);
4761 	}
4762 
4763 	/* Purple reset retry count */
4764 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4765 		ASSERT(prop_list != NULL);
4766 		un->un_reset_retry_count =
4767 		    prop_list->sdt_reset_retries;
4768 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4769 		    "sd_set_vers1_properties: "
4770 		    "reset retry count set to %d\n",
4771 		    un->un_reset_retry_count);
4772 	}
4773 
4774 	/* Purple reservation release timeout */
4775 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4776 		ASSERT(prop_list != NULL);
4777 		un->un_reserve_release_time =
4778 		    prop_list->sdt_reserv_rel_time;
4779 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4780 		    "sd_set_vers1_properties: "
4781 		    "reservation release timeout set to %d\n",
4782 		    un->un_reserve_release_time);
4783 	}
4784 
4785 	/*
4786 	 * Driver flag telling the driver to verify that no commands are pending
4787 	 * for a device before issuing a Test Unit Ready. This is a workaround
4788 	 * for a firmware bug in some Seagate eliteI drives.
4789 	 */
4790 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4791 		un->un_f_cfg_tur_check = TRUE;
4792 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4793 		    "sd_set_vers1_properties: tur queue check set\n");
4794 	}
4795 
4796 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4797 		un->un_min_throttle = prop_list->sdt_min_throttle;
4798 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4799 		    "sd_set_vers1_properties: min throttle set to %d\n",
4800 		    un->un_min_throttle);
4801 	}
4802 
4803 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4804 		un->un_f_disksort_disabled =
4805 		    (prop_list->sdt_disk_sort_dis != 0) ?
4806 		    TRUE : FALSE;
4807 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4808 		    "sd_set_vers1_properties: disksort disabled "
4809 		    "flag set to %d\n",
4810 		    prop_list->sdt_disk_sort_dis);
4811 	}
4812 
4813 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4814 		un->un_f_lun_reset_enabled =
4815 		    (prop_list->sdt_lun_reset_enable != 0) ?
4816 		    TRUE : FALSE;
4817 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4818 		    "sd_set_vers1_properties: lun reset enabled "
4819 		    "flag set to %d\n",
4820 		    prop_list->sdt_lun_reset_enable);
4821 	}
4822 
4823 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4824 		un->un_f_suppress_cache_flush =
4825 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4826 		    TRUE : FALSE;
4827 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4828 		    "sd_set_vers1_properties: suppress_cache_flush "
4829 		    "flag set to %d\n",
4830 		    prop_list->sdt_suppress_cache_flush);
4831 	}
4832 
4833 	if (flags & SD_CONF_BSET_PC_DISABLED) {
4834 		un->un_f_power_condition_disabled =
4835 		    (prop_list->sdt_power_condition_dis != 0) ?
4836 		    TRUE : FALSE;
4837 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4838 		    "sd_set_vers1_properties: power_condition_disabled "
4839 		    "flag set to %d\n",
4840 		    prop_list->sdt_power_condition_dis);
4841 	}
4842 
4843 	/*
4844 	 * Validate the throttle values.
4845 	 * If any of the numbers are invalid, set everything to defaults.
4846 	 */
4847 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4848 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4849 	    (un->un_min_throttle > un->un_throttle)) {
4850 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4851 		un->un_min_throttle = sd_min_throttle;
4852 	}
4853 }
4854 
4855 /*
4856  *   Function: sd_is_lsi()
4857  *
4858  *   Description: Check for lsi devices, step through the static device
4859  *	table to match vid/pid.
4860  *
4861  *   Args: un - ptr to sd_lun
4862  *
4863  *   Notes:  When creating new LSI property, need to add the new LSI property
4864  *		to this function.
4865  */
4866 static void
4867 sd_is_lsi(struct sd_lun *un)
4868 {
4869 	char	*id = NULL;
4870 	int	table_index;
4871 	int	idlen;
4872 	void	*prop;
4873 
4874 	ASSERT(un != NULL);
4875 	for (table_index = 0; table_index < sd_disk_table_size;
4876 	    table_index++) {
4877 		id = sd_disk_table[table_index].device_id;
4878 		idlen = strlen(id);
4879 		if (idlen == 0) {
4880 			continue;
4881 		}
4882 
4883 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4884 			prop = sd_disk_table[table_index].properties;
4885 			if (prop == &lsi_properties ||
4886 			    prop == &lsi_oem_properties ||
4887 			    prop == &lsi_properties_scsi ||
4888 			    prop == &symbios_properties) {
4889 				un->un_f_cfg_is_lsi = TRUE;
4890 			}
4891 			break;
4892 		}
4893 	}
4894 }
4895 
4896 /*
4897  *    Function: sd_get_physical_geometry
4898  *
4899  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4900  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4901  *		target, and use this information to initialize the physical
4902  *		geometry cache specified by pgeom_p.
4903  *
4904  *		MODE SENSE is an optional command, so failure in this case
4905  *		does not necessarily denote an error. We want to use the
4906  *		MODE SENSE commands to derive the physical geometry of the
4907  *		device, but if either command fails, the logical geometry is
4908  *		used as the fallback for disk label geometry in cmlb.
4909  *
4910  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4911  *		have already been initialized for the current target and
4912  *		that the current values be passed as args so that we don't
4913  *		end up ever trying to use -1 as a valid value. This could
4914  *		happen if either value is reset while we're not holding
4915  *		the mutex.
4916  *
4917  *   Arguments: un - driver soft state (unit) structure
4918  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4919  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4920  *			to use the USCSI "direct" chain and bypass the normal
4921  *			command waitq.
4922  *
4923  *     Context: Kernel thread only (can sleep).
4924  */
4925 
4926 static int
4927 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4928 	diskaddr_t capacity, int lbasize, int path_flag)
4929 {
4930 	struct	mode_format	*page3p;
4931 	struct	mode_geometry	*page4p;
4932 	struct	mode_header	*headerp;
4933 	int	sector_size;
4934 	int	nsect;
4935 	int	nhead;
4936 	int	ncyl;
4937 	int	intrlv;
4938 	int	spc;
4939 	diskaddr_t	modesense_capacity;
4940 	int	rpm;
4941 	int	bd_len;
4942 	int	mode_header_length;
4943 	uchar_t	*p3bufp;
4944 	uchar_t	*p4bufp;
4945 	int	cdbsize;
4946 	int 	ret = EIO;
4947 	sd_ssc_t *ssc;
4948 	int	status;
4949 
4950 	ASSERT(un != NULL);
4951 
4952 	if (lbasize == 0) {
4953 		if (ISCD(un)) {
4954 			lbasize = 2048;
4955 		} else {
4956 			lbasize = un->un_sys_blocksize;
4957 		}
4958 	}
4959 	pgeom_p->g_secsize = (unsigned short)lbasize;
4960 
4961 	/*
4962 	 * If the unit is a cd/dvd drive MODE SENSE page three
4963 	 * and MODE SENSE page four are reserved (see SBC spec
4964 	 * and MMC spec). To prevent soft errors just return
4965 	 * using the default LBA size.
4966 	 */
4967 	if (ISCD(un))
4968 		return (ret);
4969 
4970 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4971 
4972 	/*
4973 	 * Retrieve MODE SENSE page 3 - Format Device Page
4974 	 */
4975 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4976 	ssc = sd_ssc_init(un);
4977 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p3bufp,
4978 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag);
4979 	if (status != 0) {
4980 		SD_ERROR(SD_LOG_COMMON, un,
4981 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4982 		goto page3_exit;
4983 	}
4984 
4985 	/*
4986 	 * Determine size of Block Descriptors in order to locate the mode
4987 	 * page data.  ATAPI devices return 0, SCSI devices should return
4988 	 * MODE_BLK_DESC_LENGTH.
4989 	 */
4990 	headerp = (struct mode_header *)p3bufp;
4991 	if (un->un_f_cfg_is_atapi == TRUE) {
4992 		struct mode_header_grp2 *mhp =
4993 		    (struct mode_header_grp2 *)headerp;
4994 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4995 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4996 	} else {
4997 		mode_header_length = MODE_HEADER_LENGTH;
4998 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4999 	}
5000 
5001 	if (bd_len > MODE_BLK_DESC_LENGTH) {
5002 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5003 		    "sd_get_physical_geometry: received unexpected bd_len "
5004 		    "of %d, page3\n", bd_len);
5005 		status = EIO;
5006 		goto page3_exit;
5007 	}
5008 
5009 	page3p = (struct mode_format *)
5010 	    ((caddr_t)headerp + mode_header_length + bd_len);
5011 
5012 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
5013 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5014 		    "sd_get_physical_geometry: mode sense pg3 code mismatch "
5015 		    "%d\n", page3p->mode_page.code);
5016 		status = EIO;
5017 		goto page3_exit;
5018 	}
5019 
5020 	/*
5021 	 * Use this physical geometry data only if BOTH MODE SENSE commands
5022 	 * complete successfully; otherwise, revert to the logical geometry.
5023 	 * So, we need to save everything in temporary variables.
5024 	 */
5025 	sector_size = BE_16(page3p->data_bytes_sect);
5026 
5027 	/*
5028 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
5029 	 */
5030 	if (sector_size == 0) {
5031 		sector_size = un->un_sys_blocksize;
5032 	} else {
5033 		sector_size &= ~(un->un_sys_blocksize - 1);
5034 	}
5035 
5036 	nsect  = BE_16(page3p->sect_track);
5037 	intrlv = BE_16(page3p->interleave);
5038 
5039 	SD_INFO(SD_LOG_COMMON, un,
5040 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
5041 	SD_INFO(SD_LOG_COMMON, un,
5042 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
5043 	    page3p->mode_page.code, nsect, sector_size);
5044 	SD_INFO(SD_LOG_COMMON, un,
5045 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
5046 	    BE_16(page3p->track_skew),
5047 	    BE_16(page3p->cylinder_skew));
5048 
5049 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5050 
5051 	/*
5052 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
5053 	 */
5054 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
5055 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p4bufp,
5056 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag);
5057 	if (status != 0) {
5058 		SD_ERROR(SD_LOG_COMMON, un,
5059 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
5060 		goto page4_exit;
5061 	}
5062 
5063 	/*
5064 	 * Determine size of Block Descriptors in order to locate the mode
5065 	 * page data.  ATAPI devices return 0, SCSI devices should return
5066 	 * MODE_BLK_DESC_LENGTH.
5067 	 */
5068 	headerp = (struct mode_header *)p4bufp;
5069 	if (un->un_f_cfg_is_atapi == TRUE) {
5070 		struct mode_header_grp2 *mhp =
5071 		    (struct mode_header_grp2 *)headerp;
5072 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
5073 	} else {
5074 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
5075 	}
5076 
5077 	if (bd_len > MODE_BLK_DESC_LENGTH) {
5078 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5079 		    "sd_get_physical_geometry: received unexpected bd_len of "
5080 		    "%d, page4\n", bd_len);
5081 		status = EIO;
5082 		goto page4_exit;
5083 	}
5084 
5085 	page4p = (struct mode_geometry *)
5086 	    ((caddr_t)headerp + mode_header_length + bd_len);
5087 
5088 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
5089 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5090 		    "sd_get_physical_geometry: mode sense pg4 code mismatch "
5091 		    "%d\n", page4p->mode_page.code);
5092 		status = EIO;
5093 		goto page4_exit;
5094 	}
5095 
5096 	/*
5097 	 * Stash the data now, after we know that both commands completed.
5098 	 */
5099 
5100 
5101 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
5102 	spc   = nhead * nsect;
5103 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
5104 	rpm   = BE_16(page4p->rpm);
5105 
5106 	modesense_capacity = spc * ncyl;
5107 
5108 	SD_INFO(SD_LOG_COMMON, un,
5109 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
5110 	SD_INFO(SD_LOG_COMMON, un,
5111 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
5112 	SD_INFO(SD_LOG_COMMON, un,
5113 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
5114 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
5115 	    (void *)pgeom_p, capacity);
5116 
5117 	/*
5118 	 * Compensate if the drive's geometry is not rectangular, i.e.,
5119 	 * the product of C * H * S returned by MODE SENSE >= that returned
5120 	 * by read capacity. This is an idiosyncrasy of the original x86
5121 	 * disk subsystem.
5122 	 */
5123 	if (modesense_capacity >= capacity) {
5124 		SD_INFO(SD_LOG_COMMON, un,
5125 		    "sd_get_physical_geometry: adjusting acyl; "
5126 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
5127 		    (modesense_capacity - capacity + spc - 1) / spc);
5128 		if (sector_size != 0) {
5129 			/* 1243403: NEC D38x7 drives don't support sec size */
5130 			pgeom_p->g_secsize = (unsigned short)sector_size;
5131 		}
5132 		pgeom_p->g_nsect    = (unsigned short)nsect;
5133 		pgeom_p->g_nhead    = (unsigned short)nhead;
5134 		pgeom_p->g_capacity = capacity;
5135 		pgeom_p->g_acyl	    =
5136 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
5137 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
5138 	}
5139 
5140 	pgeom_p->g_rpm    = (unsigned short)rpm;
5141 	pgeom_p->g_intrlv = (unsigned short)intrlv;
5142 	ret = 0;
5143 
5144 	SD_INFO(SD_LOG_COMMON, un,
5145 	    "sd_get_physical_geometry: mode sense geometry:\n");
5146 	SD_INFO(SD_LOG_COMMON, un,
5147 	    "   nsect: %d; sector size: %d; interlv: %d\n",
5148 	    nsect, sector_size, intrlv);
5149 	SD_INFO(SD_LOG_COMMON, un,
5150 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
5151 	    nhead, ncyl, rpm, modesense_capacity);
5152 	SD_INFO(SD_LOG_COMMON, un,
5153 	    "sd_get_physical_geometry: (cached)\n");
5154 	SD_INFO(SD_LOG_COMMON, un,
5155 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5156 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
5157 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
5158 	SD_INFO(SD_LOG_COMMON, un,
5159 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
5160 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
5161 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
5162 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5163 
5164 page4_exit:
5165 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
5166 
5167 page3_exit:
5168 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
5169 
5170 	if (status != 0) {
5171 		if (status == EIO) {
5172 			/*
5173 			 * Some disks do not support mode sense(6), we
5174 			 * should ignore this kind of error(sense key is
5175 			 * 0x5 - illegal request).
5176 			 */
5177 			uint8_t *sensep;
5178 			int senlen;
5179 
5180 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
5181 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
5182 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
5183 
5184 			if (senlen > 0 &&
5185 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
5186 				sd_ssc_assessment(ssc,
5187 				    SD_FMT_IGNORE_COMPROMISE);
5188 			} else {
5189 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
5190 			}
5191 		} else {
5192 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5193 		}
5194 	}
5195 	sd_ssc_fini(ssc);
5196 	return (ret);
5197 }
5198 
5199 /*
5200  *    Function: sd_get_virtual_geometry
5201  *
5202  * Description: Ask the controller to tell us about the target device.
5203  *
5204  *   Arguments: un - pointer to softstate
5205  *		capacity - disk capacity in #blocks
5206  *		lbasize - disk block size in bytes
5207  *
5208  *     Context: Kernel thread only
5209  */
5210 
5211 static int
5212 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
5213     diskaddr_t capacity, int lbasize)
5214 {
5215 	uint_t	geombuf;
5216 	int	spc;
5217 
5218 	ASSERT(un != NULL);
5219 
5220 	/* Set sector size, and total number of sectors */
5221 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
5222 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
5223 
5224 	/* Let the HBA tell us its geometry */
5225 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
5226 
5227 	/* A value of -1 indicates an undefined "geometry" property */
5228 	if (geombuf == (-1)) {
5229 		return (EINVAL);
5230 	}
5231 
5232 	/* Initialize the logical geometry cache. */
5233 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
5234 	lgeom_p->g_nsect   = geombuf & 0xffff;
5235 	lgeom_p->g_secsize = un->un_sys_blocksize;
5236 
5237 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
5238 
5239 	/*
5240 	 * Note: The driver originally converted the capacity value from
5241 	 * target blocks to system blocks. However, the capacity value passed
5242 	 * to this routine is already in terms of system blocks (this scaling
5243 	 * is done when the READ CAPACITY command is issued and processed).
5244 	 * This 'error' may have gone undetected because the usage of g_ncyl
5245 	 * (which is based upon g_capacity) is very limited within the driver
5246 	 */
5247 	lgeom_p->g_capacity = capacity;
5248 
5249 	/*
5250 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
5251 	 * hba may return zero values if the device has been removed.
5252 	 */
5253 	if (spc == 0) {
5254 		lgeom_p->g_ncyl = 0;
5255 	} else {
5256 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
5257 	}
5258 	lgeom_p->g_acyl = 0;
5259 
5260 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
5261 	return (0);
5262 
5263 }
5264 /*
5265  *    Function: sd_update_block_info
5266  *
5267  * Description: Calculate a byte count to sector count bitshift value
5268  *		from sector size.
5269  *
5270  *   Arguments: un: unit struct.
5271  *		lbasize: new target sector size
5272  *		capacity: new target capacity, ie. block count
5273  *
5274  *     Context: Kernel thread context
5275  */
5276 
5277 static void
5278 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
5279 {
5280 	if (lbasize != 0) {
5281 		un->un_tgt_blocksize = lbasize;
5282 		un->un_f_tgt_blocksize_is_valid = TRUE;
5283 		if (!un->un_f_has_removable_media) {
5284 			un->un_sys_blocksize = lbasize;
5285 		}
5286 	}
5287 
5288 	if (capacity != 0) {
5289 		un->un_blockcount		= capacity;
5290 		un->un_f_blockcount_is_valid	= TRUE;
5291 	}
5292 }
5293 
5294 
5295 /*
5296  *    Function: sd_register_devid
5297  *
5298  * Description: This routine will obtain the device id information from the
5299  *		target, obtain the serial number, and register the device
5300  *		id with the ddi framework.
5301  *
5302  *   Arguments: devi - the system's dev_info_t for the device.
5303  *		un - driver soft state (unit) structure
5304  *		reservation_flag - indicates if a reservation conflict
5305  *		occurred during attach
5306  *
5307  *     Context: Kernel Thread
5308  */
5309 static void
5310 sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi, int reservation_flag)
5311 {
5312 	int		rval		= 0;
5313 	uchar_t		*inq80		= NULL;
5314 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5315 	size_t		inq80_resid	= 0;
5316 	uchar_t		*inq83		= NULL;
5317 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5318 	size_t		inq83_resid	= 0;
5319 	int		dlen, len;
5320 	char		*sn;
5321 	struct sd_lun	*un;
5322 
5323 	ASSERT(ssc != NULL);
5324 	un = ssc->ssc_un;
5325 	ASSERT(un != NULL);
5326 	ASSERT(mutex_owned(SD_MUTEX(un)));
5327 	ASSERT((SD_DEVINFO(un)) == devi);
5328 
5329 
5330 	/*
5331 	 * We check the availability of the World Wide Name (0x83) and Unit
5332 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5333 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5334 	 * 0x83 is available, that is the best choice.  Our next choice is
5335 	 * 0x80.  If neither are available, we munge the devid from the device
5336 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5337 	 * to fabricate a devid for non-Sun qualified disks.
5338 	 */
5339 	if (sd_check_vpd_page_support(ssc) == 0) {
5340 		/* collect page 80 data if available */
5341 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5342 
5343 			mutex_exit(SD_MUTEX(un));
5344 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5345 
5346 			rval = sd_send_scsi_INQUIRY(ssc, inq80, inq80_len,
5347 			    0x01, 0x80, &inq80_resid);
5348 
5349 			if (rval != 0) {
5350 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5351 				kmem_free(inq80, inq80_len);
5352 				inq80 = NULL;
5353 				inq80_len = 0;
5354 			} else if (ddi_prop_exists(
5355 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
5356 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
5357 			    INQUIRY_SERIAL_NO) == 0) {
5358 				/*
5359 				 * If we don't already have a serial number
5360 				 * property, do quick verify of data returned
5361 				 * and define property.
5362 				 */
5363 				dlen = inq80_len - inq80_resid;
5364 				len = (size_t)inq80[3];
5365 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
5366 					/*
5367 					 * Ensure sn termination, skip leading
5368 					 * blanks, and create property
5369 					 * 'inquiry-serial-no'.
5370 					 */
5371 					sn = (char *)&inq80[4];
5372 					sn[len] = 0;
5373 					while (*sn && (*sn == ' '))
5374 						sn++;
5375 					if (*sn) {
5376 						(void) ddi_prop_update_string(
5377 						    DDI_DEV_T_NONE,
5378 						    SD_DEVINFO(un),
5379 						    INQUIRY_SERIAL_NO, sn);
5380 					}
5381 				}
5382 			}
5383 			mutex_enter(SD_MUTEX(un));
5384 		}
5385 
5386 		/* collect page 83 data if available */
5387 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5388 			mutex_exit(SD_MUTEX(un));
5389 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
5390 
5391 			rval = sd_send_scsi_INQUIRY(ssc, inq83, inq83_len,
5392 			    0x01, 0x83, &inq83_resid);
5393 
5394 			if (rval != 0) {
5395 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5396 				kmem_free(inq83, inq83_len);
5397 				inq83 = NULL;
5398 				inq83_len = 0;
5399 			}
5400 			mutex_enter(SD_MUTEX(un));
5401 		}
5402 	}
5403 
5404 	/*
5405 	 * If transport has already registered a devid for this target
5406 	 * then that takes precedence over the driver's determination
5407 	 * of the devid.
5408 	 *
5409 	 * NOTE: The reason this check is done here instead of at the beginning
5410 	 * of the function is to allow the code above to create the
5411 	 * 'inquiry-serial-no' property.
5412 	 */
5413 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
5414 		ASSERT(un->un_devid);
5415 		un->un_f_devid_transport_defined = TRUE;
5416 		goto cleanup; /* use devid registered by the transport */
5417 	}
5418 
5419 	/*
5420 	 * This is the case of antiquated Sun disk drives that have the
5421 	 * FAB_DEVID property set in the disk_table.  These drives
5422 	 * manage the devid's by storing them in last 2 available sectors
5423 	 * on the drive and have them fabricated by the ddi layer by calling
5424 	 * ddi_devid_init and passing the DEVID_FAB flag.
5425 	 */
5426 	if (un->un_f_opt_fab_devid == TRUE) {
5427 		/*
5428 		 * Depending on EINVAL isn't reliable, since a reserved disk
5429 		 * may result in invalid geometry, so check to make sure a
5430 		 * reservation conflict did not occur during attach.
5431 		 */
5432 		if ((sd_get_devid(ssc) == EINVAL) &&
5433 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5434 			/*
5435 			 * The devid is invalid AND there is no reservation
5436 			 * conflict.  Fabricate a new devid.
5437 			 */
5438 			(void) sd_create_devid(ssc);
5439 		}
5440 
5441 		/* Register the devid if it exists */
5442 		if (un->un_devid != NULL) {
5443 			(void) ddi_devid_register(SD_DEVINFO(un),
5444 			    un->un_devid);
5445 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5446 			    "sd_register_devid: Devid Fabricated\n");
5447 		}
5448 		goto cleanup;
5449 	}
5450 
5451 	/* encode best devid possible based on data available */
5452 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
5453 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
5454 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
5455 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
5456 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
5457 
5458 		/* devid successfully encoded, register devid */
5459 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
5460 
5461 	} else {
5462 		/*
5463 		 * Unable to encode a devid based on data available.
5464 		 * This is not a Sun qualified disk.  Older Sun disk
5465 		 * drives that have the SD_FAB_DEVID property
5466 		 * set in the disk_table and non Sun qualified
5467 		 * disks are treated in the same manner.  These
5468 		 * drives manage the devid's by storing them in
5469 		 * last 2 available sectors on the drive and
5470 		 * have them fabricated by the ddi layer by
5471 		 * calling ddi_devid_init and passing the
5472 		 * DEVID_FAB flag.
5473 		 * Create a fabricate devid only if there's no
5474 		 * fabricate devid existed.
5475 		 */
5476 		if (sd_get_devid(ssc) == EINVAL) {
5477 			(void) sd_create_devid(ssc);
5478 		}
5479 		un->un_f_opt_fab_devid = TRUE;
5480 
5481 		/* Register the devid if it exists */
5482 		if (un->un_devid != NULL) {
5483 			(void) ddi_devid_register(SD_DEVINFO(un),
5484 			    un->un_devid);
5485 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5486 			    "sd_register_devid: devid fabricated using "
5487 			    "ddi framework\n");
5488 		}
5489 	}
5490 
5491 cleanup:
5492 	/* clean up resources */
5493 	if (inq80 != NULL) {
5494 		kmem_free(inq80, inq80_len);
5495 	}
5496 	if (inq83 != NULL) {
5497 		kmem_free(inq83, inq83_len);
5498 	}
5499 }
5500 
5501 
5502 
5503 /*
5504  *    Function: sd_get_devid
5505  *
5506  * Description: This routine will return 0 if a valid device id has been
5507  *		obtained from the target and stored in the soft state. If a
5508  *		valid device id has not been previously read and stored, a
5509  *		read attempt will be made.
5510  *
5511  *   Arguments: un - driver soft state (unit) structure
5512  *
5513  * Return Code: 0 if we successfully get the device id
5514  *
5515  *     Context: Kernel Thread
5516  */
5517 
5518 static int
5519 sd_get_devid(sd_ssc_t *ssc)
5520 {
5521 	struct dk_devid		*dkdevid;
5522 	ddi_devid_t		tmpid;
5523 	uint_t			*ip;
5524 	size_t			sz;
5525 	diskaddr_t		blk;
5526 	int			status;
5527 	int			chksum;
5528 	int			i;
5529 	size_t			buffer_size;
5530 	struct sd_lun		*un;
5531 
5532 	ASSERT(ssc != NULL);
5533 	un = ssc->ssc_un;
5534 	ASSERT(un != NULL);
5535 	ASSERT(mutex_owned(SD_MUTEX(un)));
5536 
5537 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
5538 	    un);
5539 
5540 	if (un->un_devid != NULL) {
5541 		return (0);
5542 	}
5543 
5544 	mutex_exit(SD_MUTEX(un));
5545 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5546 	    (void *)SD_PATH_DIRECT) != 0) {
5547 		mutex_enter(SD_MUTEX(un));
5548 		return (EINVAL);
5549 	}
5550 
5551 	/*
5552 	 * Read and verify device id, stored in the reserved cylinders at the
5553 	 * end of the disk. Backup label is on the odd sectors of the last
5554 	 * track of the last cylinder. Device id will be on track of the next
5555 	 * to last cylinder.
5556 	 */
5557 	mutex_enter(SD_MUTEX(un));
5558 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
5559 	mutex_exit(SD_MUTEX(un));
5560 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
5561 	status = sd_send_scsi_READ(ssc, dkdevid, buffer_size, blk,
5562 	    SD_PATH_DIRECT);
5563 
5564 	if (status != 0) {
5565 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5566 		goto error;
5567 	}
5568 
5569 	/* Validate the revision */
5570 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
5571 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
5572 		status = EINVAL;
5573 		goto error;
5574 	}
5575 
5576 	/* Calculate the checksum */
5577 	chksum = 0;
5578 	ip = (uint_t *)dkdevid;
5579 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5580 	    i++) {
5581 		chksum ^= ip[i];
5582 	}
5583 
5584 	/* Compare the checksums */
5585 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
5586 		status = EINVAL;
5587 		goto error;
5588 	}
5589 
5590 	/* Validate the device id */
5591 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
5592 		status = EINVAL;
5593 		goto error;
5594 	}
5595 
5596 	/*
5597 	 * Store the device id in the driver soft state
5598 	 */
5599 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
5600 	tmpid = kmem_alloc(sz, KM_SLEEP);
5601 
5602 	mutex_enter(SD_MUTEX(un));
5603 
5604 	un->un_devid = tmpid;
5605 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
5606 
5607 	kmem_free(dkdevid, buffer_size);
5608 
5609 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
5610 
5611 	return (status);
5612 error:
5613 	mutex_enter(SD_MUTEX(un));
5614 	kmem_free(dkdevid, buffer_size);
5615 	return (status);
5616 }
5617 
5618 
5619 /*
5620  *    Function: sd_create_devid
5621  *
5622  * Description: This routine will fabricate the device id and write it
5623  *		to the disk.
5624  *
5625  *   Arguments: un - driver soft state (unit) structure
5626  *
5627  * Return Code: value of the fabricated device id
5628  *
5629  *     Context: Kernel Thread
5630  */
5631 
5632 static ddi_devid_t
5633 sd_create_devid(sd_ssc_t *ssc)
5634 {
5635 	struct sd_lun	*un;
5636 
5637 	ASSERT(ssc != NULL);
5638 	un = ssc->ssc_un;
5639 	ASSERT(un != NULL);
5640 
5641 	/* Fabricate the devid */
5642 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
5643 	    == DDI_FAILURE) {
5644 		return (NULL);
5645 	}
5646 
5647 	/* Write the devid to disk */
5648 	if (sd_write_deviceid(ssc) != 0) {
5649 		ddi_devid_free(un->un_devid);
5650 		un->un_devid = NULL;
5651 	}
5652 
5653 	return (un->un_devid);
5654 }
5655 
5656 
5657 /*
5658  *    Function: sd_write_deviceid
5659  *
5660  * Description: This routine will write the device id to the disk
5661  *		reserved sector.
5662  *
5663  *   Arguments: un - driver soft state (unit) structure
5664  *
5665  * Return Code: EINVAL
5666  *		value returned by sd_send_scsi_cmd
5667  *
5668  *     Context: Kernel Thread
5669  */
5670 
5671 static int
5672 sd_write_deviceid(sd_ssc_t *ssc)
5673 {
5674 	struct dk_devid		*dkdevid;
5675 	uchar_t			*buf;
5676 	diskaddr_t		blk;
5677 	uint_t			*ip, chksum;
5678 	int			status;
5679 	int			i;
5680 	struct sd_lun		*un;
5681 
5682 	ASSERT(ssc != NULL);
5683 	un = ssc->ssc_un;
5684 	ASSERT(un != NULL);
5685 	ASSERT(mutex_owned(SD_MUTEX(un)));
5686 
5687 	mutex_exit(SD_MUTEX(un));
5688 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5689 	    (void *)SD_PATH_DIRECT) != 0) {
5690 		mutex_enter(SD_MUTEX(un));
5691 		return (-1);
5692 	}
5693 
5694 
5695 	/* Allocate the buffer */
5696 	buf = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5697 	dkdevid = (struct dk_devid *)buf;
5698 
5699 	/* Fill in the revision */
5700 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5701 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5702 
5703 	/* Copy in the device id */
5704 	mutex_enter(SD_MUTEX(un));
5705 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5706 	    ddi_devid_sizeof(un->un_devid));
5707 	mutex_exit(SD_MUTEX(un));
5708 
5709 	/* Calculate the checksum */
5710 	chksum = 0;
5711 	ip = (uint_t *)dkdevid;
5712 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5713 	    i++) {
5714 		chksum ^= ip[i];
5715 	}
5716 
5717 	/* Fill-in checksum */
5718 	DKD_FORMCHKSUM(chksum, dkdevid);
5719 
5720 	/* Write the reserved sector */
5721 	status = sd_send_scsi_WRITE(ssc, buf, un->un_sys_blocksize, blk,
5722 	    SD_PATH_DIRECT);
5723 	if (status != 0)
5724 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5725 
5726 	kmem_free(buf, un->un_sys_blocksize);
5727 
5728 	mutex_enter(SD_MUTEX(un));
5729 	return (status);
5730 }
5731 
5732 
5733 /*
5734  *    Function: sd_check_vpd_page_support
5735  *
5736  * Description: This routine sends an inquiry command with the EVPD bit set and
5737  *		a page code of 0x00 to the device. It is used to determine which
5738  *		vital product pages are available to find the devid. We are
5739  *		looking for pages 0x83 0x80 or 0xB1.  If we return a negative 1,
5740  *		the device does not support that command.
5741  *
5742  *   Arguments: un  - driver soft state (unit) structure
5743  *
5744  * Return Code: 0 - success
5745  *		1 - check condition
5746  *
5747  *     Context: This routine can sleep.
5748  */
5749 
5750 static int
5751 sd_check_vpd_page_support(sd_ssc_t *ssc)
5752 {
5753 	uchar_t	*page_list	= NULL;
5754 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5755 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5756 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5757 	int    	rval		= 0;
5758 	int	counter;
5759 	struct sd_lun		*un;
5760 
5761 	ASSERT(ssc != NULL);
5762 	un = ssc->ssc_un;
5763 	ASSERT(un != NULL);
5764 	ASSERT(mutex_owned(SD_MUTEX(un)));
5765 
5766 	mutex_exit(SD_MUTEX(un));
5767 
5768 	/*
5769 	 * We'll set the page length to the maximum to save figuring it out
5770 	 * with an additional call.
5771 	 */
5772 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5773 
5774 	rval = sd_send_scsi_INQUIRY(ssc, page_list, page_length, evpd,
5775 	    page_code, NULL);
5776 
5777 	if (rval != 0)
5778 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5779 
5780 	mutex_enter(SD_MUTEX(un));
5781 
5782 	/*
5783 	 * Now we must validate that the device accepted the command, as some
5784 	 * drives do not support it.  If the drive does support it, we will
5785 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5786 	 * not, we return -1.
5787 	 */
5788 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5789 		/* Loop to find one of the 2 pages we need */
5790 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5791 
5792 		/*
5793 		 * Pages are returned in ascending order, and 0x83 is what we
5794 		 * are hoping for.
5795 		 */
5796 		while ((page_list[counter] <= 0xB1) &&
5797 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5798 		    VPD_HEAD_OFFSET))) {
5799 			/*
5800 			 * Add 3 because page_list[3] is the number of
5801 			 * pages minus 3
5802 			 */
5803 
5804 			switch (page_list[counter]) {
5805 			case 0x00:
5806 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5807 				break;
5808 			case 0x80:
5809 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5810 				break;
5811 			case 0x81:
5812 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5813 				break;
5814 			case 0x82:
5815 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5816 				break;
5817 			case 0x83:
5818 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5819 				break;
5820 			case 0x86:
5821 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5822 				break;
5823 			case 0xB1:
5824 				un->un_vpd_page_mask |= SD_VPD_DEV_CHARACTER_PG;
5825 				break;
5826 			}
5827 			counter++;
5828 		}
5829 
5830 	} else {
5831 		rval = -1;
5832 
5833 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5834 		    "sd_check_vpd_page_support: This drive does not implement "
5835 		    "VPD pages.\n");
5836 	}
5837 
5838 	kmem_free(page_list, page_length);
5839 
5840 	return (rval);
5841 }
5842 
5843 
5844 /*
5845  *    Function: sd_setup_pm
5846  *
5847  * Description: Initialize Power Management on the device
5848  *
5849  *     Context: Kernel Thread
5850  */
5851 
5852 static void
5853 sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi)
5854 {
5855 	uint_t		log_page_size;
5856 	uchar_t		*log_page_data;
5857 	int		rval = 0;
5858 	struct sd_lun	*un;
5859 
5860 	ASSERT(ssc != NULL);
5861 	un = ssc->ssc_un;
5862 	ASSERT(un != NULL);
5863 
5864 	/*
5865 	 * Since we are called from attach, holding a mutex for
5866 	 * un is unnecessary. Because some of the routines called
5867 	 * from here require SD_MUTEX to not be held, assert this
5868 	 * right up front.
5869 	 */
5870 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5871 	/*
5872 	 * Since the sd device does not have the 'reg' property,
5873 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5874 	 * The following code is to tell cpr that this device
5875 	 * DOES need to be suspended and resumed.
5876 	 */
5877 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5878 	    "pm-hardware-state", "needs-suspend-resume");
5879 
5880 	/*
5881 	 * This complies with the new power management framework
5882 	 * for certain desktop machines. Create the pm_components
5883 	 * property as a string array property.
5884 	 * If un_f_pm_supported is TRUE, that means the disk
5885 	 * attached HBA has set the "pm-capable" property and
5886 	 * the value of this property is bigger than 0.
5887 	 */
5888 	if (un->un_f_pm_supported) {
5889 		/*
5890 		 * not all devices have a motor, try it first.
5891 		 * some devices may return ILLEGAL REQUEST, some
5892 		 * will hang
5893 		 * The following START_STOP_UNIT is used to check if target
5894 		 * device has a motor.
5895 		 */
5896 		un->un_f_start_stop_supported = TRUE;
5897 
5898 		if (un->un_f_power_condition_supported) {
5899 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5900 			    SD_POWER_CONDITION, SD_TARGET_ACTIVE,
5901 			    SD_PATH_DIRECT);
5902 			if (rval != 0) {
5903 				un->un_f_power_condition_supported = FALSE;
5904 			}
5905 		}
5906 		if (!un->un_f_power_condition_supported) {
5907 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5908 			    SD_START_STOP, SD_TARGET_START, SD_PATH_DIRECT);
5909 		}
5910 		if (rval != 0) {
5911 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5912 			un->un_f_start_stop_supported = FALSE;
5913 		}
5914 
5915 		/*
5916 		 * create pm properties anyways otherwise the parent can't
5917 		 * go to sleep
5918 		 */
5919 		un->un_f_pm_is_enabled = TRUE;
5920 		(void) sd_create_pm_components(devi, un);
5921 
5922 		/*
5923 		 * If it claims that log sense is supported, check it out.
5924 		 */
5925 		if (un->un_f_log_sense_supported) {
5926 			rval = sd_log_page_supported(ssc,
5927 			    START_STOP_CYCLE_PAGE);
5928 			if (rval == 1) {
5929 				/* Page found, use it. */
5930 				un->un_start_stop_cycle_page =
5931 				    START_STOP_CYCLE_PAGE;
5932 			} else {
5933 				/*
5934 				 * Page not found or log sense is not
5935 				 * supported.
5936 				 * Notice we do not check the old style
5937 				 * START_STOP_CYCLE_VU_PAGE because this
5938 				 * code path does not apply to old disks.
5939 				 */
5940 				un->un_f_log_sense_supported = FALSE;
5941 				un->un_f_pm_log_sense_smart = FALSE;
5942 			}
5943 		}
5944 
5945 		return;
5946 	}
5947 
5948 	/*
5949 	 * For the disk whose attached HBA has not set the "pm-capable"
5950 	 * property, check if it supports the power management.
5951 	 */
5952 	if (!un->un_f_log_sense_supported) {
5953 		un->un_power_level = SD_SPINDLE_ON;
5954 		un->un_f_pm_is_enabled = FALSE;
5955 		return;
5956 	}
5957 
5958 	rval = sd_log_page_supported(ssc, START_STOP_CYCLE_PAGE);
5959 
5960 #ifdef	SDDEBUG
5961 	if (sd_force_pm_supported) {
5962 		/* Force a successful result */
5963 		rval = 1;
5964 	}
5965 #endif
5966 
5967 	/*
5968 	 * If the start-stop cycle counter log page is not supported
5969 	 * or if the pm-capable property is set to be false (0),
5970 	 * then we should not create the pm_components property.
5971 	 */
5972 	if (rval == -1) {
5973 		/*
5974 		 * Error.
5975 		 * Reading log sense failed, most likely this is
5976 		 * an older drive that does not support log sense.
5977 		 * If this fails auto-pm is not supported.
5978 		 */
5979 		un->un_power_level = SD_SPINDLE_ON;
5980 		un->un_f_pm_is_enabled = FALSE;
5981 
5982 	} else if (rval == 0) {
5983 		/*
5984 		 * Page not found.
5985 		 * The start stop cycle counter is implemented as page
5986 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5987 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5988 		 */
5989 		if (sd_log_page_supported(ssc, START_STOP_CYCLE_VU_PAGE) == 1) {
5990 			/*
5991 			 * Page found, use this one.
5992 			 */
5993 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5994 			un->un_f_pm_is_enabled = TRUE;
5995 		} else {
5996 			/*
5997 			 * Error or page not found.
5998 			 * auto-pm is not supported for this device.
5999 			 */
6000 			un->un_power_level = SD_SPINDLE_ON;
6001 			un->un_f_pm_is_enabled = FALSE;
6002 		}
6003 	} else {
6004 		/*
6005 		 * Page found, use it.
6006 		 */
6007 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
6008 		un->un_f_pm_is_enabled = TRUE;
6009 	}
6010 
6011 
6012 	if (un->un_f_pm_is_enabled == TRUE) {
6013 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6014 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6015 
6016 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6017 		    log_page_size, un->un_start_stop_cycle_page,
6018 		    0x01, 0, SD_PATH_DIRECT);
6019 
6020 		if (rval != 0) {
6021 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6022 		}
6023 
6024 #ifdef	SDDEBUG
6025 		if (sd_force_pm_supported) {
6026 			/* Force a successful result */
6027 			rval = 0;
6028 		}
6029 #endif
6030 
6031 		/*
6032 		 * If the Log sense for Page( Start/stop cycle counter page)
6033 		 * succeeds, then power management is supported and we can
6034 		 * enable auto-pm.
6035 		 */
6036 		if (rval == 0)  {
6037 			(void) sd_create_pm_components(devi, un);
6038 		} else {
6039 			un->un_power_level = SD_SPINDLE_ON;
6040 			un->un_f_pm_is_enabled = FALSE;
6041 		}
6042 
6043 		kmem_free(log_page_data, log_page_size);
6044 	}
6045 }
6046 
6047 
6048 /*
6049  *    Function: sd_create_pm_components
6050  *
6051  * Description: Initialize PM property.
6052  *
6053  *     Context: Kernel thread context
6054  */
6055 
6056 static void
6057 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
6058 {
6059 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6060 
6061 	if (un->un_f_power_condition_supported) {
6062 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6063 		    "pm-components", sd_pwr_pc.pm_comp, 5)
6064 		    != DDI_PROP_SUCCESS) {
6065 			un->un_power_level = SD_SPINDLE_ACTIVE;
6066 			un->un_f_pm_is_enabled = FALSE;
6067 			return;
6068 		}
6069 	} else {
6070 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6071 		    "pm-components", sd_pwr_ss.pm_comp, 3)
6072 		    != DDI_PROP_SUCCESS) {
6073 			un->un_power_level = SD_SPINDLE_ON;
6074 			un->un_f_pm_is_enabled = FALSE;
6075 			return;
6076 		}
6077 	}
6078 	/*
6079 	 * When components are initially created they are idle,
6080 	 * power up any non-removables.
6081 	 * Note: the return value of pm_raise_power can't be used
6082 	 * for determining if PM should be enabled for this device.
6083 	 * Even if you check the return values and remove this
6084 	 * property created above, the PM framework will not honor the
6085 	 * change after the first call to pm_raise_power. Hence,
6086 	 * removal of that property does not help if pm_raise_power
6087 	 * fails. In the case of removable media, the start/stop
6088 	 * will fail if the media is not present.
6089 	 */
6090 	if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
6091 	    SD_PM_STATE_ACTIVE(un)) == DDI_SUCCESS)) {
6092 		mutex_enter(SD_MUTEX(un));
6093 		un->un_power_level = SD_PM_STATE_ACTIVE(un);
6094 		mutex_enter(&un->un_pm_mutex);
6095 		/* Set to on and not busy. */
6096 		un->un_pm_count = 0;
6097 	} else {
6098 		mutex_enter(SD_MUTEX(un));
6099 		un->un_power_level = SD_PM_STATE_STOPPED(un);
6100 		mutex_enter(&un->un_pm_mutex);
6101 		/* Set to off. */
6102 		un->un_pm_count = -1;
6103 	}
6104 	mutex_exit(&un->un_pm_mutex);
6105 	mutex_exit(SD_MUTEX(un));
6106 }
6107 
6108 
6109 /*
6110  *    Function: sd_ddi_suspend
6111  *
6112  * Description: Performs system power-down operations. This includes
6113  *		setting the drive state to indicate its suspended so
6114  *		that no new commands will be accepted. Also, wait for
6115  *		all commands that are in transport or queued to a timer
6116  *		for retry to complete. All timeout threads are cancelled.
6117  *
6118  * Return Code: DDI_FAILURE or DDI_SUCCESS
6119  *
6120  *     Context: Kernel thread context
6121  */
6122 
6123 static int
6124 sd_ddi_suspend(dev_info_t *devi)
6125 {
6126 	struct	sd_lun	*un;
6127 	clock_t		wait_cmds_complete;
6128 
6129 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6130 	if (un == NULL) {
6131 		return (DDI_FAILURE);
6132 	}
6133 
6134 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
6135 
6136 	mutex_enter(SD_MUTEX(un));
6137 
6138 	/* Return success if the device is already suspended. */
6139 	if (un->un_state == SD_STATE_SUSPENDED) {
6140 		mutex_exit(SD_MUTEX(un));
6141 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6142 		    "device already suspended, exiting\n");
6143 		return (DDI_SUCCESS);
6144 	}
6145 
6146 	/* Return failure if the device is being used by HA */
6147 	if (un->un_resvd_status &
6148 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
6149 		mutex_exit(SD_MUTEX(un));
6150 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6151 		    "device in use by HA, exiting\n");
6152 		return (DDI_FAILURE);
6153 	}
6154 
6155 	/*
6156 	 * Return failure if the device is in a resource wait
6157 	 * or power changing state.
6158 	 */
6159 	if ((un->un_state == SD_STATE_RWAIT) ||
6160 	    (un->un_state == SD_STATE_PM_CHANGING)) {
6161 		mutex_exit(SD_MUTEX(un));
6162 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6163 		    "device in resource wait state, exiting\n");
6164 		return (DDI_FAILURE);
6165 	}
6166 
6167 
6168 	un->un_save_state = un->un_last_state;
6169 	New_state(un, SD_STATE_SUSPENDED);
6170 
6171 	/*
6172 	 * Wait for all commands that are in transport or queued to a timer
6173 	 * for retry to complete.
6174 	 *
6175 	 * While waiting, no new commands will be accepted or sent because of
6176 	 * the new state we set above.
6177 	 *
6178 	 * Wait till current operation has completed. If we are in the resource
6179 	 * wait state (with an intr outstanding) then we need to wait till the
6180 	 * intr completes and starts the next cmd. We want to wait for
6181 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
6182 	 */
6183 	wait_cmds_complete = ddi_get_lbolt() +
6184 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
6185 
6186 	while (un->un_ncmds_in_transport != 0) {
6187 		/*
6188 		 * Fail if commands do not finish in the specified time.
6189 		 */
6190 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
6191 		    wait_cmds_complete) == -1) {
6192 			/*
6193 			 * Undo the state changes made above. Everything
6194 			 * must go back to it's original value.
6195 			 */
6196 			Restore_state(un);
6197 			un->un_last_state = un->un_save_state;
6198 			/* Wake up any threads that might be waiting. */
6199 			cv_broadcast(&un->un_suspend_cv);
6200 			mutex_exit(SD_MUTEX(un));
6201 			SD_ERROR(SD_LOG_IO_PM, un,
6202 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
6203 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
6204 			return (DDI_FAILURE);
6205 		}
6206 	}
6207 
6208 	/*
6209 	 * Cancel SCSI watch thread and timeouts, if any are active
6210 	 */
6211 
6212 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
6213 		opaque_t temp_token = un->un_swr_token;
6214 		mutex_exit(SD_MUTEX(un));
6215 		scsi_watch_suspend(temp_token);
6216 		mutex_enter(SD_MUTEX(un));
6217 	}
6218 
6219 	if (un->un_reset_throttle_timeid != NULL) {
6220 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
6221 		un->un_reset_throttle_timeid = NULL;
6222 		mutex_exit(SD_MUTEX(un));
6223 		(void) untimeout(temp_id);
6224 		mutex_enter(SD_MUTEX(un));
6225 	}
6226 
6227 	if (un->un_dcvb_timeid != NULL) {
6228 		timeout_id_t temp_id = un->un_dcvb_timeid;
6229 		un->un_dcvb_timeid = NULL;
6230 		mutex_exit(SD_MUTEX(un));
6231 		(void) untimeout(temp_id);
6232 		mutex_enter(SD_MUTEX(un));
6233 	}
6234 
6235 	mutex_enter(&un->un_pm_mutex);
6236 	if (un->un_pm_timeid != NULL) {
6237 		timeout_id_t temp_id = un->un_pm_timeid;
6238 		un->un_pm_timeid = NULL;
6239 		mutex_exit(&un->un_pm_mutex);
6240 		mutex_exit(SD_MUTEX(un));
6241 		(void) untimeout(temp_id);
6242 		mutex_enter(SD_MUTEX(un));
6243 	} else {
6244 		mutex_exit(&un->un_pm_mutex);
6245 	}
6246 
6247 	if (un->un_rmw_msg_timeid != NULL) {
6248 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
6249 		un->un_rmw_msg_timeid = NULL;
6250 		mutex_exit(SD_MUTEX(un));
6251 		(void) untimeout(temp_id);
6252 		mutex_enter(SD_MUTEX(un));
6253 	}
6254 
6255 	if (un->un_retry_timeid != NULL) {
6256 		timeout_id_t temp_id = un->un_retry_timeid;
6257 		un->un_retry_timeid = NULL;
6258 		mutex_exit(SD_MUTEX(un));
6259 		(void) untimeout(temp_id);
6260 		mutex_enter(SD_MUTEX(un));
6261 
6262 		if (un->un_retry_bp != NULL) {
6263 			un->un_retry_bp->av_forw = un->un_waitq_headp;
6264 			un->un_waitq_headp = un->un_retry_bp;
6265 			if (un->un_waitq_tailp == NULL) {
6266 				un->un_waitq_tailp = un->un_retry_bp;
6267 			}
6268 			un->un_retry_bp = NULL;
6269 			un->un_retry_statp = NULL;
6270 		}
6271 	}
6272 
6273 	if (un->un_direct_priority_timeid != NULL) {
6274 		timeout_id_t temp_id = un->un_direct_priority_timeid;
6275 		un->un_direct_priority_timeid = NULL;
6276 		mutex_exit(SD_MUTEX(un));
6277 		(void) untimeout(temp_id);
6278 		mutex_enter(SD_MUTEX(un));
6279 	}
6280 
6281 	if (un->un_f_is_fibre == TRUE) {
6282 		/*
6283 		 * Remove callbacks for insert and remove events
6284 		 */
6285 		if (un->un_insert_event != NULL) {
6286 			mutex_exit(SD_MUTEX(un));
6287 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
6288 			mutex_enter(SD_MUTEX(un));
6289 			un->un_insert_event = NULL;
6290 		}
6291 
6292 		if (un->un_remove_event != NULL) {
6293 			mutex_exit(SD_MUTEX(un));
6294 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
6295 			mutex_enter(SD_MUTEX(un));
6296 			un->un_remove_event = NULL;
6297 		}
6298 	}
6299 
6300 	mutex_exit(SD_MUTEX(un));
6301 
6302 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
6303 
6304 	return (DDI_SUCCESS);
6305 }
6306 
6307 
6308 /*
6309  *    Function: sd_ddi_resume
6310  *
6311  * Description: Performs system power-up operations..
6312  *
6313  * Return Code: DDI_SUCCESS
6314  *		DDI_FAILURE
6315  *
6316  *     Context: Kernel thread context
6317  */
6318 
6319 static int
6320 sd_ddi_resume(dev_info_t *devi)
6321 {
6322 	struct	sd_lun	*un;
6323 
6324 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6325 	if (un == NULL) {
6326 		return (DDI_FAILURE);
6327 	}
6328 
6329 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6330 
6331 	mutex_enter(SD_MUTEX(un));
6332 	Restore_state(un);
6333 
6334 	/*
6335 	 * Restore the state which was saved to give the
6336 	 * the right state in un_last_state
6337 	 */
6338 	un->un_last_state = un->un_save_state;
6339 	/*
6340 	 * Note: throttle comes back at full.
6341 	 * Also note: this MUST be done before calling pm_raise_power
6342 	 * otherwise the system can get hung in biowait. The scenario where
6343 	 * this'll happen is under cpr suspend. Writing of the system
6344 	 * state goes through sddump, which writes 0 to un_throttle. If
6345 	 * writing the system state then fails, example if the partition is
6346 	 * too small, then cpr attempts a resume. If throttle isn't restored
6347 	 * from the saved value until after calling pm_raise_power then
6348 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6349 	 * in biowait.
6350 	 */
6351 	un->un_throttle = un->un_saved_throttle;
6352 
6353 	/*
6354 	 * The chance of failure is very rare as the only command done in power
6355 	 * entry point is START command when you transition from 0->1 or
6356 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6357 	 * which suspend was done. Ignore the return value as the resume should
6358 	 * not be failed. In the case of removable media the media need not be
6359 	 * inserted and hence there is a chance that raise power will fail with
6360 	 * media not present.
6361 	 */
6362 	if (un->un_f_attach_spinup) {
6363 		mutex_exit(SD_MUTEX(un));
6364 		(void) pm_raise_power(SD_DEVINFO(un), 0,
6365 		    SD_PM_STATE_ACTIVE(un));
6366 		mutex_enter(SD_MUTEX(un));
6367 	}
6368 
6369 	/*
6370 	 * Don't broadcast to the suspend cv and therefore possibly
6371 	 * start I/O until after power has been restored.
6372 	 */
6373 	cv_broadcast(&un->un_suspend_cv);
6374 	cv_broadcast(&un->un_state_cv);
6375 
6376 	/* restart thread */
6377 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6378 		scsi_watch_resume(un->un_swr_token);
6379 	}
6380 
6381 #if (defined(__fibre))
6382 	if (un->un_f_is_fibre == TRUE) {
6383 		/*
6384 		 * Add callbacks for insert and remove events
6385 		 */
6386 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6387 			sd_init_event_callbacks(un);
6388 		}
6389 	}
6390 #endif
6391 
6392 	/*
6393 	 * Transport any pending commands to the target.
6394 	 *
6395 	 * If this is a low-activity device commands in queue will have to wait
6396 	 * until new commands come in, which may take awhile. Also, we
6397 	 * specifically don't check un_ncmds_in_transport because we know that
6398 	 * there really are no commands in progress after the unit was
6399 	 * suspended and we could have reached the throttle level, been
6400 	 * suspended, and have no new commands coming in for awhile. Highly
6401 	 * unlikely, but so is the low-activity disk scenario.
6402 	 */
6403 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6404 
6405 	sd_start_cmds(un, NULL);
6406 	mutex_exit(SD_MUTEX(un));
6407 
6408 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6409 
6410 	return (DDI_SUCCESS);
6411 }
6412 
6413 
6414 /*
6415  *    Function: sd_pm_state_change
6416  *
6417  * Description: Change the driver power state.
6418  * 		Someone else is required to actually change the driver
6419  * 		power level.
6420  *
6421  *   Arguments: un - driver soft state (unit) structure
6422  *              level - the power level that is changed to
6423  *              flag - to decide how to change the power state
6424  *
6425  * Return Code: DDI_SUCCESS
6426  *
6427  *     Context: Kernel thread context
6428  */
6429 static int
6430 sd_pm_state_change(struct sd_lun *un, int level, int flag)
6431 {
6432 	ASSERT(un != NULL);
6433 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: entry\n");
6434 
6435 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6436 	mutex_enter(SD_MUTEX(un));
6437 
6438 	if (flag == SD_PM_STATE_ROLLBACK || SD_PM_IS_IO_CAPABLE(un, level)) {
6439 		un->un_power_level = level;
6440 		ASSERT(!mutex_owned(&un->un_pm_mutex));
6441 		mutex_enter(&un->un_pm_mutex);
6442 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6443 			un->un_pm_count++;
6444 			ASSERT(un->un_pm_count == 0);
6445 		}
6446 		mutex_exit(&un->un_pm_mutex);
6447 	} else {
6448 		/*
6449 		 * Exit if power management is not enabled for this device,
6450 		 * or if the device is being used by HA.
6451 		 */
6452 		if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
6453 		    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
6454 			mutex_exit(SD_MUTEX(un));
6455 			SD_TRACE(SD_LOG_POWER, un,
6456 			    "sd_pm_state_change: exiting\n");
6457 			return (DDI_FAILURE);
6458 		}
6459 
6460 		SD_INFO(SD_LOG_POWER, un, "sd_pm_state_change: "
6461 		    "un_ncmds_in_driver=%ld\n", un->un_ncmds_in_driver);
6462 
6463 		/*
6464 		 * See if the device is not busy, ie.:
6465 		 *    - we have no commands in the driver for this device
6466 		 *    - not waiting for resources
6467 		 */
6468 		if ((un->un_ncmds_in_driver == 0) &&
6469 		    (un->un_state != SD_STATE_RWAIT)) {
6470 			/*
6471 			 * The device is not busy, so it is OK to go to low
6472 			 * power state. Indicate low power, but rely on someone
6473 			 * else to actually change it.
6474 			 */
6475 			mutex_enter(&un->un_pm_mutex);
6476 			un->un_pm_count = -1;
6477 			mutex_exit(&un->un_pm_mutex);
6478 			un->un_power_level = level;
6479 		}
6480 	}
6481 
6482 	mutex_exit(SD_MUTEX(un));
6483 
6484 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: exit\n");
6485 
6486 	return (DDI_SUCCESS);
6487 }
6488 
6489 
6490 /*
6491  *    Function: sd_pm_idletimeout_handler
6492  *
6493  * Description: A timer routine that's active only while a device is busy.
6494  *		The purpose is to extend slightly the pm framework's busy
6495  *		view of the device to prevent busy/idle thrashing for
6496  *		back-to-back commands. Do this by comparing the current time
6497  *		to the time at which the last command completed and when the
6498  *		difference is greater than sd_pm_idletime, call
6499  *		pm_idle_component. In addition to indicating idle to the pm
6500  *		framework, update the chain type to again use the internal pm
6501  *		layers of the driver.
6502  *
6503  *   Arguments: arg - driver soft state (unit) structure
6504  *
6505  *     Context: Executes in a timeout(9F) thread context
6506  */
6507 
6508 static void
6509 sd_pm_idletimeout_handler(void *arg)
6510 {
6511 	struct sd_lun *un = arg;
6512 
6513 	time_t	now;
6514 
6515 	mutex_enter(&sd_detach_mutex);
6516 	if (un->un_detach_count != 0) {
6517 		/* Abort if the instance is detaching */
6518 		mutex_exit(&sd_detach_mutex);
6519 		return;
6520 	}
6521 	mutex_exit(&sd_detach_mutex);
6522 
6523 	now = ddi_get_time();
6524 	/*
6525 	 * Grab both mutexes, in the proper order, since we're accessing
6526 	 * both PM and softstate variables.
6527 	 */
6528 	mutex_enter(SD_MUTEX(un));
6529 	mutex_enter(&un->un_pm_mutex);
6530 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
6531 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
6532 		/*
6533 		 * Update the chain types.
6534 		 * This takes affect on the next new command received.
6535 		 */
6536 		if (un->un_f_non_devbsize_supported) {
6537 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6538 		} else {
6539 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6540 		}
6541 		un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD;
6542 
6543 		SD_TRACE(SD_LOG_IO_PM, un,
6544 		    "sd_pm_idletimeout_handler: idling device\n");
6545 		(void) pm_idle_component(SD_DEVINFO(un), 0);
6546 		un->un_pm_idle_timeid = NULL;
6547 	} else {
6548 		un->un_pm_idle_timeid =
6549 		    timeout(sd_pm_idletimeout_handler, un,
6550 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
6551 	}
6552 	mutex_exit(&un->un_pm_mutex);
6553 	mutex_exit(SD_MUTEX(un));
6554 }
6555 
6556 
6557 /*
6558  *    Function: sd_pm_timeout_handler
6559  *
6560  * Description: Callback to tell framework we are idle.
6561  *
6562  *     Context: timeout(9f) thread context.
6563  */
6564 
6565 static void
6566 sd_pm_timeout_handler(void *arg)
6567 {
6568 	struct sd_lun *un = arg;
6569 
6570 	(void) pm_idle_component(SD_DEVINFO(un), 0);
6571 	mutex_enter(&un->un_pm_mutex);
6572 	un->un_pm_timeid = NULL;
6573 	mutex_exit(&un->un_pm_mutex);
6574 }
6575 
6576 
6577 /*
6578  *    Function: sdpower
6579  *
6580  * Description: PM entry point.
6581  *
6582  * Return Code: DDI_SUCCESS
6583  *		DDI_FAILURE
6584  *
6585  *     Context: Kernel thread context
6586  */
6587 
6588 static int
6589 sdpower(dev_info_t *devi, int component, int level)
6590 {
6591 	struct sd_lun	*un;
6592 	int		instance;
6593 	int		rval = DDI_SUCCESS;
6594 	uint_t		i, log_page_size, maxcycles, ncycles;
6595 	uchar_t		*log_page_data;
6596 	int		log_sense_page;
6597 	int		medium_present;
6598 	time_t		intvlp;
6599 	struct pm_trans_data	sd_pm_tran_data;
6600 	uchar_t		save_state;
6601 	int		sval;
6602 	uchar_t		state_before_pm;
6603 	int		got_semaphore_here;
6604 	sd_ssc_t	*ssc;
6605 	int	last_power_level;
6606 
6607 	instance = ddi_get_instance(devi);
6608 
6609 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
6610 	    !SD_PM_IS_LEVEL_VALID(un, level) || component != 0) {
6611 		return (DDI_FAILURE);
6612 	}
6613 
6614 	ssc = sd_ssc_init(un);
6615 
6616 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
6617 
6618 	/*
6619 	 * Must synchronize power down with close.
6620 	 * Attempt to decrement/acquire the open/close semaphore,
6621 	 * but do NOT wait on it. If it's not greater than zero,
6622 	 * ie. it can't be decremented without waiting, then
6623 	 * someone else, either open or close, already has it
6624 	 * and the try returns 0. Use that knowledge here to determine
6625 	 * if it's OK to change the device power level.
6626 	 * Also, only increment it on exit if it was decremented, ie. gotten,
6627 	 * here.
6628 	 */
6629 	got_semaphore_here = sema_tryp(&un->un_semoclose);
6630 
6631 	mutex_enter(SD_MUTEX(un));
6632 
6633 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
6634 	    un->un_ncmds_in_driver);
6635 
6636 	/*
6637 	 * If un_ncmds_in_driver is non-zero it indicates commands are
6638 	 * already being processed in the driver, or if the semaphore was
6639 	 * not gotten here it indicates an open or close is being processed.
6640 	 * At the same time somebody is requesting to go to a lower power
6641 	 * that can't perform I/O, which can't happen, therefore we need to
6642 	 * return failure.
6643 	 */
6644 	if ((!SD_PM_IS_IO_CAPABLE(un, level)) &&
6645 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
6646 		mutex_exit(SD_MUTEX(un));
6647 
6648 		if (got_semaphore_here != 0) {
6649 			sema_v(&un->un_semoclose);
6650 		}
6651 		SD_TRACE(SD_LOG_IO_PM, un,
6652 		    "sdpower: exit, device has queued cmds.\n");
6653 
6654 		goto sdpower_failed;
6655 	}
6656 
6657 	/*
6658 	 * if it is OFFLINE that means the disk is completely dead
6659 	 * in our case we have to put the disk in on or off by sending commands
6660 	 * Of course that will fail anyway so return back here.
6661 	 *
6662 	 * Power changes to a device that's OFFLINE or SUSPENDED
6663 	 * are not allowed.
6664 	 */
6665 	if ((un->un_state == SD_STATE_OFFLINE) ||
6666 	    (un->un_state == SD_STATE_SUSPENDED)) {
6667 		mutex_exit(SD_MUTEX(un));
6668 
6669 		if (got_semaphore_here != 0) {
6670 			sema_v(&un->un_semoclose);
6671 		}
6672 		SD_TRACE(SD_LOG_IO_PM, un,
6673 		    "sdpower: exit, device is off-line.\n");
6674 
6675 		goto sdpower_failed;
6676 	}
6677 
6678 	/*
6679 	 * Change the device's state to indicate it's power level
6680 	 * is being changed. Do this to prevent a power off in the
6681 	 * middle of commands, which is especially bad on devices
6682 	 * that are really powered off instead of just spun down.
6683 	 */
6684 	state_before_pm = un->un_state;
6685 	un->un_state = SD_STATE_PM_CHANGING;
6686 
6687 	mutex_exit(SD_MUTEX(un));
6688 
6689 	/*
6690 	 * If log sense command is not supported, bypass the
6691 	 * following checking, otherwise, check the log sense
6692 	 * information for this device.
6693 	 */
6694 	if (SD_PM_STOP_MOTOR_NEEDED(un, level) &&
6695 	    un->un_f_log_sense_supported) {
6696 		/*
6697 		 * Get the log sense information to understand whether the
6698 		 * the powercycle counts have gone beyond the threshhold.
6699 		 */
6700 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6701 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6702 
6703 		mutex_enter(SD_MUTEX(un));
6704 		log_sense_page = un->un_start_stop_cycle_page;
6705 		mutex_exit(SD_MUTEX(un));
6706 
6707 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6708 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
6709 
6710 		if (rval != 0) {
6711 			if (rval == EIO)
6712 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6713 			else
6714 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6715 		}
6716 
6717 #ifdef	SDDEBUG
6718 		if (sd_force_pm_supported) {
6719 			/* Force a successful result */
6720 			rval = 0;
6721 		}
6722 #endif
6723 		if (rval != 0) {
6724 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
6725 			    "Log Sense Failed\n");
6726 
6727 			kmem_free(log_page_data, log_page_size);
6728 			/* Cannot support power management on those drives */
6729 
6730 			if (got_semaphore_here != 0) {
6731 				sema_v(&un->un_semoclose);
6732 			}
6733 			/*
6734 			 * On exit put the state back to it's original value
6735 			 * and broadcast to anyone waiting for the power
6736 			 * change completion.
6737 			 */
6738 			mutex_enter(SD_MUTEX(un));
6739 			un->un_state = state_before_pm;
6740 			cv_broadcast(&un->un_suspend_cv);
6741 			mutex_exit(SD_MUTEX(un));
6742 			SD_TRACE(SD_LOG_IO_PM, un,
6743 			    "sdpower: exit, Log Sense Failed.\n");
6744 
6745 			goto sdpower_failed;
6746 		}
6747 
6748 		/*
6749 		 * From the page data - Convert the essential information to
6750 		 * pm_trans_data
6751 		 */
6752 		maxcycles =
6753 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
6754 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
6755 
6756 		ncycles =
6757 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6758 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6759 
6760 		if (un->un_f_pm_log_sense_smart) {
6761 			sd_pm_tran_data.un.smart_count.allowed = maxcycles;
6762 			sd_pm_tran_data.un.smart_count.consumed = ncycles;
6763 			sd_pm_tran_data.un.smart_count.flag = 0;
6764 			sd_pm_tran_data.format = DC_SMART_FORMAT;
6765 		} else {
6766 			sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6767 			sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6768 			for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6769 				sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6770 				    log_page_data[8+i];
6771 			}
6772 			sd_pm_tran_data.un.scsi_cycles.flag = 0;
6773 			sd_pm_tran_data.format = DC_SCSI_FORMAT;
6774 		}
6775 
6776 		kmem_free(log_page_data, log_page_size);
6777 
6778 		/*
6779 		 * Call pm_trans_check routine to get the Ok from
6780 		 * the global policy
6781 		 */
6782 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6783 #ifdef	SDDEBUG
6784 		if (sd_force_pm_supported) {
6785 			/* Force a successful result */
6786 			rval = 1;
6787 		}
6788 #endif
6789 		switch (rval) {
6790 		case 0:
6791 			/*
6792 			 * Not Ok to Power cycle or error in parameters passed
6793 			 * Would have given the advised time to consider power
6794 			 * cycle. Based on the new intvlp parameter we are
6795 			 * supposed to pretend we are busy so that pm framework
6796 			 * will never call our power entry point. Because of
6797 			 * that install a timeout handler and wait for the
6798 			 * recommended time to elapse so that power management
6799 			 * can be effective again.
6800 			 *
6801 			 * To effect this behavior, call pm_busy_component to
6802 			 * indicate to the framework this device is busy.
6803 			 * By not adjusting un_pm_count the rest of PM in
6804 			 * the driver will function normally, and independent
6805 			 * of this but because the framework is told the device
6806 			 * is busy it won't attempt powering down until it gets
6807 			 * a matching idle. The timeout handler sends this.
6808 			 * Note: sd_pm_entry can't be called here to do this
6809 			 * because sdpower may have been called as a result
6810 			 * of a call to pm_raise_power from within sd_pm_entry.
6811 			 *
6812 			 * If a timeout handler is already active then
6813 			 * don't install another.
6814 			 */
6815 			mutex_enter(&un->un_pm_mutex);
6816 			if (un->un_pm_timeid == NULL) {
6817 				un->un_pm_timeid =
6818 				    timeout(sd_pm_timeout_handler,
6819 				    un, intvlp * drv_usectohz(1000000));
6820 				mutex_exit(&un->un_pm_mutex);
6821 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6822 			} else {
6823 				mutex_exit(&un->un_pm_mutex);
6824 			}
6825 			if (got_semaphore_here != 0) {
6826 				sema_v(&un->un_semoclose);
6827 			}
6828 			/*
6829 			 * On exit put the state back to it's original value
6830 			 * and broadcast to anyone waiting for the power
6831 			 * change completion.
6832 			 */
6833 			mutex_enter(SD_MUTEX(un));
6834 			un->un_state = state_before_pm;
6835 			cv_broadcast(&un->un_suspend_cv);
6836 			mutex_exit(SD_MUTEX(un));
6837 
6838 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6839 			    "trans check Failed, not ok to power cycle.\n");
6840 
6841 			goto sdpower_failed;
6842 		case -1:
6843 			if (got_semaphore_here != 0) {
6844 				sema_v(&un->un_semoclose);
6845 			}
6846 			/*
6847 			 * On exit put the state back to it's original value
6848 			 * and broadcast to anyone waiting for the power
6849 			 * change completion.
6850 			 */
6851 			mutex_enter(SD_MUTEX(un));
6852 			un->un_state = state_before_pm;
6853 			cv_broadcast(&un->un_suspend_cv);
6854 			mutex_exit(SD_MUTEX(un));
6855 			SD_TRACE(SD_LOG_IO_PM, un,
6856 			    "sdpower: exit, trans check command Failed.\n");
6857 
6858 			goto sdpower_failed;
6859 		}
6860 	}
6861 
6862 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6863 		/*
6864 		 * Save the last state... if the STOP FAILS we need it
6865 		 * for restoring
6866 		 */
6867 		mutex_enter(SD_MUTEX(un));
6868 		save_state = un->un_last_state;
6869 		last_power_level = un->un_power_level;
6870 		/*
6871 		 * There must not be any cmds. getting processed
6872 		 * in the driver when we get here. Power to the
6873 		 * device is potentially going off.
6874 		 */
6875 		ASSERT(un->un_ncmds_in_driver == 0);
6876 		mutex_exit(SD_MUTEX(un));
6877 
6878 		/*
6879 		 * For now PM suspend the device completely before spindle is
6880 		 * turned off
6881 		 */
6882 		if ((rval = sd_pm_state_change(un, level, SD_PM_STATE_CHANGE))
6883 		    == DDI_FAILURE) {
6884 			if (got_semaphore_here != 0) {
6885 				sema_v(&un->un_semoclose);
6886 			}
6887 			/*
6888 			 * On exit put the state back to it's original value
6889 			 * and broadcast to anyone waiting for the power
6890 			 * change completion.
6891 			 */
6892 			mutex_enter(SD_MUTEX(un));
6893 			un->un_state = state_before_pm;
6894 			un->un_power_level = last_power_level;
6895 			cv_broadcast(&un->un_suspend_cv);
6896 			mutex_exit(SD_MUTEX(un));
6897 			SD_TRACE(SD_LOG_IO_PM, un,
6898 			    "sdpower: exit, PM suspend Failed.\n");
6899 
6900 			goto sdpower_failed;
6901 		}
6902 	}
6903 
6904 	/*
6905 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6906 	 * close, or strategy. Dump no long uses this routine, it uses it's
6907 	 * own code so it can be done in polled mode.
6908 	 */
6909 
6910 	medium_present = TRUE;
6911 
6912 	/*
6913 	 * When powering up, issue a TUR in case the device is at unit
6914 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6915 	 * a deadlock on un_pm_busy_cv will occur.
6916 	 */
6917 	if (SD_PM_IS_IO_CAPABLE(un, level)) {
6918 		sval = sd_send_scsi_TEST_UNIT_READY(ssc,
6919 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6920 		if (sval != 0)
6921 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6922 	}
6923 
6924 	if (un->un_f_power_condition_supported) {
6925 		char *pm_condition_name[] = {"STOPPED", "STANDBY",
6926 		    "IDLE", "ACTIVE"};
6927 		SD_TRACE(SD_LOG_IO_PM, un,
6928 		    "sdpower: sending \'%s\' power condition",
6929 		    pm_condition_name[level]);
6930 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
6931 		    sd_pl2pc[level], SD_PATH_DIRECT);
6932 	} else {
6933 		SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6934 		    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6935 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
6936 		    ((level == SD_SPINDLE_ON) ? SD_TARGET_START :
6937 		    SD_TARGET_STOP), SD_PATH_DIRECT);
6938 	}
6939 	if (sval != 0) {
6940 		if (sval == EIO)
6941 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6942 		else
6943 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6944 	}
6945 
6946 	/* Command failed, check for media present. */
6947 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6948 		medium_present = FALSE;
6949 	}
6950 
6951 	/*
6952 	 * The conditions of interest here are:
6953 	 *   if a spindle off with media present fails,
6954 	 *	then restore the state and return an error.
6955 	 *   else if a spindle on fails,
6956 	 *	then return an error (there's no state to restore).
6957 	 * In all other cases we setup for the new state
6958 	 * and return success.
6959 	 */
6960 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6961 		if ((medium_present == TRUE) && (sval != 0)) {
6962 			/* The stop command from above failed */
6963 			rval = DDI_FAILURE;
6964 			/*
6965 			 * The stop command failed, and we have media
6966 			 * present. Put the level back by calling the
6967 			 * sd_pm_resume() and set the state back to
6968 			 * it's previous value.
6969 			 */
6970 			(void) sd_pm_state_change(un, last_power_level,
6971 			    SD_PM_STATE_ROLLBACK);
6972 			mutex_enter(SD_MUTEX(un));
6973 			un->un_last_state = save_state;
6974 			mutex_exit(SD_MUTEX(un));
6975 		} else if (un->un_f_monitor_media_state) {
6976 			/*
6977 			 * The stop command from above succeeded.
6978 			 * Terminate watch thread in case of removable media
6979 			 * devices going into low power state. This is as per
6980 			 * the requirements of pm framework, otherwise commands
6981 			 * will be generated for the device (through watch
6982 			 * thread), even when the device is in low power state.
6983 			 */
6984 			mutex_enter(SD_MUTEX(un));
6985 			un->un_f_watcht_stopped = FALSE;
6986 			if (un->un_swr_token != NULL) {
6987 				opaque_t temp_token = un->un_swr_token;
6988 				un->un_f_watcht_stopped = TRUE;
6989 				un->un_swr_token = NULL;
6990 				mutex_exit(SD_MUTEX(un));
6991 				(void) scsi_watch_request_terminate(temp_token,
6992 				    SCSI_WATCH_TERMINATE_ALL_WAIT);
6993 			} else {
6994 				mutex_exit(SD_MUTEX(un));
6995 			}
6996 		}
6997 	} else {
6998 		/*
6999 		 * The level requested is I/O capable.
7000 		 * Legacy behavior: return success on a failed spinup
7001 		 * if there is no media in the drive.
7002 		 * Do this by looking at medium_present here.
7003 		 */
7004 		if ((sval != 0) && medium_present) {
7005 			/* The start command from above failed */
7006 			rval = DDI_FAILURE;
7007 		} else {
7008 			/*
7009 			 * The start command from above succeeded
7010 			 * PM resume the devices now that we have
7011 			 * started the disks
7012 			 */
7013 			(void) sd_pm_state_change(un, level,
7014 			    SD_PM_STATE_CHANGE);
7015 
7016 			/*
7017 			 * Resume the watch thread since it was suspended
7018 			 * when the device went into low power mode.
7019 			 */
7020 			if (un->un_f_monitor_media_state) {
7021 				mutex_enter(SD_MUTEX(un));
7022 				if (un->un_f_watcht_stopped == TRUE) {
7023 					opaque_t temp_token;
7024 
7025 					un->un_f_watcht_stopped = FALSE;
7026 					mutex_exit(SD_MUTEX(un));
7027 					temp_token =
7028 					    sd_watch_request_submit(un);
7029 					mutex_enter(SD_MUTEX(un));
7030 					un->un_swr_token = temp_token;
7031 				}
7032 				mutex_exit(SD_MUTEX(un));
7033 			}
7034 		}
7035 	}
7036 
7037 	if (got_semaphore_here != 0) {
7038 		sema_v(&un->un_semoclose);
7039 	}
7040 	/*
7041 	 * On exit put the state back to it's original value
7042 	 * and broadcast to anyone waiting for the power
7043 	 * change completion.
7044 	 */
7045 	mutex_enter(SD_MUTEX(un));
7046 	un->un_state = state_before_pm;
7047 	cv_broadcast(&un->un_suspend_cv);
7048 	mutex_exit(SD_MUTEX(un));
7049 
7050 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
7051 
7052 	sd_ssc_fini(ssc);
7053 	return (rval);
7054 
7055 sdpower_failed:
7056 
7057 	sd_ssc_fini(ssc);
7058 	return (DDI_FAILURE);
7059 }
7060 
7061 
7062 
7063 /*
7064  *    Function: sdattach
7065  *
7066  * Description: Driver's attach(9e) entry point function.
7067  *
7068  *   Arguments: devi - opaque device info handle
7069  *		cmd  - attach  type
7070  *
7071  * Return Code: DDI_SUCCESS
7072  *		DDI_FAILURE
7073  *
7074  *     Context: Kernel thread context
7075  */
7076 
7077 static int
7078 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
7079 {
7080 	switch (cmd) {
7081 	case DDI_ATTACH:
7082 		return (sd_unit_attach(devi));
7083 	case DDI_RESUME:
7084 		return (sd_ddi_resume(devi));
7085 	default:
7086 		break;
7087 	}
7088 	return (DDI_FAILURE);
7089 }
7090 
7091 
7092 /*
7093  *    Function: sddetach
7094  *
7095  * Description: Driver's detach(9E) entry point function.
7096  *
7097  *   Arguments: devi - opaque device info handle
7098  *		cmd  - detach  type
7099  *
7100  * Return Code: DDI_SUCCESS
7101  *		DDI_FAILURE
7102  *
7103  *     Context: Kernel thread context
7104  */
7105 
7106 static int
7107 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
7108 {
7109 	switch (cmd) {
7110 	case DDI_DETACH:
7111 		return (sd_unit_detach(devi));
7112 	case DDI_SUSPEND:
7113 		return (sd_ddi_suspend(devi));
7114 	default:
7115 		break;
7116 	}
7117 	return (DDI_FAILURE);
7118 }
7119 
7120 
7121 /*
7122  *     Function: sd_sync_with_callback
7123  *
7124  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
7125  *		 state while the callback routine is active.
7126  *
7127  *    Arguments: un: softstate structure for the instance
7128  *
7129  *	Context: Kernel thread context
7130  */
7131 
7132 static void
7133 sd_sync_with_callback(struct sd_lun *un)
7134 {
7135 	ASSERT(un != NULL);
7136 
7137 	mutex_enter(SD_MUTEX(un));
7138 
7139 	ASSERT(un->un_in_callback >= 0);
7140 
7141 	while (un->un_in_callback > 0) {
7142 		mutex_exit(SD_MUTEX(un));
7143 		delay(2);
7144 		mutex_enter(SD_MUTEX(un));
7145 	}
7146 
7147 	mutex_exit(SD_MUTEX(un));
7148 }
7149 
7150 /*
7151  *    Function: sd_unit_attach
7152  *
7153  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
7154  *		the soft state structure for the device and performs
7155  *		all necessary structure and device initializations.
7156  *
7157  *   Arguments: devi: the system's dev_info_t for the device.
7158  *
7159  * Return Code: DDI_SUCCESS if attach is successful.
7160  *		DDI_FAILURE if any part of the attach fails.
7161  *
7162  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
7163  *		Kernel thread context only.  Can sleep.
7164  */
7165 
7166 static int
7167 sd_unit_attach(dev_info_t *devi)
7168 {
7169 	struct	scsi_device	*devp;
7170 	struct	sd_lun		*un;
7171 	char			*variantp;
7172 	char			name_str[48];
7173 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
7174 	int	instance;
7175 	int	rval;
7176 	int	wc_enabled;
7177 	int	tgt;
7178 	uint64_t	capacity;
7179 	uint_t		lbasize = 0;
7180 	dev_info_t	*pdip = ddi_get_parent(devi);
7181 	int		offbyone = 0;
7182 	int		geom_label_valid = 0;
7183 	sd_ssc_t	*ssc;
7184 	int		status;
7185 	struct sd_fm_internal	*sfip = NULL;
7186 	int		max_xfer_size;
7187 
7188 	/*
7189 	 * Retrieve the target driver's private data area. This was set
7190 	 * up by the HBA.
7191 	 */
7192 	devp = ddi_get_driver_private(devi);
7193 
7194 	/*
7195 	 * Retrieve the target ID of the device.
7196 	 */
7197 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7198 	    SCSI_ADDR_PROP_TARGET, -1);
7199 
7200 	/*
7201 	 * Since we have no idea what state things were left in by the last
7202 	 * user of the device, set up some 'default' settings, ie. turn 'em
7203 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
7204 	 * Do this before the scsi_probe, which sends an inquiry.
7205 	 * This is a fix for bug (4430280).
7206 	 * Of special importance is wide-xfer. The drive could have been left
7207 	 * in wide transfer mode by the last driver to communicate with it,
7208 	 * this includes us. If that's the case, and if the following is not
7209 	 * setup properly or we don't re-negotiate with the drive prior to
7210 	 * transferring data to/from the drive, it causes bus parity errors,
7211 	 * data overruns, and unexpected interrupts. This first occurred when
7212 	 * the fix for bug (4378686) was made.
7213 	 */
7214 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
7215 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
7216 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
7217 
7218 	/*
7219 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
7220 	 * on a target. Setting it per lun instance actually sets the
7221 	 * capability of this target, which affects those luns already
7222 	 * attached on the same target. So during attach, we can only disable
7223 	 * this capability only when no other lun has been attached on this
7224 	 * target. By doing this, we assume a target has the same tagged-qing
7225 	 * capability for every lun. The condition can be removed when HBA
7226 	 * is changed to support per lun based tagged-qing capability.
7227 	 */
7228 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7229 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
7230 	}
7231 
7232 	/*
7233 	 * Use scsi_probe() to issue an INQUIRY command to the device.
7234 	 * This call will allocate and fill in the scsi_inquiry structure
7235 	 * and point the sd_inq member of the scsi_device structure to it.
7236 	 * If the attach succeeds, then this memory will not be de-allocated
7237 	 * (via scsi_unprobe()) until the instance is detached.
7238 	 */
7239 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
7240 		goto probe_failed;
7241 	}
7242 
7243 	/*
7244 	 * Check the device type as specified in the inquiry data and
7245 	 * claim it if it is of a type that we support.
7246 	 */
7247 	switch (devp->sd_inq->inq_dtype) {
7248 	case DTYPE_DIRECT:
7249 		break;
7250 	case DTYPE_RODIRECT:
7251 		break;
7252 	case DTYPE_OPTICAL:
7253 		break;
7254 	case DTYPE_NOTPRESENT:
7255 	default:
7256 		/* Unsupported device type; fail the attach. */
7257 		goto probe_failed;
7258 	}
7259 
7260 	/*
7261 	 * Allocate the soft state structure for this unit.
7262 	 *
7263 	 * We rely upon this memory being set to all zeroes by
7264 	 * ddi_soft_state_zalloc().  We assume that any member of the
7265 	 * soft state structure that is not explicitly initialized by
7266 	 * this routine will have a value of zero.
7267 	 */
7268 	instance = ddi_get_instance(devp->sd_dev);
7269 #ifndef XPV_HVM_DRIVER
7270 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
7271 		goto probe_failed;
7272 	}
7273 #endif /* !XPV_HVM_DRIVER */
7274 
7275 	/*
7276 	 * Retrieve a pointer to the newly-allocated soft state.
7277 	 *
7278 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
7279 	 * was successful, unless something has gone horribly wrong and the
7280 	 * ddi's soft state internals are corrupt (in which case it is
7281 	 * probably better to halt here than just fail the attach....)
7282 	 */
7283 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
7284 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
7285 		    instance);
7286 		/*NOTREACHED*/
7287 	}
7288 
7289 	/*
7290 	 * Link the back ptr of the driver soft state to the scsi_device
7291 	 * struct for this lun.
7292 	 * Save a pointer to the softstate in the driver-private area of
7293 	 * the scsi_device struct.
7294 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
7295 	 * we first set un->un_sd below.
7296 	 */
7297 	un->un_sd = devp;
7298 	devp->sd_private = (opaque_t)un;
7299 
7300 	/*
7301 	 * The following must be after devp is stored in the soft state struct.
7302 	 */
7303 #ifdef SDDEBUG
7304 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7305 	    "%s_unit_attach: un:0x%p instance:%d\n",
7306 	    ddi_driver_name(devi), un, instance);
7307 #endif
7308 
7309 	/*
7310 	 * Set up the device type and node type (for the minor nodes).
7311 	 * By default we assume that the device can at least support the
7312 	 * Common Command Set. Call it a CD-ROM if it reports itself
7313 	 * as a RODIRECT device.
7314 	 */
7315 	switch (devp->sd_inq->inq_dtype) {
7316 	case DTYPE_RODIRECT:
7317 		un->un_node_type = DDI_NT_CD_CHAN;
7318 		un->un_ctype	 = CTYPE_CDROM;
7319 		break;
7320 	case DTYPE_OPTICAL:
7321 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7322 		un->un_ctype	 = CTYPE_ROD;
7323 		break;
7324 	default:
7325 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7326 		un->un_ctype	 = CTYPE_CCS;
7327 		break;
7328 	}
7329 
7330 	/*
7331 	 * Try to read the interconnect type from the HBA.
7332 	 *
7333 	 * Note: This driver is currently compiled as two binaries, a parallel
7334 	 * scsi version (sd) and a fibre channel version (ssd). All functional
7335 	 * differences are determined at compile time. In the future a single
7336 	 * binary will be provided and the interconnect type will be used to
7337 	 * differentiate between fibre and parallel scsi behaviors. At that time
7338 	 * it will be necessary for all fibre channel HBAs to support this
7339 	 * property.
7340 	 *
7341 	 * set un_f_is_fiber to TRUE ( default fiber )
7342 	 */
7343 	un->un_f_is_fibre = TRUE;
7344 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
7345 	case INTERCONNECT_SSA:
7346 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
7347 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7348 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
7349 		break;
7350 	case INTERCONNECT_PARALLEL:
7351 		un->un_f_is_fibre = FALSE;
7352 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7353 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7354 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
7355 		break;
7356 	case INTERCONNECT_SAS:
7357 		un->un_f_is_fibre = FALSE;
7358 		un->un_interconnect_type = SD_INTERCONNECT_SAS;
7359 		un->un_node_type = DDI_NT_BLOCK_SAS;
7360 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7361 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SAS\n", un);
7362 		break;
7363 	case INTERCONNECT_SATA:
7364 		un->un_f_is_fibre = FALSE;
7365 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
7366 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7367 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
7368 		break;
7369 	case INTERCONNECT_FIBRE:
7370 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7371 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7372 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7373 		break;
7374 	case INTERCONNECT_FABRIC:
7375 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7376 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7377 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7378 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7379 		break;
7380 	default:
7381 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7382 		/*
7383 		 * The HBA does not support the "interconnect-type" property
7384 		 * (or did not provide a recognized type).
7385 		 *
7386 		 * Note: This will be obsoleted when a single fibre channel
7387 		 * and parallel scsi driver is delivered. In the meantime the
7388 		 * interconnect type will be set to the platform default.If that
7389 		 * type is not parallel SCSI, it means that we should be
7390 		 * assuming "ssd" semantics. However, here this also means that
7391 		 * the FC HBA is not supporting the "interconnect-type" property
7392 		 * like we expect it to, so log this occurrence.
7393 		 */
7394 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7395 		if (!SD_IS_PARALLEL_SCSI(un)) {
7396 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7397 			    "sd_unit_attach: un:0x%p Assuming "
7398 			    "INTERCONNECT_FIBRE\n", un);
7399 		} else {
7400 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7401 			    "sd_unit_attach: un:0x%p Assuming "
7402 			    "INTERCONNECT_PARALLEL\n", un);
7403 			un->un_f_is_fibre = FALSE;
7404 		}
7405 #else
7406 		/*
7407 		 * Note: This source will be implemented when a single fibre
7408 		 * channel and parallel scsi driver is delivered. The default
7409 		 * will be to assume that if a device does not support the
7410 		 * "interconnect-type" property it is a parallel SCSI HBA and
7411 		 * we will set the interconnect type for parallel scsi.
7412 		 */
7413 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7414 		un->un_f_is_fibre = FALSE;
7415 #endif
7416 		break;
7417 	}
7418 
7419 	if (un->un_f_is_fibre == TRUE) {
7420 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7421 		    SCSI_VERSION_3) {
7422 			switch (un->un_interconnect_type) {
7423 			case SD_INTERCONNECT_FIBRE:
7424 			case SD_INTERCONNECT_SSA:
7425 				un->un_node_type = DDI_NT_BLOCK_WWN;
7426 				break;
7427 			default:
7428 				break;
7429 			}
7430 		}
7431 	}
7432 
7433 	/*
7434 	 * Initialize the Request Sense command for the target
7435 	 */
7436 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7437 		goto alloc_rqs_failed;
7438 	}
7439 
7440 	/*
7441 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7442 	 * with separate binary for sd and ssd.
7443 	 *
7444 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7445 	 * The hardcoded values will go away when Sparc uses 1 binary
7446 	 * for sd and ssd.  This hardcoded values need to match
7447 	 * SD_RETRY_COUNT in sddef.h
7448 	 * The value used is base on interconnect type.
7449 	 * fibre = 3, parallel = 5
7450 	 */
7451 #if defined(__i386) || defined(__amd64)
7452 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7453 #else
7454 	un->un_retry_count = SD_RETRY_COUNT;
7455 #endif
7456 
7457 	/*
7458 	 * Set the per disk retry count to the default number of retries
7459 	 * for disks and CDROMs. This value can be overridden by the
7460 	 * disk property list or an entry in sd.conf.
7461 	 */
7462 	un->un_notready_retry_count =
7463 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7464 	    : DISK_NOT_READY_RETRY_COUNT(un);
7465 
7466 	/*
7467 	 * Set the busy retry count to the default value of un_retry_count.
7468 	 * This can be overridden by entries in sd.conf or the device
7469 	 * config table.
7470 	 */
7471 	un->un_busy_retry_count = un->un_retry_count;
7472 
7473 	/*
7474 	 * Init the reset threshold for retries.  This number determines
7475 	 * how many retries must be performed before a reset can be issued
7476 	 * (for certain error conditions). This can be overridden by entries
7477 	 * in sd.conf or the device config table.
7478 	 */
7479 	un->un_reset_retry_count = (un->un_retry_count / 2);
7480 
7481 	/*
7482 	 * Set the victim_retry_count to the default un_retry_count
7483 	 */
7484 	un->un_victim_retry_count = (2 * un->un_retry_count);
7485 
7486 	/*
7487 	 * Set the reservation release timeout to the default value of
7488 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7489 	 * device config table.
7490 	 */
7491 	un->un_reserve_release_time = 5;
7492 
7493 	/*
7494 	 * Set up the default maximum transfer size. Note that this may
7495 	 * get updated later in the attach, when setting up default wide
7496 	 * operations for disks.
7497 	 */
7498 #if defined(__i386) || defined(__amd64)
7499 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7500 	un->un_partial_dma_supported = 1;
7501 #else
7502 	un->un_max_xfer_size = (uint_t)maxphys;
7503 #endif
7504 
7505 	/*
7506 	 * Get "allow bus device reset" property (defaults to "enabled" if
7507 	 * the property was not defined). This is to disable bus resets for
7508 	 * certain kinds of error recovery. Note: In the future when a run-time
7509 	 * fibre check is available the soft state flag should default to
7510 	 * enabled.
7511 	 */
7512 	if (un->un_f_is_fibre == TRUE) {
7513 		un->un_f_allow_bus_device_reset = TRUE;
7514 	} else {
7515 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7516 		    "allow-bus-device-reset", 1) != 0) {
7517 			un->un_f_allow_bus_device_reset = TRUE;
7518 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7519 			    "sd_unit_attach: un:0x%p Bus device reset "
7520 			    "enabled\n", un);
7521 		} else {
7522 			un->un_f_allow_bus_device_reset = FALSE;
7523 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7524 			    "sd_unit_attach: un:0x%p Bus device reset "
7525 			    "disabled\n", un);
7526 		}
7527 	}
7528 
7529 	/*
7530 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7531 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7532 	 *
7533 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7534 	 * property. The new "variant" property with a value of "atapi" has been
7535 	 * introduced so that future 'variants' of standard SCSI behavior (like
7536 	 * atapi) could be specified by the underlying HBA drivers by supplying
7537 	 * a new value for the "variant" property, instead of having to define a
7538 	 * new property.
7539 	 */
7540 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7541 		un->un_f_cfg_is_atapi = TRUE;
7542 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7543 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7544 	}
7545 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7546 	    &variantp) == DDI_PROP_SUCCESS) {
7547 		if (strcmp(variantp, "atapi") == 0) {
7548 			un->un_f_cfg_is_atapi = TRUE;
7549 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7550 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7551 		}
7552 		ddi_prop_free(variantp);
7553 	}
7554 
7555 	un->un_cmd_timeout	= SD_IO_TIME;
7556 
7557 	un->un_busy_timeout  = SD_BSY_TIMEOUT;
7558 
7559 	/* Info on current states, statuses, etc. (Updated frequently) */
7560 	un->un_state		= SD_STATE_NORMAL;
7561 	un->un_last_state	= SD_STATE_NORMAL;
7562 
7563 	/* Control & status info for command throttling */
7564 	un->un_throttle		= sd_max_throttle;
7565 	un->un_saved_throttle	= sd_max_throttle;
7566 	un->un_min_throttle	= sd_min_throttle;
7567 
7568 	if (un->un_f_is_fibre == TRUE) {
7569 		un->un_f_use_adaptive_throttle = TRUE;
7570 	} else {
7571 		un->un_f_use_adaptive_throttle = FALSE;
7572 	}
7573 
7574 	/* Removable media support. */
7575 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7576 	un->un_mediastate		= DKIO_NONE;
7577 	un->un_specified_mediastate	= DKIO_NONE;
7578 
7579 	/* CVs for suspend/resume (PM or DR) */
7580 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7581 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7582 
7583 	/* Power management support. */
7584 	un->un_power_level = SD_SPINDLE_UNINIT;
7585 
7586 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
7587 	un->un_f_wcc_inprog = 0;
7588 
7589 	/*
7590 	 * The open/close semaphore is used to serialize threads executing
7591 	 * in the driver's open & close entry point routines for a given
7592 	 * instance.
7593 	 */
7594 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
7595 
7596 	/*
7597 	 * The conf file entry and softstate variable is a forceful override,
7598 	 * meaning a non-zero value must be entered to change the default.
7599 	 */
7600 	un->un_f_disksort_disabled = FALSE;
7601 	un->un_f_rmw_type = SD_RMW_TYPE_DEFAULT;
7602 	un->un_f_enable_rmw = FALSE;
7603 
7604 	/*
7605 	 * GET EVENT STATUS NOTIFICATION media polling enabled by default, but
7606 	 * can be overridden via [s]sd-config-list "mmc-gesn-polling" property.
7607 	 */
7608 	un->un_f_mmc_gesn_polling = TRUE;
7609 
7610 	/*
7611 	 * Retrieve the properties from the static driver table or the driver
7612 	 * configuration file (.conf) for this unit and update the soft state
7613 	 * for the device as needed for the indicated properties.
7614 	 * Note: the property configuration needs to occur here as some of the
7615 	 * following routines may have dependencies on soft state flags set
7616 	 * as part of the driver property configuration.
7617 	 */
7618 	sd_read_unit_properties(un);
7619 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7620 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
7621 
7622 	/*
7623 	 * Only if a device has "hotpluggable" property, it is
7624 	 * treated as hotpluggable device. Otherwise, it is
7625 	 * regarded as non-hotpluggable one.
7626 	 */
7627 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
7628 	    -1) != -1) {
7629 		un->un_f_is_hotpluggable = TRUE;
7630 	}
7631 
7632 	/*
7633 	 * set unit's attributes(flags) according to "hotpluggable" and
7634 	 * RMB bit in INQUIRY data.
7635 	 */
7636 	sd_set_unit_attributes(un, devi);
7637 
7638 	/*
7639 	 * By default, we mark the capacity, lbasize, and geometry
7640 	 * as invalid. Only if we successfully read a valid capacity
7641 	 * will we update the un_blockcount and un_tgt_blocksize with the
7642 	 * valid values (the geometry will be validated later).
7643 	 */
7644 	un->un_f_blockcount_is_valid	= FALSE;
7645 	un->un_f_tgt_blocksize_is_valid	= FALSE;
7646 
7647 	/*
7648 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
7649 	 * otherwise.
7650 	 */
7651 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
7652 	un->un_blockcount = 0;
7653 
7654 	/*
7655 	 * physical sector size default to DEV_BSIZE currently.
7656 	 */
7657 	un->un_phy_blocksize = DEV_BSIZE;
7658 
7659 	/*
7660 	 * Set up the per-instance info needed to determine the correct
7661 	 * CDBs and other info for issuing commands to the target.
7662 	 */
7663 	sd_init_cdb_limits(un);
7664 
7665 	/*
7666 	 * Set up the IO chains to use, based upon the target type.
7667 	 */
7668 	if (un->un_f_non_devbsize_supported) {
7669 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7670 	} else {
7671 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7672 	}
7673 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7674 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
7675 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
7676 
7677 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
7678 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
7679 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
7680 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
7681 
7682 
7683 	if (ISCD(un)) {
7684 		un->un_additional_codes = sd_additional_codes;
7685 	} else {
7686 		un->un_additional_codes = NULL;
7687 	}
7688 
7689 	/*
7690 	 * Create the kstats here so they can be available for attach-time
7691 	 * routines that send commands to the unit (either polled or via
7692 	 * sd_send_scsi_cmd).
7693 	 *
7694 	 * Note: This is a critical sequence that needs to be maintained:
7695 	 *	1) Instantiate the kstats here, before any routines using the
7696 	 *	   iopath (i.e. sd_send_scsi_cmd).
7697 	 *	2) Instantiate and initialize the partition stats
7698 	 *	   (sd_set_pstats).
7699 	 *	3) Initialize the error stats (sd_set_errstats), following
7700 	 *	   sd_validate_geometry(),sd_register_devid(),
7701 	 *	   and sd_cache_control().
7702 	 */
7703 
7704 	un->un_stats = kstat_create(sd_label, instance,
7705 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
7706 	if (un->un_stats != NULL) {
7707 		un->un_stats->ks_lock = SD_MUTEX(un);
7708 		kstat_install(un->un_stats);
7709 	}
7710 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7711 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
7712 
7713 	sd_create_errstats(un, instance);
7714 	if (un->un_errstats == NULL) {
7715 		goto create_errstats_failed;
7716 	}
7717 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7718 	    "sd_unit_attach: un:0x%p errstats created\n", un);
7719 
7720 	/*
7721 	 * The following if/else code was relocated here from below as part
7722 	 * of the fix for bug (4430280). However with the default setup added
7723 	 * on entry to this routine, it's no longer absolutely necessary for
7724 	 * this to be before the call to sd_spin_up_unit.
7725 	 */
7726 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
7727 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
7728 		    (devp->sd_inq->inq_ansi == 5)) &&
7729 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
7730 
7731 		/*
7732 		 * If tagged queueing is supported by the target
7733 		 * and by the host adapter then we will enable it
7734 		 */
7735 		un->un_tagflags = 0;
7736 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
7737 		    (un->un_f_arq_enabled == TRUE)) {
7738 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
7739 			    1, 1) == 1) {
7740 				un->un_tagflags = FLAG_STAG;
7741 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7742 				    "sd_unit_attach: un:0x%p tag queueing "
7743 				    "enabled\n", un);
7744 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
7745 			    "untagged-qing", 0) == 1) {
7746 				un->un_f_opt_queueing = TRUE;
7747 				un->un_saved_throttle = un->un_throttle =
7748 				    min(un->un_throttle, 3);
7749 			} else {
7750 				un->un_f_opt_queueing = FALSE;
7751 				un->un_saved_throttle = un->un_throttle = 1;
7752 			}
7753 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
7754 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
7755 			/* The Host Adapter supports internal queueing. */
7756 			un->un_f_opt_queueing = TRUE;
7757 			un->un_saved_throttle = un->un_throttle =
7758 			    min(un->un_throttle, 3);
7759 		} else {
7760 			un->un_f_opt_queueing = FALSE;
7761 			un->un_saved_throttle = un->un_throttle = 1;
7762 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7763 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
7764 		}
7765 
7766 		/*
7767 		 * Enable large transfers for SATA/SAS drives
7768 		 */
7769 		if (SD_IS_SERIAL(un)) {
7770 			un->un_max_xfer_size =
7771 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7772 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7773 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7774 			    "sd_unit_attach: un:0x%p max transfer "
7775 			    "size=0x%x\n", un, un->un_max_xfer_size);
7776 
7777 		}
7778 
7779 		/* Setup or tear down default wide operations for disks */
7780 
7781 		/*
7782 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
7783 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
7784 		 * system and be set to different values. In the future this
7785 		 * code may need to be updated when the ssd module is
7786 		 * obsoleted and removed from the system. (4299588)
7787 		 */
7788 		if (SD_IS_PARALLEL_SCSI(un) &&
7789 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
7790 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
7791 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7792 			    1, 1) == 1) {
7793 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7794 				    "sd_unit_attach: un:0x%p Wide Transfer "
7795 				    "enabled\n", un);
7796 			}
7797 
7798 			/*
7799 			 * If tagged queuing has also been enabled, then
7800 			 * enable large xfers
7801 			 */
7802 			if (un->un_saved_throttle == sd_max_throttle) {
7803 				un->un_max_xfer_size =
7804 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7805 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7806 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7807 				    "sd_unit_attach: un:0x%p max transfer "
7808 				    "size=0x%x\n", un, un->un_max_xfer_size);
7809 			}
7810 		} else {
7811 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7812 			    0, 1) == 1) {
7813 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7814 				    "sd_unit_attach: un:0x%p "
7815 				    "Wide Transfer disabled\n", un);
7816 			}
7817 		}
7818 	} else {
7819 		un->un_tagflags = FLAG_STAG;
7820 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7821 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7822 	}
7823 
7824 	/*
7825 	 * If this target supports LUN reset, try to enable it.
7826 	 */
7827 	if (un->un_f_lun_reset_enabled) {
7828 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7829 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7830 			    "un:0x%p lun_reset capability set\n", un);
7831 		} else {
7832 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7833 			    "un:0x%p lun-reset capability not set\n", un);
7834 		}
7835 	}
7836 
7837 	/*
7838 	 * Adjust the maximum transfer size. This is to fix
7839 	 * the problem of partial DMA support on SPARC. Some
7840 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7841 	 * size, which requires partial DMA support on SPARC.
7842 	 * In the future the SPARC pci nexus driver may solve
7843 	 * the problem instead of this fix.
7844 	 */
7845 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7846 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7847 		/* We need DMA partial even on sparc to ensure sddump() works */
7848 		un->un_max_xfer_size = max_xfer_size;
7849 		if (un->un_partial_dma_supported == 0)
7850 			un->un_partial_dma_supported = 1;
7851 	}
7852 	if (ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7853 	    DDI_PROP_DONTPASS, "buf_break", 0) == 1) {
7854 		if (ddi_xbuf_attr_setup_brk(un->un_xbuf_attr,
7855 		    un->un_max_xfer_size) == 1) {
7856 			un->un_buf_breakup_supported = 1;
7857 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7858 			    "un:0x%p Buf breakup enabled\n", un);
7859 		}
7860 	}
7861 
7862 	/*
7863 	 * Set PKT_DMA_PARTIAL flag.
7864 	 */
7865 	if (un->un_partial_dma_supported == 1) {
7866 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7867 	} else {
7868 		un->un_pkt_flags = 0;
7869 	}
7870 
7871 	/* Initialize sd_ssc_t for internal uscsi commands */
7872 	ssc = sd_ssc_init(un);
7873 	scsi_fm_init(devp);
7874 
7875 	/*
7876 	 * Allocate memory for SCSI FMA stuffs.
7877 	 */
7878 	un->un_fm_private =
7879 	    kmem_zalloc(sizeof (struct sd_fm_internal), KM_SLEEP);
7880 	sfip = (struct sd_fm_internal *)un->un_fm_private;
7881 	sfip->fm_ssc.ssc_uscsi_cmd = &sfip->fm_ucmd;
7882 	sfip->fm_ssc.ssc_uscsi_info = &sfip->fm_uinfo;
7883 	sfip->fm_ssc.ssc_un = un;
7884 
7885 	if (ISCD(un) ||
7886 	    un->un_f_has_removable_media ||
7887 	    devp->sd_fm_capable == DDI_FM_NOT_CAPABLE) {
7888 		/*
7889 		 * We don't touch CDROM or the DDI_FM_NOT_CAPABLE device.
7890 		 * Their log are unchanged.
7891 		 */
7892 		sfip->fm_log_level = SD_FM_LOG_NSUP;
7893 	} else {
7894 		/*
7895 		 * If enter here, it should be non-CDROM and FM-capable
7896 		 * device, and it will not keep the old scsi_log as before
7897 		 * in /var/adm/messages. However, the property
7898 		 * "fm-scsi-log" will control whether the FM telemetry will
7899 		 * be logged in /var/adm/messages.
7900 		 */
7901 		int fm_scsi_log;
7902 		fm_scsi_log = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7903 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "fm-scsi-log", 0);
7904 
7905 		if (fm_scsi_log)
7906 			sfip->fm_log_level = SD_FM_LOG_EREPORT;
7907 		else
7908 			sfip->fm_log_level = SD_FM_LOG_SILENT;
7909 	}
7910 
7911 	/*
7912 	 * At this point in the attach, we have enough info in the
7913 	 * soft state to be able to issue commands to the target.
7914 	 *
7915 	 * All command paths used below MUST issue their commands as
7916 	 * SD_PATH_DIRECT. This is important as intermediate layers
7917 	 * are not all initialized yet (such as PM).
7918 	 */
7919 
7920 	/*
7921 	 * Send a TEST UNIT READY command to the device. This should clear
7922 	 * any outstanding UNIT ATTENTION that may be present.
7923 	 *
7924 	 * Note: Don't check for success, just track if there is a reservation,
7925 	 * this is a throw away command to clear any unit attentions.
7926 	 *
7927 	 * Note: This MUST be the first command issued to the target during
7928 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7929 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7930 	 * with attempts at spinning up a device with no media.
7931 	 */
7932 	status = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
7933 	if (status != 0) {
7934 		if (status == EACCES)
7935 			reservation_flag = SD_TARGET_IS_RESERVED;
7936 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7937 	}
7938 
7939 	/*
7940 	 * If the device is NOT a removable media device, attempt to spin
7941 	 * it up (using the START_STOP_UNIT command) and read its capacity
7942 	 * (using the READ CAPACITY command).  Note, however, that either
7943 	 * of these could fail and in some cases we would continue with
7944 	 * the attach despite the failure (see below).
7945 	 */
7946 	if (un->un_f_descr_format_supported) {
7947 
7948 		switch (sd_spin_up_unit(ssc)) {
7949 		case 0:
7950 			/*
7951 			 * Spin-up was successful; now try to read the
7952 			 * capacity.  If successful then save the results
7953 			 * and mark the capacity & lbasize as valid.
7954 			 */
7955 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7956 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7957 
7958 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
7959 			    &lbasize, SD_PATH_DIRECT);
7960 
7961 			switch (status) {
7962 			case 0: {
7963 				if (capacity > DK_MAX_BLOCKS) {
7964 #ifdef _LP64
7965 					if ((capacity + 1) >
7966 					    SD_GROUP1_MAX_ADDRESS) {
7967 						/*
7968 						 * Enable descriptor format
7969 						 * sense data so that we can
7970 						 * get 64 bit sense data
7971 						 * fields.
7972 						 */
7973 						sd_enable_descr_sense(ssc);
7974 					}
7975 #else
7976 					/* 32-bit kernels can't handle this */
7977 					scsi_log(SD_DEVINFO(un),
7978 					    sd_label, CE_WARN,
7979 					    "disk has %llu blocks, which "
7980 					    "is too large for a 32-bit "
7981 					    "kernel", capacity);
7982 
7983 #if defined(__i386) || defined(__amd64)
7984 					/*
7985 					 * 1TB disk was treated as (1T - 512)B
7986 					 * in the past, so that it might have
7987 					 * valid VTOC and solaris partitions,
7988 					 * we have to allow it to continue to
7989 					 * work.
7990 					 */
7991 					if (capacity -1 > DK_MAX_BLOCKS)
7992 #endif
7993 					goto spinup_failed;
7994 #endif
7995 				}
7996 
7997 				/*
7998 				 * Here it's not necessary to check the case:
7999 				 * the capacity of the device is bigger than
8000 				 * what the max hba cdb can support. Because
8001 				 * sd_send_scsi_READ_CAPACITY will retrieve
8002 				 * the capacity by sending USCSI command, which
8003 				 * is constrained by the max hba cdb. Actually,
8004 				 * sd_send_scsi_READ_CAPACITY will return
8005 				 * EINVAL when using bigger cdb than required
8006 				 * cdb length. Will handle this case in
8007 				 * "case EINVAL".
8008 				 */
8009 
8010 				/*
8011 				 * The following relies on
8012 				 * sd_send_scsi_READ_CAPACITY never
8013 				 * returning 0 for capacity and/or lbasize.
8014 				 */
8015 				sd_update_block_info(un, lbasize, capacity);
8016 
8017 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8018 				    "sd_unit_attach: un:0x%p capacity = %ld "
8019 				    "blocks; lbasize= %ld.\n", un,
8020 				    un->un_blockcount, un->un_tgt_blocksize);
8021 
8022 				break;
8023 			}
8024 			case EINVAL:
8025 				/*
8026 				 * In the case where the max-cdb-length property
8027 				 * is smaller than the required CDB length for
8028 				 * a SCSI device, a target driver can fail to
8029 				 * attach to that device.
8030 				 */
8031 				scsi_log(SD_DEVINFO(un),
8032 				    sd_label, CE_WARN,
8033 				    "disk capacity is too large "
8034 				    "for current cdb length");
8035 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8036 
8037 				goto spinup_failed;
8038 			case EACCES:
8039 				/*
8040 				 * Should never get here if the spin-up
8041 				 * succeeded, but code it in anyway.
8042 				 * From here, just continue with the attach...
8043 				 */
8044 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8045 				    "sd_unit_attach: un:0x%p "
8046 				    "sd_send_scsi_READ_CAPACITY "
8047 				    "returned reservation conflict\n", un);
8048 				reservation_flag = SD_TARGET_IS_RESERVED;
8049 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8050 				break;
8051 			default:
8052 				/*
8053 				 * Likewise, should never get here if the
8054 				 * spin-up succeeded. Just continue with
8055 				 * the attach...
8056 				 */
8057 				if (status == EIO)
8058 					sd_ssc_assessment(ssc,
8059 					    SD_FMT_STATUS_CHECK);
8060 				else
8061 					sd_ssc_assessment(ssc,
8062 					    SD_FMT_IGNORE);
8063 				break;
8064 			}
8065 			break;
8066 		case EACCES:
8067 			/*
8068 			 * Device is reserved by another host.  In this case
8069 			 * we could not spin it up or read the capacity, but
8070 			 * we continue with the attach anyway.
8071 			 */
8072 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8073 			    "sd_unit_attach: un:0x%p spin-up reservation "
8074 			    "conflict.\n", un);
8075 			reservation_flag = SD_TARGET_IS_RESERVED;
8076 			break;
8077 		default:
8078 			/* Fail the attach if the spin-up failed. */
8079 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8080 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
8081 			goto spinup_failed;
8082 		}
8083 
8084 	}
8085 
8086 	/*
8087 	 * Check to see if this is a MMC drive
8088 	 */
8089 	if (ISCD(un)) {
8090 		sd_set_mmc_caps(ssc);
8091 	}
8092 
8093 	/*
8094 	 * Add a zero-length attribute to tell the world we support
8095 	 * kernel ioctls (for layered drivers)
8096 	 */
8097 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8098 	    DDI_KERNEL_IOCTL, NULL, 0);
8099 
8100 	/*
8101 	 * Add a boolean property to tell the world we support
8102 	 * the B_FAILFAST flag (for layered drivers)
8103 	 */
8104 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8105 	    "ddi-failfast-supported", NULL, 0);
8106 
8107 	/*
8108 	 * Initialize power management
8109 	 */
8110 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
8111 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
8112 	sd_setup_pm(ssc, devi);
8113 	if (un->un_f_pm_is_enabled == FALSE) {
8114 		/*
8115 		 * For performance, point to a jump table that does
8116 		 * not include pm.
8117 		 * The direct and priority chains don't change with PM.
8118 		 *
8119 		 * Note: this is currently done based on individual device
8120 		 * capabilities. When an interface for determining system
8121 		 * power enabled state becomes available, or when additional
8122 		 * layers are added to the command chain, these values will
8123 		 * have to be re-evaluated for correctness.
8124 		 */
8125 		if (un->un_f_non_devbsize_supported) {
8126 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
8127 		} else {
8128 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
8129 		}
8130 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8131 	}
8132 
8133 	/*
8134 	 * This property is set to 0 by HA software to avoid retries
8135 	 * on a reserved disk. (The preferred property name is
8136 	 * "retry-on-reservation-conflict") (1189689)
8137 	 *
8138 	 * Note: The use of a global here can have unintended consequences. A
8139 	 * per instance variable is preferable to match the capabilities of
8140 	 * different underlying hba's (4402600)
8141 	 */
8142 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
8143 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
8144 	    sd_retry_on_reservation_conflict);
8145 	if (sd_retry_on_reservation_conflict != 0) {
8146 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
8147 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
8148 		    sd_retry_on_reservation_conflict);
8149 	}
8150 
8151 	/* Set up options for QFULL handling. */
8152 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8153 	    "qfull-retries", -1)) != -1) {
8154 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
8155 		    rval, 1);
8156 	}
8157 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8158 	    "qfull-retry-interval", -1)) != -1) {
8159 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
8160 		    rval, 1);
8161 	}
8162 
8163 	/*
8164 	 * This just prints a message that announces the existence of the
8165 	 * device. The message is always printed in the system logfile, but
8166 	 * only appears on the console if the system is booted with the
8167 	 * -v (verbose) argument.
8168 	 */
8169 	ddi_report_dev(devi);
8170 
8171 	un->un_mediastate = DKIO_NONE;
8172 
8173 	/*
8174 	 * Check if this is a SSD(Solid State Drive).
8175 	 */
8176 	sd_check_solid_state(ssc);
8177 
8178 	/*
8179 	 * Check whether the drive is in emulation mode.
8180 	 */
8181 	sd_check_emulation_mode(ssc);
8182 
8183 	cmlb_alloc_handle(&un->un_cmlbhandle);
8184 
8185 #if defined(__i386) || defined(__amd64)
8186 	/*
8187 	 * On x86, compensate for off-by-1 legacy error
8188 	 */
8189 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
8190 	    (lbasize == un->un_sys_blocksize))
8191 		offbyone = CMLB_OFF_BY_ONE;
8192 #endif
8193 
8194 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
8195 	    VOID2BOOLEAN(un->un_f_has_removable_media != 0),
8196 	    VOID2BOOLEAN(un->un_f_is_hotpluggable != 0),
8197 	    un->un_node_type, offbyone, un->un_cmlbhandle,
8198 	    (void *)SD_PATH_DIRECT) != 0) {
8199 		goto cmlb_attach_failed;
8200 	}
8201 
8202 
8203 	/*
8204 	 * Read and validate the device's geometry (ie, disk label)
8205 	 * A new unformatted drive will not have a valid geometry, but
8206 	 * the driver needs to successfully attach to this device so
8207 	 * the drive can be formatted via ioctls.
8208 	 */
8209 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
8210 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
8211 
8212 	mutex_enter(SD_MUTEX(un));
8213 
8214 	/*
8215 	 * Read and initialize the devid for the unit.
8216 	 */
8217 	if (un->un_f_devid_supported) {
8218 		sd_register_devid(ssc, devi, reservation_flag);
8219 	}
8220 	mutex_exit(SD_MUTEX(un));
8221 
8222 #if (defined(__fibre))
8223 	/*
8224 	 * Register callbacks for fibre only.  You can't do this solely
8225 	 * on the basis of the devid_type because this is hba specific.
8226 	 * We need to query our hba capabilities to find out whether to
8227 	 * register or not.
8228 	 */
8229 	if (un->un_f_is_fibre) {
8230 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
8231 			sd_init_event_callbacks(un);
8232 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8233 			    "sd_unit_attach: un:0x%p event callbacks inserted",
8234 			    un);
8235 		}
8236 	}
8237 #endif
8238 
8239 	if (un->un_f_opt_disable_cache == TRUE) {
8240 		/*
8241 		 * Disable both read cache and write cache.  This is
8242 		 * the historic behavior of the keywords in the config file.
8243 		 */
8244 		if (sd_cache_control(ssc, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
8245 		    0) {
8246 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8247 			    "sd_unit_attach: un:0x%p Could not disable "
8248 			    "caching", un);
8249 			goto devid_failed;
8250 		}
8251 	}
8252 
8253 	/*
8254 	 * Check the value of the WCE bit now and
8255 	 * set un_f_write_cache_enabled accordingly.
8256 	 */
8257 	(void) sd_get_write_cache_enabled(ssc, &wc_enabled);
8258 	mutex_enter(SD_MUTEX(un));
8259 	un->un_f_write_cache_enabled = (wc_enabled != 0);
8260 	mutex_exit(SD_MUTEX(un));
8261 
8262 	if ((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR &&
8263 	    un->un_tgt_blocksize != DEV_BSIZE) ||
8264 	    un->un_f_enable_rmw) {
8265 		if (!(un->un_wm_cache)) {
8266 			(void) snprintf(name_str, sizeof (name_str),
8267 			    "%s%d_cache",
8268 			    ddi_driver_name(SD_DEVINFO(un)),
8269 			    ddi_get_instance(SD_DEVINFO(un)));
8270 			un->un_wm_cache = kmem_cache_create(
8271 			    name_str, sizeof (struct sd_w_map),
8272 			    8, sd_wm_cache_constructor,
8273 			    sd_wm_cache_destructor, NULL,
8274 			    (void *)un, NULL, 0);
8275 			if (!(un->un_wm_cache)) {
8276 				goto wm_cache_failed;
8277 			}
8278 		}
8279 	}
8280 
8281 	/*
8282 	 * Check the value of the NV_SUP bit and set
8283 	 * un_f_suppress_cache_flush accordingly.
8284 	 */
8285 	sd_get_nv_sup(ssc);
8286 
8287 	/*
8288 	 * Find out what type of reservation this disk supports.
8289 	 */
8290 	status = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS, 0, NULL);
8291 
8292 	switch (status) {
8293 	case 0:
8294 		/*
8295 		 * SCSI-3 reservations are supported.
8296 		 */
8297 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8298 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8299 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
8300 		break;
8301 	case ENOTSUP:
8302 		/*
8303 		 * The PERSISTENT RESERVE IN command would not be recognized by
8304 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
8305 		 */
8306 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8307 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
8308 		un->un_reservation_type = SD_SCSI2_RESERVATION;
8309 
8310 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8311 		break;
8312 	default:
8313 		/*
8314 		 * default to SCSI-3 reservations
8315 		 */
8316 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8317 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
8318 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8319 
8320 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8321 		break;
8322 	}
8323 
8324 	/*
8325 	 * Set the pstat and error stat values here, so data obtained during the
8326 	 * previous attach-time routines is available.
8327 	 *
8328 	 * Note: This is a critical sequence that needs to be maintained:
8329 	 *	1) Instantiate the kstats before any routines using the iopath
8330 	 *	   (i.e. sd_send_scsi_cmd).
8331 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8332 	 *	   stats (sd_set_pstats)here, following
8333 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
8334 	 *	   sd_cache_control().
8335 	 */
8336 
8337 	if (un->un_f_pkstats_enabled && geom_label_valid) {
8338 		sd_set_pstats(un);
8339 		SD_TRACE(SD_LOG_IO_PARTITION, un,
8340 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
8341 	}
8342 
8343 	sd_set_errstats(un);
8344 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8345 	    "sd_unit_attach: un:0x%p errstats set\n", un);
8346 
8347 
8348 	/*
8349 	 * After successfully attaching an instance, we record the information
8350 	 * of how many luns have been attached on the relative target and
8351 	 * controller for parallel SCSI. This information is used when sd tries
8352 	 * to set the tagged queuing capability in HBA.
8353 	 */
8354 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8355 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
8356 	}
8357 
8358 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8359 	    "sd_unit_attach: un:0x%p exit success\n", un);
8360 
8361 	/* Uninitialize sd_ssc_t pointer */
8362 	sd_ssc_fini(ssc);
8363 
8364 	return (DDI_SUCCESS);
8365 
8366 	/*
8367 	 * An error occurred during the attach; clean up & return failure.
8368 	 */
8369 wm_cache_failed:
8370 devid_failed:
8371 
8372 setup_pm_failed:
8373 	ddi_remove_minor_node(devi, NULL);
8374 
8375 cmlb_attach_failed:
8376 	/*
8377 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8378 	 */
8379 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8380 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8381 
8382 	/*
8383 	 * Refer to the comments of setting tagged-qing in the beginning of
8384 	 * sd_unit_attach. We can only disable tagged queuing when there is
8385 	 * no lun attached on the target.
8386 	 */
8387 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
8388 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8389 	}
8390 
8391 	if (un->un_f_is_fibre == FALSE) {
8392 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8393 	}
8394 
8395 spinup_failed:
8396 
8397 	/* Uninitialize sd_ssc_t pointer */
8398 	sd_ssc_fini(ssc);
8399 
8400 	mutex_enter(SD_MUTEX(un));
8401 
8402 	/* Deallocate SCSI FMA memory spaces */
8403 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8404 
8405 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
8406 	if (un->un_direct_priority_timeid != NULL) {
8407 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8408 		un->un_direct_priority_timeid = NULL;
8409 		mutex_exit(SD_MUTEX(un));
8410 		(void) untimeout(temp_id);
8411 		mutex_enter(SD_MUTEX(un));
8412 	}
8413 
8414 	/* Cancel any pending start/stop timeouts */
8415 	if (un->un_startstop_timeid != NULL) {
8416 		timeout_id_t temp_id = un->un_startstop_timeid;
8417 		un->un_startstop_timeid = NULL;
8418 		mutex_exit(SD_MUTEX(un));
8419 		(void) untimeout(temp_id);
8420 		mutex_enter(SD_MUTEX(un));
8421 	}
8422 
8423 	/* Cancel any pending reset-throttle timeouts */
8424 	if (un->un_reset_throttle_timeid != NULL) {
8425 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8426 		un->un_reset_throttle_timeid = NULL;
8427 		mutex_exit(SD_MUTEX(un));
8428 		(void) untimeout(temp_id);
8429 		mutex_enter(SD_MUTEX(un));
8430 	}
8431 
8432 	/* Cancel rmw warning message timeouts */
8433 	if (un->un_rmw_msg_timeid != NULL) {
8434 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8435 		un->un_rmw_msg_timeid = NULL;
8436 		mutex_exit(SD_MUTEX(un));
8437 		(void) untimeout(temp_id);
8438 		mutex_enter(SD_MUTEX(un));
8439 	}
8440 
8441 	/* Cancel any pending retry timeouts */
8442 	if (un->un_retry_timeid != NULL) {
8443 		timeout_id_t temp_id = un->un_retry_timeid;
8444 		un->un_retry_timeid = NULL;
8445 		mutex_exit(SD_MUTEX(un));
8446 		(void) untimeout(temp_id);
8447 		mutex_enter(SD_MUTEX(un));
8448 	}
8449 
8450 	/* Cancel any pending delayed cv broadcast timeouts */
8451 	if (un->un_dcvb_timeid != NULL) {
8452 		timeout_id_t temp_id = un->un_dcvb_timeid;
8453 		un->un_dcvb_timeid = NULL;
8454 		mutex_exit(SD_MUTEX(un));
8455 		(void) untimeout(temp_id);
8456 		mutex_enter(SD_MUTEX(un));
8457 	}
8458 
8459 	mutex_exit(SD_MUTEX(un));
8460 
8461 	/* There should not be any in-progress I/O so ASSERT this check */
8462 	ASSERT(un->un_ncmds_in_transport == 0);
8463 	ASSERT(un->un_ncmds_in_driver == 0);
8464 
8465 	/* Do not free the softstate if the callback routine is active */
8466 	sd_sync_with_callback(un);
8467 
8468 	/*
8469 	 * Partition stats apparently are not used with removables. These would
8470 	 * not have been created during attach, so no need to clean them up...
8471 	 */
8472 	if (un->un_errstats != NULL) {
8473 		kstat_delete(un->un_errstats);
8474 		un->un_errstats = NULL;
8475 	}
8476 
8477 create_errstats_failed:
8478 
8479 	if (un->un_stats != NULL) {
8480 		kstat_delete(un->un_stats);
8481 		un->un_stats = NULL;
8482 	}
8483 
8484 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8485 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8486 
8487 	ddi_prop_remove_all(devi);
8488 	sema_destroy(&un->un_semoclose);
8489 	cv_destroy(&un->un_state_cv);
8490 
8491 getrbuf_failed:
8492 
8493 	sd_free_rqs(un);
8494 
8495 alloc_rqs_failed:
8496 
8497 	devp->sd_private = NULL;
8498 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8499 
8500 get_softstate_failed:
8501 	/*
8502 	 * Note: the man pages are unclear as to whether or not doing a
8503 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8504 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8505 	 * ddi_get_soft_state() fails.  The implication seems to be
8506 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8507 	 */
8508 #ifndef XPV_HVM_DRIVER
8509 	ddi_soft_state_free(sd_state, instance);
8510 #endif /* !XPV_HVM_DRIVER */
8511 
8512 probe_failed:
8513 	scsi_unprobe(devp);
8514 
8515 	return (DDI_FAILURE);
8516 }
8517 
8518 
8519 /*
8520  *    Function: sd_unit_detach
8521  *
8522  * Description: Performs DDI_DETACH processing for sddetach().
8523  *
8524  * Return Code: DDI_SUCCESS
8525  *		DDI_FAILURE
8526  *
8527  *     Context: Kernel thread context
8528  */
8529 
8530 static int
8531 sd_unit_detach(dev_info_t *devi)
8532 {
8533 	struct scsi_device	*devp;
8534 	struct sd_lun		*un;
8535 	int			i;
8536 	int			tgt;
8537 	dev_t			dev;
8538 	dev_info_t		*pdip = ddi_get_parent(devi);
8539 #ifndef XPV_HVM_DRIVER
8540 	int			instance = ddi_get_instance(devi);
8541 #endif /* !XPV_HVM_DRIVER */
8542 
8543 	mutex_enter(&sd_detach_mutex);
8544 
8545 	/*
8546 	 * Fail the detach for any of the following:
8547 	 *  - Unable to get the sd_lun struct for the instance
8548 	 *  - A layered driver has an outstanding open on the instance
8549 	 *  - Another thread is already detaching this instance
8550 	 *  - Another thread is currently performing an open
8551 	 */
8552 	devp = ddi_get_driver_private(devi);
8553 	if ((devp == NULL) ||
8554 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8555 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
8556 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
8557 		mutex_exit(&sd_detach_mutex);
8558 		return (DDI_FAILURE);
8559 	}
8560 
8561 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8562 
8563 	/*
8564 	 * Mark this instance as currently in a detach, to inhibit any
8565 	 * opens from a layered driver.
8566 	 */
8567 	un->un_detach_count++;
8568 	mutex_exit(&sd_detach_mutex);
8569 
8570 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
8571 	    SCSI_ADDR_PROP_TARGET, -1);
8572 
8573 	dev = sd_make_device(SD_DEVINFO(un));
8574 
8575 #ifndef lint
8576 	_NOTE(COMPETING_THREADS_NOW);
8577 #endif
8578 
8579 	mutex_enter(SD_MUTEX(un));
8580 
8581 	/*
8582 	 * Fail the detach if there are any outstanding layered
8583 	 * opens on this device.
8584 	 */
8585 	for (i = 0; i < NDKMAP; i++) {
8586 		if (un->un_ocmap.lyropen[i] != 0) {
8587 			goto err_notclosed;
8588 		}
8589 	}
8590 
8591 	/*
8592 	 * Verify there are NO outstanding commands issued to this device.
8593 	 * ie, un_ncmds_in_transport == 0.
8594 	 * It's possible to have outstanding commands through the physio
8595 	 * code path, even though everything's closed.
8596 	 */
8597 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8598 	    (un->un_direct_priority_timeid != NULL) ||
8599 	    (un->un_state == SD_STATE_RWAIT)) {
8600 		mutex_exit(SD_MUTEX(un));
8601 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8602 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8603 		goto err_stillbusy;
8604 	}
8605 
8606 	/*
8607 	 * If we have the device reserved, release the reservation.
8608 	 */
8609 	if ((un->un_resvd_status & SD_RESERVE) &&
8610 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8611 		mutex_exit(SD_MUTEX(un));
8612 		/*
8613 		 * Note: sd_reserve_release sends a command to the device
8614 		 * via the sd_ioctlcmd() path, and can sleep.
8615 		 */
8616 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8617 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8618 			    "sd_dr_detach: Cannot release reservation \n");
8619 		}
8620 	} else {
8621 		mutex_exit(SD_MUTEX(un));
8622 	}
8623 
8624 	/*
8625 	 * Untimeout any reserve recover, throttle reset, restart unit
8626 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8627 	 * from getting nulled by their callback functions.
8628 	 */
8629 	mutex_enter(SD_MUTEX(un));
8630 	if (un->un_resvd_timeid != NULL) {
8631 		timeout_id_t temp_id = un->un_resvd_timeid;
8632 		un->un_resvd_timeid = NULL;
8633 		mutex_exit(SD_MUTEX(un));
8634 		(void) untimeout(temp_id);
8635 		mutex_enter(SD_MUTEX(un));
8636 	}
8637 
8638 	if (un->un_reset_throttle_timeid != NULL) {
8639 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8640 		un->un_reset_throttle_timeid = NULL;
8641 		mutex_exit(SD_MUTEX(un));
8642 		(void) untimeout(temp_id);
8643 		mutex_enter(SD_MUTEX(un));
8644 	}
8645 
8646 	if (un->un_startstop_timeid != NULL) {
8647 		timeout_id_t temp_id = un->un_startstop_timeid;
8648 		un->un_startstop_timeid = NULL;
8649 		mutex_exit(SD_MUTEX(un));
8650 		(void) untimeout(temp_id);
8651 		mutex_enter(SD_MUTEX(un));
8652 	}
8653 
8654 	if (un->un_rmw_msg_timeid != NULL) {
8655 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8656 		un->un_rmw_msg_timeid = NULL;
8657 		mutex_exit(SD_MUTEX(un));
8658 		(void) untimeout(temp_id);
8659 		mutex_enter(SD_MUTEX(un));
8660 	}
8661 
8662 	if (un->un_dcvb_timeid != NULL) {
8663 		timeout_id_t temp_id = un->un_dcvb_timeid;
8664 		un->un_dcvb_timeid = NULL;
8665 		mutex_exit(SD_MUTEX(un));
8666 		(void) untimeout(temp_id);
8667 	} else {
8668 		mutex_exit(SD_MUTEX(un));
8669 	}
8670 
8671 	/* Remove any pending reservation reclaim requests for this device */
8672 	sd_rmv_resv_reclaim_req(dev);
8673 
8674 	mutex_enter(SD_MUTEX(un));
8675 
8676 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8677 	if (un->un_direct_priority_timeid != NULL) {
8678 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8679 		un->un_direct_priority_timeid = NULL;
8680 		mutex_exit(SD_MUTEX(un));
8681 		(void) untimeout(temp_id);
8682 		mutex_enter(SD_MUTEX(un));
8683 	}
8684 
8685 	/* Cancel any active multi-host disk watch thread requests */
8686 	if (un->un_mhd_token != NULL) {
8687 		mutex_exit(SD_MUTEX(un));
8688 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8689 		if (scsi_watch_request_terminate(un->un_mhd_token,
8690 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8691 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8692 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8693 			/*
8694 			 * Note: We are returning here after having removed
8695 			 * some driver timeouts above. This is consistent with
8696 			 * the legacy implementation but perhaps the watch
8697 			 * terminate call should be made with the wait flag set.
8698 			 */
8699 			goto err_stillbusy;
8700 		}
8701 		mutex_enter(SD_MUTEX(un));
8702 		un->un_mhd_token = NULL;
8703 	}
8704 
8705 	if (un->un_swr_token != NULL) {
8706 		mutex_exit(SD_MUTEX(un));
8707 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8708 		if (scsi_watch_request_terminate(un->un_swr_token,
8709 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8710 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8711 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8712 			/*
8713 			 * Note: We are returning here after having removed
8714 			 * some driver timeouts above. This is consistent with
8715 			 * the legacy implementation but perhaps the watch
8716 			 * terminate call should be made with the wait flag set.
8717 			 */
8718 			goto err_stillbusy;
8719 		}
8720 		mutex_enter(SD_MUTEX(un));
8721 		un->un_swr_token = NULL;
8722 	}
8723 
8724 	mutex_exit(SD_MUTEX(un));
8725 
8726 	/*
8727 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8728 	 * if we have not registered one.
8729 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8730 	 */
8731 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8732 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8733 
8734 	/*
8735 	 * protect the timeout pointers from getting nulled by
8736 	 * their callback functions during the cancellation process.
8737 	 * In such a scenario untimeout can be invoked with a null value.
8738 	 */
8739 	_NOTE(NO_COMPETING_THREADS_NOW);
8740 
8741 	mutex_enter(&un->un_pm_mutex);
8742 	if (un->un_pm_idle_timeid != NULL) {
8743 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8744 		un->un_pm_idle_timeid = NULL;
8745 		mutex_exit(&un->un_pm_mutex);
8746 
8747 		/*
8748 		 * Timeout is active; cancel it.
8749 		 * Note that it'll never be active on a device
8750 		 * that does not support PM therefore we don't
8751 		 * have to check before calling pm_idle_component.
8752 		 */
8753 		(void) untimeout(temp_id);
8754 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8755 		mutex_enter(&un->un_pm_mutex);
8756 	}
8757 
8758 	/*
8759 	 * Check whether there is already a timeout scheduled for power
8760 	 * management. If yes then don't lower the power here, that's.
8761 	 * the timeout handler's job.
8762 	 */
8763 	if (un->un_pm_timeid != NULL) {
8764 		timeout_id_t temp_id = un->un_pm_timeid;
8765 		un->un_pm_timeid = NULL;
8766 		mutex_exit(&un->un_pm_mutex);
8767 		/*
8768 		 * Timeout is active; cancel it.
8769 		 * Note that it'll never be active on a device
8770 		 * that does not support PM therefore we don't
8771 		 * have to check before calling pm_idle_component.
8772 		 */
8773 		(void) untimeout(temp_id);
8774 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8775 
8776 	} else {
8777 		mutex_exit(&un->un_pm_mutex);
8778 		if ((un->un_f_pm_is_enabled == TRUE) &&
8779 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_PM_STATE_STOPPED(un))
8780 		    != DDI_SUCCESS)) {
8781 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8782 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8783 			/*
8784 			 * Fix for bug: 4297749, item # 13
8785 			 * The above test now includes a check to see if PM is
8786 			 * supported by this device before call
8787 			 * pm_lower_power().
8788 			 * Note, the following is not dead code. The call to
8789 			 * pm_lower_power above will generate a call back into
8790 			 * our sdpower routine which might result in a timeout
8791 			 * handler getting activated. Therefore the following
8792 			 * code is valid and necessary.
8793 			 */
8794 			mutex_enter(&un->un_pm_mutex);
8795 			if (un->un_pm_timeid != NULL) {
8796 				timeout_id_t temp_id = un->un_pm_timeid;
8797 				un->un_pm_timeid = NULL;
8798 				mutex_exit(&un->un_pm_mutex);
8799 				(void) untimeout(temp_id);
8800 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8801 			} else {
8802 				mutex_exit(&un->un_pm_mutex);
8803 			}
8804 		}
8805 	}
8806 
8807 	/*
8808 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8809 	 * Relocated here from above to be after the call to
8810 	 * pm_lower_power, which was getting errors.
8811 	 */
8812 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8813 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8814 
8815 	/*
8816 	 * Currently, tagged queuing is supported per target based by HBA.
8817 	 * Setting this per lun instance actually sets the capability of this
8818 	 * target in HBA, which affects those luns already attached on the
8819 	 * same target. So during detach, we can only disable this capability
8820 	 * only when this is the only lun left on this target. By doing
8821 	 * this, we assume a target has the same tagged queuing capability
8822 	 * for every lun. The condition can be removed when HBA is changed to
8823 	 * support per lun based tagged queuing capability.
8824 	 */
8825 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
8826 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8827 	}
8828 
8829 	if (un->un_f_is_fibre == FALSE) {
8830 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8831 	}
8832 
8833 	/*
8834 	 * Remove any event callbacks, fibre only
8835 	 */
8836 	if (un->un_f_is_fibre == TRUE) {
8837 		if ((un->un_insert_event != NULL) &&
8838 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
8839 		    DDI_SUCCESS)) {
8840 			/*
8841 			 * Note: We are returning here after having done
8842 			 * substantial cleanup above. This is consistent
8843 			 * with the legacy implementation but this may not
8844 			 * be the right thing to do.
8845 			 */
8846 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8847 			    "sd_dr_detach: Cannot cancel insert event\n");
8848 			goto err_remove_event;
8849 		}
8850 		un->un_insert_event = NULL;
8851 
8852 		if ((un->un_remove_event != NULL) &&
8853 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
8854 		    DDI_SUCCESS)) {
8855 			/*
8856 			 * Note: We are returning here after having done
8857 			 * substantial cleanup above. This is consistent
8858 			 * with the legacy implementation but this may not
8859 			 * be the right thing to do.
8860 			 */
8861 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8862 			    "sd_dr_detach: Cannot cancel remove event\n");
8863 			goto err_remove_event;
8864 		}
8865 		un->un_remove_event = NULL;
8866 	}
8867 
8868 	/* Do not free the softstate if the callback routine is active */
8869 	sd_sync_with_callback(un);
8870 
8871 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
8872 	cmlb_free_handle(&un->un_cmlbhandle);
8873 
8874 	/*
8875 	 * Hold the detach mutex here, to make sure that no other threads ever
8876 	 * can access a (partially) freed soft state structure.
8877 	 */
8878 	mutex_enter(&sd_detach_mutex);
8879 
8880 	/*
8881 	 * Clean up the soft state struct.
8882 	 * Cleanup is done in reverse order of allocs/inits.
8883 	 * At this point there should be no competing threads anymore.
8884 	 */
8885 
8886 	scsi_fm_fini(devp);
8887 
8888 	/*
8889 	 * Deallocate memory for SCSI FMA.
8890 	 */
8891 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8892 
8893 	/*
8894 	 * Unregister and free device id if it was not registered
8895 	 * by the transport.
8896 	 */
8897 	if (un->un_f_devid_transport_defined == FALSE)
8898 		ddi_devid_unregister(devi);
8899 
8900 	/*
8901 	 * free the devid structure if allocated before (by ddi_devid_init()
8902 	 * or ddi_devid_get()).
8903 	 */
8904 	if (un->un_devid) {
8905 		ddi_devid_free(un->un_devid);
8906 		un->un_devid = NULL;
8907 	}
8908 
8909 	/*
8910 	 * Destroy wmap cache if it exists.
8911 	 */
8912 	if (un->un_wm_cache != NULL) {
8913 		kmem_cache_destroy(un->un_wm_cache);
8914 		un->un_wm_cache = NULL;
8915 	}
8916 
8917 	/*
8918 	 * kstat cleanup is done in detach for all device types (4363169).
8919 	 * We do not want to fail detach if the device kstats are not deleted
8920 	 * since there is a confusion about the devo_refcnt for the device.
8921 	 * We just delete the kstats and let detach complete successfully.
8922 	 */
8923 	if (un->un_stats != NULL) {
8924 		kstat_delete(un->un_stats);
8925 		un->un_stats = NULL;
8926 	}
8927 	if (un->un_errstats != NULL) {
8928 		kstat_delete(un->un_errstats);
8929 		un->un_errstats = NULL;
8930 	}
8931 
8932 	/* Remove partition stats */
8933 	if (un->un_f_pkstats_enabled) {
8934 		for (i = 0; i < NSDMAP; i++) {
8935 			if (un->un_pstats[i] != NULL) {
8936 				kstat_delete(un->un_pstats[i]);
8937 				un->un_pstats[i] = NULL;
8938 			}
8939 		}
8940 	}
8941 
8942 	/* Remove xbuf registration */
8943 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8944 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8945 
8946 	/* Remove driver properties */
8947 	ddi_prop_remove_all(devi);
8948 
8949 	mutex_destroy(&un->un_pm_mutex);
8950 	cv_destroy(&un->un_pm_busy_cv);
8951 
8952 	cv_destroy(&un->un_wcc_cv);
8953 
8954 	/* Open/close semaphore */
8955 	sema_destroy(&un->un_semoclose);
8956 
8957 	/* Removable media condvar. */
8958 	cv_destroy(&un->un_state_cv);
8959 
8960 	/* Suspend/resume condvar. */
8961 	cv_destroy(&un->un_suspend_cv);
8962 	cv_destroy(&un->un_disk_busy_cv);
8963 
8964 	sd_free_rqs(un);
8965 
8966 	/* Free up soft state */
8967 	devp->sd_private = NULL;
8968 
8969 	bzero(un, sizeof (struct sd_lun));
8970 #ifndef XPV_HVM_DRIVER
8971 	ddi_soft_state_free(sd_state, instance);
8972 #endif /* !XPV_HVM_DRIVER */
8973 
8974 	mutex_exit(&sd_detach_mutex);
8975 
8976 	/* This frees up the INQUIRY data associated with the device. */
8977 	scsi_unprobe(devp);
8978 
8979 	/*
8980 	 * After successfully detaching an instance, we update the information
8981 	 * of how many luns have been attached in the relative target and
8982 	 * controller for parallel SCSI. This information is used when sd tries
8983 	 * to set the tagged queuing capability in HBA.
8984 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8985 	 * check if the device is parallel SCSI. However, we don't need to
8986 	 * check here because we've already checked during attach. No device
8987 	 * that is not parallel SCSI is in the chain.
8988 	 */
8989 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8990 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8991 	}
8992 
8993 	return (DDI_SUCCESS);
8994 
8995 err_notclosed:
8996 	mutex_exit(SD_MUTEX(un));
8997 
8998 err_stillbusy:
8999 	_NOTE(NO_COMPETING_THREADS_NOW);
9000 
9001 err_remove_event:
9002 	mutex_enter(&sd_detach_mutex);
9003 	un->un_detach_count--;
9004 	mutex_exit(&sd_detach_mutex);
9005 
9006 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
9007 	return (DDI_FAILURE);
9008 }
9009 
9010 
9011 /*
9012  *    Function: sd_create_errstats
9013  *
9014  * Description: This routine instantiates the device error stats.
9015  *
9016  *		Note: During attach the stats are instantiated first so they are
9017  *		available for attach-time routines that utilize the driver
9018  *		iopath to send commands to the device. The stats are initialized
9019  *		separately so data obtained during some attach-time routines is
9020  *		available. (4362483)
9021  *
9022  *   Arguments: un - driver soft state (unit) structure
9023  *		instance - driver instance
9024  *
9025  *     Context: Kernel thread context
9026  */
9027 
9028 static void
9029 sd_create_errstats(struct sd_lun *un, int instance)
9030 {
9031 	struct	sd_errstats	*stp;
9032 	char	kstatmodule_err[KSTAT_STRLEN];
9033 	char	kstatname[KSTAT_STRLEN];
9034 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
9035 
9036 	ASSERT(un != NULL);
9037 
9038 	if (un->un_errstats != NULL) {
9039 		return;
9040 	}
9041 
9042 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
9043 	    "%serr", sd_label);
9044 	(void) snprintf(kstatname, sizeof (kstatname),
9045 	    "%s%d,err", sd_label, instance);
9046 
9047 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
9048 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
9049 
9050 	if (un->un_errstats == NULL) {
9051 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
9052 		    "sd_create_errstats: Failed kstat_create\n");
9053 		return;
9054 	}
9055 
9056 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9057 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
9058 	    KSTAT_DATA_UINT32);
9059 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
9060 	    KSTAT_DATA_UINT32);
9061 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
9062 	    KSTAT_DATA_UINT32);
9063 	kstat_named_init(&stp->sd_vid,		"Vendor",
9064 	    KSTAT_DATA_CHAR);
9065 	kstat_named_init(&stp->sd_pid,		"Product",
9066 	    KSTAT_DATA_CHAR);
9067 	kstat_named_init(&stp->sd_revision,	"Revision",
9068 	    KSTAT_DATA_CHAR);
9069 	kstat_named_init(&stp->sd_serial,	"Serial No",
9070 	    KSTAT_DATA_CHAR);
9071 	kstat_named_init(&stp->sd_capacity,	"Size",
9072 	    KSTAT_DATA_ULONGLONG);
9073 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
9074 	    KSTAT_DATA_UINT32);
9075 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
9076 	    KSTAT_DATA_UINT32);
9077 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
9078 	    KSTAT_DATA_UINT32);
9079 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
9080 	    KSTAT_DATA_UINT32);
9081 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
9082 	    KSTAT_DATA_UINT32);
9083 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
9084 	    KSTAT_DATA_UINT32);
9085 
9086 	un->un_errstats->ks_private = un;
9087 	un->un_errstats->ks_update  = nulldev;
9088 
9089 	kstat_install(un->un_errstats);
9090 }
9091 
9092 
9093 /*
9094  *    Function: sd_set_errstats
9095  *
9096  * Description: This routine sets the value of the vendor id, product id,
9097  *		revision, serial number, and capacity device error stats.
9098  *
9099  *		Note: During attach the stats are instantiated first so they are
9100  *		available for attach-time routines that utilize the driver
9101  *		iopath to send commands to the device. The stats are initialized
9102  *		separately so data obtained during some attach-time routines is
9103  *		available. (4362483)
9104  *
9105  *   Arguments: un - driver soft state (unit) structure
9106  *
9107  *     Context: Kernel thread context
9108  */
9109 
9110 static void
9111 sd_set_errstats(struct sd_lun *un)
9112 {
9113 	struct	sd_errstats	*stp;
9114 	char 			*sn;
9115 
9116 	ASSERT(un != NULL);
9117 	ASSERT(un->un_errstats != NULL);
9118 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9119 	ASSERT(stp != NULL);
9120 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
9121 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
9122 	(void) strncpy(stp->sd_revision.value.c,
9123 	    un->un_sd->sd_inq->inq_revision, 4);
9124 
9125 	/*
9126 	 * All the errstats are persistent across detach/attach,
9127 	 * so reset all the errstats here in case of the hot
9128 	 * replacement of disk drives, except for not changed
9129 	 * Sun qualified drives.
9130 	 */
9131 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
9132 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9133 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
9134 		stp->sd_softerrs.value.ui32 = 0;
9135 		stp->sd_harderrs.value.ui32 = 0;
9136 		stp->sd_transerrs.value.ui32 = 0;
9137 		stp->sd_rq_media_err.value.ui32 = 0;
9138 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
9139 		stp->sd_rq_nodev_err.value.ui32 = 0;
9140 		stp->sd_rq_recov_err.value.ui32 = 0;
9141 		stp->sd_rq_illrq_err.value.ui32 = 0;
9142 		stp->sd_rq_pfa_err.value.ui32 = 0;
9143 	}
9144 
9145 	/*
9146 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
9147 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
9148 	 * (4376302))
9149 	 */
9150 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
9151 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9152 		    sizeof (SD_INQUIRY(un)->inq_serial));
9153 	} else {
9154 		/*
9155 		 * Set the "Serial No" kstat for non-Sun qualified drives
9156 		 */
9157 		if (ddi_prop_lookup_string(DDI_DEV_T_ANY, SD_DEVINFO(un),
9158 		    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
9159 		    INQUIRY_SERIAL_NO, &sn) == DDI_SUCCESS) {
9160 			(void) strlcpy(stp->sd_serial.value.c, sn,
9161 			    sizeof (stp->sd_serial.value.c));
9162 			ddi_prop_free(sn);
9163 		}
9164 	}
9165 
9166 	if (un->un_f_blockcount_is_valid != TRUE) {
9167 		/*
9168 		 * Set capacity error stat to 0 for no media. This ensures
9169 		 * a valid capacity is displayed in response to 'iostat -E'
9170 		 * when no media is present in the device.
9171 		 */
9172 		stp->sd_capacity.value.ui64 = 0;
9173 	} else {
9174 		/*
9175 		 * Multiply un_blockcount by un->un_sys_blocksize to get
9176 		 * capacity.
9177 		 *
9178 		 * Note: for non-512 blocksize devices "un_blockcount" has been
9179 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
9180 		 * (un_tgt_blocksize / un->un_sys_blocksize).
9181 		 */
9182 		stp->sd_capacity.value.ui64 = (uint64_t)
9183 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
9184 	}
9185 }
9186 
9187 
9188 /*
9189  *    Function: sd_set_pstats
9190  *
9191  * Description: This routine instantiates and initializes the partition
9192  *              stats for each partition with more than zero blocks.
9193  *		(4363169)
9194  *
9195  *   Arguments: un - driver soft state (unit) structure
9196  *
9197  *     Context: Kernel thread context
9198  */
9199 
9200 static void
9201 sd_set_pstats(struct sd_lun *un)
9202 {
9203 	char	kstatname[KSTAT_STRLEN];
9204 	int	instance;
9205 	int	i;
9206 	diskaddr_t	nblks = 0;
9207 	char	*partname = NULL;
9208 
9209 	ASSERT(un != NULL);
9210 
9211 	instance = ddi_get_instance(SD_DEVINFO(un));
9212 
9213 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
9214 	for (i = 0; i < NSDMAP; i++) {
9215 
9216 		if (cmlb_partinfo(un->un_cmlbhandle, i,
9217 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
9218 			continue;
9219 		mutex_enter(SD_MUTEX(un));
9220 
9221 		if ((un->un_pstats[i] == NULL) &&
9222 		    (nblks != 0)) {
9223 
9224 			(void) snprintf(kstatname, sizeof (kstatname),
9225 			    "%s%d,%s", sd_label, instance,
9226 			    partname);
9227 
9228 			un->un_pstats[i] = kstat_create(sd_label,
9229 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
9230 			    1, KSTAT_FLAG_PERSISTENT);
9231 			if (un->un_pstats[i] != NULL) {
9232 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
9233 				kstat_install(un->un_pstats[i]);
9234 			}
9235 		}
9236 		mutex_exit(SD_MUTEX(un));
9237 	}
9238 }
9239 
9240 
9241 #if (defined(__fibre))
9242 /*
9243  *    Function: sd_init_event_callbacks
9244  *
9245  * Description: This routine initializes the insertion and removal event
9246  *		callbacks. (fibre only)
9247  *
9248  *   Arguments: un - driver soft state (unit) structure
9249  *
9250  *     Context: Kernel thread context
9251  */
9252 
9253 static void
9254 sd_init_event_callbacks(struct sd_lun *un)
9255 {
9256 	ASSERT(un != NULL);
9257 
9258 	if ((un->un_insert_event == NULL) &&
9259 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
9260 	    &un->un_insert_event) == DDI_SUCCESS)) {
9261 		/*
9262 		 * Add the callback for an insertion event
9263 		 */
9264 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9265 		    un->un_insert_event, sd_event_callback, (void *)un,
9266 		    &(un->un_insert_cb_id));
9267 	}
9268 
9269 	if ((un->un_remove_event == NULL) &&
9270 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
9271 	    &un->un_remove_event) == DDI_SUCCESS)) {
9272 		/*
9273 		 * Add the callback for a removal event
9274 		 */
9275 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9276 		    un->un_remove_event, sd_event_callback, (void *)un,
9277 		    &(un->un_remove_cb_id));
9278 	}
9279 }
9280 
9281 
9282 /*
9283  *    Function: sd_event_callback
9284  *
9285  * Description: This routine handles insert/remove events (photon). The
9286  *		state is changed to OFFLINE which can be used to supress
9287  *		error msgs. (fibre only)
9288  *
9289  *   Arguments: un - driver soft state (unit) structure
9290  *
9291  *     Context: Callout thread context
9292  */
9293 /* ARGSUSED */
9294 static void
9295 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
9296     void *bus_impldata)
9297 {
9298 	struct sd_lun *un = (struct sd_lun *)arg;
9299 
9300 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
9301 	if (event == un->un_insert_event) {
9302 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
9303 		mutex_enter(SD_MUTEX(un));
9304 		if (un->un_state == SD_STATE_OFFLINE) {
9305 			if (un->un_last_state != SD_STATE_SUSPENDED) {
9306 				un->un_state = un->un_last_state;
9307 			} else {
9308 				/*
9309 				 * We have gone through SUSPEND/RESUME while
9310 				 * we were offline. Restore the last state
9311 				 */
9312 				un->un_state = un->un_save_state;
9313 			}
9314 		}
9315 		mutex_exit(SD_MUTEX(un));
9316 
9317 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
9318 	} else if (event == un->un_remove_event) {
9319 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
9320 		mutex_enter(SD_MUTEX(un));
9321 		/*
9322 		 * We need to handle an event callback that occurs during
9323 		 * the suspend operation, since we don't prevent it.
9324 		 */
9325 		if (un->un_state != SD_STATE_OFFLINE) {
9326 			if (un->un_state != SD_STATE_SUSPENDED) {
9327 				New_state(un, SD_STATE_OFFLINE);
9328 			} else {
9329 				un->un_last_state = SD_STATE_OFFLINE;
9330 			}
9331 		}
9332 		mutex_exit(SD_MUTEX(un));
9333 	} else {
9334 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
9335 		    "!Unknown event\n");
9336 	}
9337 
9338 }
9339 #endif
9340 
9341 /*
9342  *    Function: sd_cache_control()
9343  *
9344  * Description: This routine is the driver entry point for setting
9345  *		read and write caching by modifying the WCE (write cache
9346  *		enable) and RCD (read cache disable) bits of mode
9347  *		page 8 (MODEPAGE_CACHING).
9348  *
9349  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
9350  *                      structure for this target.
9351  *		rcd_flag - flag for controlling the read cache
9352  *		wce_flag - flag for controlling the write cache
9353  *
9354  * Return Code: EIO
9355  *		code returned by sd_send_scsi_MODE_SENSE and
9356  *		sd_send_scsi_MODE_SELECT
9357  *
9358  *     Context: Kernel Thread
9359  */
9360 
9361 static int
9362 sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag)
9363 {
9364 	struct mode_caching	*mode_caching_page;
9365 	uchar_t			*header;
9366 	size_t			buflen;
9367 	int			hdrlen;
9368 	int			bd_len;
9369 	int			rval = 0;
9370 	struct mode_header_grp2	*mhp;
9371 	struct sd_lun		*un;
9372 	int			status;
9373 
9374 	ASSERT(ssc != NULL);
9375 	un = ssc->ssc_un;
9376 	ASSERT(un != NULL);
9377 
9378 	/*
9379 	 * Do a test unit ready, otherwise a mode sense may not work if this
9380 	 * is the first command sent to the device after boot.
9381 	 */
9382 	status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
9383 	if (status != 0)
9384 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9385 
9386 	if (un->un_f_cfg_is_atapi == TRUE) {
9387 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9388 	} else {
9389 		hdrlen = MODE_HEADER_LENGTH;
9390 	}
9391 
9392 	/*
9393 	 * Allocate memory for the retrieved mode page and its headers.  Set
9394 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
9395 	 * we get all of the mode sense data otherwise, the mode select
9396 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
9397 	 */
9398 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
9399 	    sizeof (struct mode_cache_scsi3);
9400 
9401 	header = kmem_zalloc(buflen, KM_SLEEP);
9402 
9403 	/* Get the information from the device. */
9404 	if (un->un_f_cfg_is_atapi == TRUE) {
9405 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, header, buflen,
9406 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9407 	} else {
9408 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
9409 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9410 	}
9411 
9412 	if (rval != 0) {
9413 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9414 		    "sd_cache_control: Mode Sense Failed\n");
9415 		goto mode_sense_failed;
9416 	}
9417 
9418 	/*
9419 	 * Determine size of Block Descriptors in order to locate
9420 	 * the mode page data. ATAPI devices return 0, SCSI devices
9421 	 * should return MODE_BLK_DESC_LENGTH.
9422 	 */
9423 	if (un->un_f_cfg_is_atapi == TRUE) {
9424 		mhp	= (struct mode_header_grp2 *)header;
9425 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9426 	} else {
9427 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9428 	}
9429 
9430 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9431 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9432 		    "sd_cache_control: Mode Sense returned invalid block "
9433 		    "descriptor length\n");
9434 		rval = EIO;
9435 		goto mode_sense_failed;
9436 	}
9437 
9438 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9439 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9440 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9441 		    "sd_cache_control: Mode Sense caching page code mismatch "
9442 		    "%d\n", mode_caching_page->mode_page.code);
9443 		rval = EIO;
9444 		goto mode_sense_failed;
9445 	}
9446 
9447 	/* Check the relevant bits on successful mode sense. */
9448 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
9449 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
9450 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
9451 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
9452 
9453 		size_t sbuflen;
9454 		uchar_t save_pg;
9455 
9456 		/*
9457 		 * Construct select buffer length based on the
9458 		 * length of the sense data returned.
9459 		 */
9460 		sbuflen =  hdrlen + bd_len +
9461 		    sizeof (struct mode_page) +
9462 		    (int)mode_caching_page->mode_page.length;
9463 
9464 		/*
9465 		 * Set the caching bits as requested.
9466 		 */
9467 		if (rcd_flag == SD_CACHE_ENABLE)
9468 			mode_caching_page->rcd = 0;
9469 		else if (rcd_flag == SD_CACHE_DISABLE)
9470 			mode_caching_page->rcd = 1;
9471 
9472 		if (wce_flag == SD_CACHE_ENABLE)
9473 			mode_caching_page->wce = 1;
9474 		else if (wce_flag == SD_CACHE_DISABLE)
9475 			mode_caching_page->wce = 0;
9476 
9477 		/*
9478 		 * Save the page if the mode sense says the
9479 		 * drive supports it.
9480 		 */
9481 		save_pg = mode_caching_page->mode_page.ps ?
9482 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
9483 
9484 		/* Clear reserved bits before mode select. */
9485 		mode_caching_page->mode_page.ps = 0;
9486 
9487 		/*
9488 		 * Clear out mode header for mode select.
9489 		 * The rest of the retrieved page will be reused.
9490 		 */
9491 		bzero(header, hdrlen);
9492 
9493 		if (un->un_f_cfg_is_atapi == TRUE) {
9494 			mhp = (struct mode_header_grp2 *)header;
9495 			mhp->bdesc_length_hi = bd_len >> 8;
9496 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
9497 		} else {
9498 			((struct mode_header *)header)->bdesc_length = bd_len;
9499 		}
9500 
9501 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9502 
9503 		/* Issue mode select to change the cache settings */
9504 		if (un->un_f_cfg_is_atapi == TRUE) {
9505 			rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, header,
9506 			    sbuflen, save_pg, SD_PATH_DIRECT);
9507 		} else {
9508 			rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
9509 			    sbuflen, save_pg, SD_PATH_DIRECT);
9510 		}
9511 
9512 	}
9513 
9514 
9515 mode_sense_failed:
9516 
9517 	kmem_free(header, buflen);
9518 
9519 	if (rval != 0) {
9520 		if (rval == EIO)
9521 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9522 		else
9523 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9524 	}
9525 	return (rval);
9526 }
9527 
9528 
9529 /*
9530  *    Function: sd_get_write_cache_enabled()
9531  *
9532  * Description: This routine is the driver entry point for determining if
9533  *		write caching is enabled.  It examines the WCE (write cache
9534  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
9535  *
9536  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
9537  *                      structure for this target.
9538  *		is_enabled - pointer to int where write cache enabled state
9539  *		is returned (non-zero -> write cache enabled)
9540  *
9541  *
9542  * Return Code: EIO
9543  *		code returned by sd_send_scsi_MODE_SENSE
9544  *
9545  *     Context: Kernel Thread
9546  *
9547  * NOTE: If ioctl is added to disable write cache, this sequence should
9548  * be followed so that no locking is required for accesses to
9549  * un->un_f_write_cache_enabled:
9550  * 	do mode select to clear wce
9551  * 	do synchronize cache to flush cache
9552  * 	set un->un_f_write_cache_enabled = FALSE
9553  *
9554  * Conversely, an ioctl to enable the write cache should be done
9555  * in this order:
9556  * 	set un->un_f_write_cache_enabled = TRUE
9557  * 	do mode select to set wce
9558  */
9559 
9560 static int
9561 sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled)
9562 {
9563 	struct mode_caching	*mode_caching_page;
9564 	uchar_t			*header;
9565 	size_t			buflen;
9566 	int			hdrlen;
9567 	int			bd_len;
9568 	int			rval = 0;
9569 	struct sd_lun		*un;
9570 	int			status;
9571 
9572 	ASSERT(ssc != NULL);
9573 	un = ssc->ssc_un;
9574 	ASSERT(un != NULL);
9575 	ASSERT(is_enabled != NULL);
9576 
9577 	/* in case of error, flag as enabled */
9578 	*is_enabled = TRUE;
9579 
9580 	/*
9581 	 * Do a test unit ready, otherwise a mode sense may not work if this
9582 	 * is the first command sent to the device after boot.
9583 	 */
9584 	status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
9585 
9586 	if (status != 0)
9587 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9588 
9589 	if (un->un_f_cfg_is_atapi == TRUE) {
9590 		hdrlen = MODE_HEADER_LENGTH_GRP2;
9591 	} else {
9592 		hdrlen = MODE_HEADER_LENGTH;
9593 	}
9594 
9595 	/*
9596 	 * Allocate memory for the retrieved mode page and its headers.  Set
9597 	 * a pointer to the page itself.
9598 	 */
9599 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
9600 	header = kmem_zalloc(buflen, KM_SLEEP);
9601 
9602 	/* Get the information from the device. */
9603 	if (un->un_f_cfg_is_atapi == TRUE) {
9604 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, header, buflen,
9605 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9606 	} else {
9607 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
9608 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
9609 	}
9610 
9611 	if (rval != 0) {
9612 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
9613 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
9614 		goto mode_sense_failed;
9615 	}
9616 
9617 	/*
9618 	 * Determine size of Block Descriptors in order to locate
9619 	 * the mode page data. ATAPI devices return 0, SCSI devices
9620 	 * should return MODE_BLK_DESC_LENGTH.
9621 	 */
9622 	if (un->un_f_cfg_is_atapi == TRUE) {
9623 		struct mode_header_grp2	*mhp;
9624 		mhp	= (struct mode_header_grp2 *)header;
9625 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9626 	} else {
9627 		bd_len  = ((struct mode_header *)header)->bdesc_length;
9628 	}
9629 
9630 	if (bd_len > MODE_BLK_DESC_LENGTH) {
9631 		/* FMA should make upset complain here */
9632 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9633 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
9634 		    "block descriptor length\n");
9635 		rval = EIO;
9636 		goto mode_sense_failed;
9637 	}
9638 
9639 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
9640 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9641 		/* FMA could make upset complain here */
9642 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9643 		    "sd_get_write_cache_enabled: Mode Sense caching page "
9644 		    "code mismatch %d\n", mode_caching_page->mode_page.code);
9645 		rval = EIO;
9646 		goto mode_sense_failed;
9647 	}
9648 	*is_enabled = mode_caching_page->wce;
9649 
9650 mode_sense_failed:
9651 	if (rval == 0) {
9652 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9653 	} else if (rval == EIO) {
9654 		/*
9655 		 * Some disks do not support mode sense(6), we
9656 		 * should ignore this kind of error(sense key is
9657 		 * 0x5 - illegal request).
9658 		 */
9659 		uint8_t *sensep;
9660 		int senlen;
9661 
9662 		sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
9663 		senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
9664 		    ssc->ssc_uscsi_cmd->uscsi_rqresid);
9665 
9666 		if (senlen > 0 &&
9667 		    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
9668 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
9669 		} else {
9670 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9671 		}
9672 	} else {
9673 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9674 	}
9675 	kmem_free(header, buflen);
9676 	return (rval);
9677 }
9678 
9679 /*
9680  *    Function: sd_get_nv_sup()
9681  *
9682  * Description: This routine is the driver entry point for
9683  * determining whether non-volatile cache is supported. This
9684  * determination process works as follows:
9685  *
9686  * 1. sd first queries sd.conf on whether
9687  * suppress_cache_flush bit is set for this device.
9688  *
9689  * 2. if not there, then queries the internal disk table.
9690  *
9691  * 3. if either sd.conf or internal disk table specifies
9692  * cache flush be suppressed, we don't bother checking
9693  * NV_SUP bit.
9694  *
9695  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
9696  * the optional INQUIRY VPD page 0x86. If the device
9697  * supports VPD page 0x86, sd examines the NV_SUP
9698  * (non-volatile cache support) bit in the INQUIRY VPD page
9699  * 0x86:
9700  *   o If NV_SUP bit is set, sd assumes the device has a
9701  *   non-volatile cache and set the
9702  *   un_f_sync_nv_supported to TRUE.
9703  *   o Otherwise cache is not non-volatile,
9704  *   un_f_sync_nv_supported is set to FALSE.
9705  *
9706  * Arguments: un - driver soft state (unit) structure
9707  *
9708  * Return Code:
9709  *
9710  *     Context: Kernel Thread
9711  */
9712 
9713 static void
9714 sd_get_nv_sup(sd_ssc_t *ssc)
9715 {
9716 	int		rval		= 0;
9717 	uchar_t		*inq86		= NULL;
9718 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
9719 	size_t		inq86_resid	= 0;
9720 	struct		dk_callback *dkc;
9721 	struct sd_lun	*un;
9722 
9723 	ASSERT(ssc != NULL);
9724 	un = ssc->ssc_un;
9725 	ASSERT(un != NULL);
9726 
9727 	mutex_enter(SD_MUTEX(un));
9728 
9729 	/*
9730 	 * Be conservative on the device's support of
9731 	 * SYNC_NV bit: un_f_sync_nv_supported is
9732 	 * initialized to be false.
9733 	 */
9734 	un->un_f_sync_nv_supported = FALSE;
9735 
9736 	/*
9737 	 * If either sd.conf or internal disk table
9738 	 * specifies cache flush be suppressed, then
9739 	 * we don't bother checking NV_SUP bit.
9740 	 */
9741 	if (un->un_f_suppress_cache_flush == TRUE) {
9742 		mutex_exit(SD_MUTEX(un));
9743 		return;
9744 	}
9745 
9746 	if (sd_check_vpd_page_support(ssc) == 0 &&
9747 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
9748 		mutex_exit(SD_MUTEX(un));
9749 		/* collect page 86 data if available */
9750 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
9751 
9752 		rval = sd_send_scsi_INQUIRY(ssc, inq86, inq86_len,
9753 		    0x01, 0x86, &inq86_resid);
9754 
9755 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
9756 			SD_TRACE(SD_LOG_COMMON, un,
9757 			    "sd_get_nv_sup: \
9758 			    successfully get VPD page: %x \
9759 			    PAGE LENGTH: %x BYTE 6: %x\n",
9760 			    inq86[1], inq86[3], inq86[6]);
9761 
9762 			mutex_enter(SD_MUTEX(un));
9763 			/*
9764 			 * check the value of NV_SUP bit: only if the device
9765 			 * reports NV_SUP bit to be 1, the
9766 			 * un_f_sync_nv_supported bit will be set to true.
9767 			 */
9768 			if (inq86[6] & SD_VPD_NV_SUP) {
9769 				un->un_f_sync_nv_supported = TRUE;
9770 			}
9771 			mutex_exit(SD_MUTEX(un));
9772 		} else if (rval != 0) {
9773 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9774 		}
9775 
9776 		kmem_free(inq86, inq86_len);
9777 	} else {
9778 		mutex_exit(SD_MUTEX(un));
9779 	}
9780 
9781 	/*
9782 	 * Send a SYNC CACHE command to check whether
9783 	 * SYNC_NV bit is supported. This command should have
9784 	 * un_f_sync_nv_supported set to correct value.
9785 	 */
9786 	mutex_enter(SD_MUTEX(un));
9787 	if (un->un_f_sync_nv_supported) {
9788 		mutex_exit(SD_MUTEX(un));
9789 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
9790 		dkc->dkc_flag = FLUSH_VOLATILE;
9791 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
9792 
9793 		/*
9794 		 * Send a TEST UNIT READY command to the device. This should
9795 		 * clear any outstanding UNIT ATTENTION that may be present.
9796 		 */
9797 		rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
9798 		if (rval != 0)
9799 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9800 
9801 		kmem_free(dkc, sizeof (struct dk_callback));
9802 	} else {
9803 		mutex_exit(SD_MUTEX(un));
9804 	}
9805 
9806 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
9807 	    un_f_suppress_cache_flush is set to %d\n",
9808 	    un->un_f_suppress_cache_flush);
9809 }
9810 
9811 /*
9812  *    Function: sd_make_device
9813  *
9814  * Description: Utility routine to return the Solaris device number from
9815  *		the data in the device's dev_info structure.
9816  *
9817  * Return Code: The Solaris device number
9818  *
9819  *     Context: Any
9820  */
9821 
9822 static dev_t
9823 sd_make_device(dev_info_t *devi)
9824 {
9825 	return (makedevice(ddi_driver_major(devi),
9826 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9827 }
9828 
9829 
9830 /*
9831  *    Function: sd_pm_entry
9832  *
9833  * Description: Called at the start of a new command to manage power
9834  *		and busy status of a device. This includes determining whether
9835  *		the current power state of the device is sufficient for
9836  *		performing the command or whether it must be changed.
9837  *		The PM framework is notified appropriately.
9838  *		Only with a return status of DDI_SUCCESS will the
9839  *		component be busy to the framework.
9840  *
9841  *		All callers of sd_pm_entry must check the return status
9842  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9843  *		of DDI_FAILURE indicates the device failed to power up.
9844  *		In this case un_pm_count has been adjusted so the result
9845  *		on exit is still powered down, ie. count is less than 0.
9846  *		Calling sd_pm_exit with this count value hits an ASSERT.
9847  *
9848  * Return Code: DDI_SUCCESS or DDI_FAILURE
9849  *
9850  *     Context: Kernel thread context.
9851  */
9852 
9853 static int
9854 sd_pm_entry(struct sd_lun *un)
9855 {
9856 	int return_status = DDI_SUCCESS;
9857 
9858 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9859 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9860 
9861 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9862 
9863 	if (un->un_f_pm_is_enabled == FALSE) {
9864 		SD_TRACE(SD_LOG_IO_PM, un,
9865 		    "sd_pm_entry: exiting, PM not enabled\n");
9866 		return (return_status);
9867 	}
9868 
9869 	/*
9870 	 * Just increment a counter if PM is enabled. On the transition from
9871 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9872 	 * the count with each IO and mark the device as idle when the count
9873 	 * hits 0.
9874 	 *
9875 	 * If the count is less than 0 the device is powered down. If a powered
9876 	 * down device is successfully powered up then the count must be
9877 	 * incremented to reflect the power up. Note that it'll get incremented
9878 	 * a second time to become busy.
9879 	 *
9880 	 * Because the following has the potential to change the device state
9881 	 * and must release the un_pm_mutex to do so, only one thread can be
9882 	 * allowed through at a time.
9883 	 */
9884 
9885 	mutex_enter(&un->un_pm_mutex);
9886 	while (un->un_pm_busy == TRUE) {
9887 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9888 	}
9889 	un->un_pm_busy = TRUE;
9890 
9891 	if (un->un_pm_count < 1) {
9892 
9893 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9894 
9895 		/*
9896 		 * Indicate we are now busy so the framework won't attempt to
9897 		 * power down the device. This call will only fail if either
9898 		 * we passed a bad component number or the device has no
9899 		 * components. Neither of these should ever happen.
9900 		 */
9901 		mutex_exit(&un->un_pm_mutex);
9902 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9903 		ASSERT(return_status == DDI_SUCCESS);
9904 
9905 		mutex_enter(&un->un_pm_mutex);
9906 
9907 		if (un->un_pm_count < 0) {
9908 			mutex_exit(&un->un_pm_mutex);
9909 
9910 			SD_TRACE(SD_LOG_IO_PM, un,
9911 			    "sd_pm_entry: power up component\n");
9912 
9913 			/*
9914 			 * pm_raise_power will cause sdpower to be called
9915 			 * which brings the device power level to the
9916 			 * desired state, If successful, un_pm_count and
9917 			 * un_power_level will be updated appropriately.
9918 			 */
9919 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9920 			    SD_PM_STATE_ACTIVE(un));
9921 
9922 			mutex_enter(&un->un_pm_mutex);
9923 
9924 			if (return_status != DDI_SUCCESS) {
9925 				/*
9926 				 * Power up failed.
9927 				 * Idle the device and adjust the count
9928 				 * so the result on exit is that we're
9929 				 * still powered down, ie. count is less than 0.
9930 				 */
9931 				SD_TRACE(SD_LOG_IO_PM, un,
9932 				    "sd_pm_entry: power up failed,"
9933 				    " idle the component\n");
9934 
9935 				(void) pm_idle_component(SD_DEVINFO(un), 0);
9936 				un->un_pm_count--;
9937 			} else {
9938 				/*
9939 				 * Device is powered up, verify the
9940 				 * count is non-negative.
9941 				 * This is debug only.
9942 				 */
9943 				ASSERT(un->un_pm_count == 0);
9944 			}
9945 		}
9946 
9947 		if (return_status == DDI_SUCCESS) {
9948 			/*
9949 			 * For performance, now that the device has been tagged
9950 			 * as busy, and it's known to be powered up, update the
9951 			 * chain types to use jump tables that do not include
9952 			 * pm. This significantly lowers the overhead and
9953 			 * therefore improves performance.
9954 			 */
9955 
9956 			mutex_exit(&un->un_pm_mutex);
9957 			mutex_enter(SD_MUTEX(un));
9958 			SD_TRACE(SD_LOG_IO_PM, un,
9959 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
9960 			    un->un_uscsi_chain_type);
9961 
9962 			if (un->un_f_non_devbsize_supported) {
9963 				un->un_buf_chain_type =
9964 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
9965 			} else {
9966 				un->un_buf_chain_type =
9967 				    SD_CHAIN_INFO_DISK_NO_PM;
9968 			}
9969 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
9970 
9971 			SD_TRACE(SD_LOG_IO_PM, un,
9972 			    "             changed  uscsi_chain_type to   %d\n",
9973 			    un->un_uscsi_chain_type);
9974 			mutex_exit(SD_MUTEX(un));
9975 			mutex_enter(&un->un_pm_mutex);
9976 
9977 			if (un->un_pm_idle_timeid == NULL) {
9978 				/* 300 ms. */
9979 				un->un_pm_idle_timeid =
9980 				    timeout(sd_pm_idletimeout_handler, un,
9981 				    (drv_usectohz((clock_t)300000)));
9982 				/*
9983 				 * Include an extra call to busy which keeps the
9984 				 * device busy with-respect-to the PM layer
9985 				 * until the timer fires, at which time it'll
9986 				 * get the extra idle call.
9987 				 */
9988 				(void) pm_busy_component(SD_DEVINFO(un), 0);
9989 			}
9990 		}
9991 	}
9992 	un->un_pm_busy = FALSE;
9993 	/* Next... */
9994 	cv_signal(&un->un_pm_busy_cv);
9995 
9996 	un->un_pm_count++;
9997 
9998 	SD_TRACE(SD_LOG_IO_PM, un,
9999 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
10000 
10001 	mutex_exit(&un->un_pm_mutex);
10002 
10003 	return (return_status);
10004 }
10005 
10006 
10007 /*
10008  *    Function: sd_pm_exit
10009  *
10010  * Description: Called at the completion of a command to manage busy
10011  *		status for the device. If the device becomes idle the
10012  *		PM framework is notified.
10013  *
10014  *     Context: Kernel thread context
10015  */
10016 
10017 static void
10018 sd_pm_exit(struct sd_lun *un)
10019 {
10020 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10021 	ASSERT(!mutex_owned(&un->un_pm_mutex));
10022 
10023 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
10024 
10025 	/*
10026 	 * After attach the following flag is only read, so don't
10027 	 * take the penalty of acquiring a mutex for it.
10028 	 */
10029 	if (un->un_f_pm_is_enabled == TRUE) {
10030 
10031 		mutex_enter(&un->un_pm_mutex);
10032 		un->un_pm_count--;
10033 
10034 		SD_TRACE(SD_LOG_IO_PM, un,
10035 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
10036 
10037 		ASSERT(un->un_pm_count >= 0);
10038 		if (un->un_pm_count == 0) {
10039 			mutex_exit(&un->un_pm_mutex);
10040 
10041 			SD_TRACE(SD_LOG_IO_PM, un,
10042 			    "sd_pm_exit: idle component\n");
10043 
10044 			(void) pm_idle_component(SD_DEVINFO(un), 0);
10045 
10046 		} else {
10047 			mutex_exit(&un->un_pm_mutex);
10048 		}
10049 	}
10050 
10051 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
10052 }
10053 
10054 
10055 /*
10056  *    Function: sdopen
10057  *
10058  * Description: Driver's open(9e) entry point function.
10059  *
10060  *   Arguments: dev_i   - pointer to device number
10061  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
10062  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10063  *		cred_p  - user credential pointer
10064  *
10065  * Return Code: EINVAL
10066  *		ENXIO
10067  *		EIO
10068  *		EROFS
10069  *		EBUSY
10070  *
10071  *     Context: Kernel thread context
10072  */
10073 /* ARGSUSED */
10074 static int
10075 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
10076 {
10077 	struct sd_lun	*un;
10078 	int		nodelay;
10079 	int		part;
10080 	uint64_t	partmask;
10081 	int		instance;
10082 	dev_t		dev;
10083 	int		rval = EIO;
10084 	diskaddr_t	nblks = 0;
10085 	diskaddr_t	label_cap;
10086 
10087 	/* Validate the open type */
10088 	if (otyp >= OTYPCNT) {
10089 		return (EINVAL);
10090 	}
10091 
10092 	dev = *dev_p;
10093 	instance = SDUNIT(dev);
10094 	mutex_enter(&sd_detach_mutex);
10095 
10096 	/*
10097 	 * Fail the open if there is no softstate for the instance, or
10098 	 * if another thread somewhere is trying to detach the instance.
10099 	 */
10100 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
10101 	    (un->un_detach_count != 0)) {
10102 		mutex_exit(&sd_detach_mutex);
10103 		/*
10104 		 * The probe cache only needs to be cleared when open (9e) fails
10105 		 * with ENXIO (4238046).
10106 		 */
10107 		/*
10108 		 * un-conditionally clearing probe cache is ok with
10109 		 * separate sd/ssd binaries
10110 		 * x86 platform can be an issue with both parallel
10111 		 * and fibre in 1 binary
10112 		 */
10113 		sd_scsi_clear_probe_cache();
10114 		return (ENXIO);
10115 	}
10116 
10117 	/*
10118 	 * The un_layer_count is to prevent another thread in specfs from
10119 	 * trying to detach the instance, which can happen when we are
10120 	 * called from a higher-layer driver instead of thru specfs.
10121 	 * This will not be needed when DDI provides a layered driver
10122 	 * interface that allows specfs to know that an instance is in
10123 	 * use by a layered driver & should not be detached.
10124 	 *
10125 	 * Note: the semantics for layered driver opens are exactly one
10126 	 * close for every open.
10127 	 */
10128 	if (otyp == OTYP_LYR) {
10129 		un->un_layer_count++;
10130 	}
10131 
10132 	/*
10133 	 * Keep a count of the current # of opens in progress. This is because
10134 	 * some layered drivers try to call us as a regular open. This can
10135 	 * cause problems that we cannot prevent, however by keeping this count
10136 	 * we can at least keep our open and detach routines from racing against
10137 	 * each other under such conditions.
10138 	 */
10139 	un->un_opens_in_progress++;
10140 	mutex_exit(&sd_detach_mutex);
10141 
10142 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
10143 	part	 = SDPART(dev);
10144 	partmask = 1 << part;
10145 
10146 	/*
10147 	 * We use a semaphore here in order to serialize
10148 	 * open and close requests on the device.
10149 	 */
10150 	sema_p(&un->un_semoclose);
10151 
10152 	mutex_enter(SD_MUTEX(un));
10153 
10154 	/*
10155 	 * All device accesses go thru sdstrategy() where we check
10156 	 * on suspend status but there could be a scsi_poll command,
10157 	 * which bypasses sdstrategy(), so we need to check pm
10158 	 * status.
10159 	 */
10160 
10161 	if (!nodelay) {
10162 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10163 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10164 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10165 		}
10166 
10167 		mutex_exit(SD_MUTEX(un));
10168 		if (sd_pm_entry(un) != DDI_SUCCESS) {
10169 			rval = EIO;
10170 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
10171 			    "sdopen: sd_pm_entry failed\n");
10172 			goto open_failed_with_pm;
10173 		}
10174 		mutex_enter(SD_MUTEX(un));
10175 	}
10176 
10177 	/* check for previous exclusive open */
10178 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
10179 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10180 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
10181 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
10182 
10183 	if (un->un_exclopen & (partmask)) {
10184 		goto excl_open_fail;
10185 	}
10186 
10187 	if (flag & FEXCL) {
10188 		int i;
10189 		if (un->un_ocmap.lyropen[part]) {
10190 			goto excl_open_fail;
10191 		}
10192 		for (i = 0; i < (OTYPCNT - 1); i++) {
10193 			if (un->un_ocmap.regopen[i] & (partmask)) {
10194 				goto excl_open_fail;
10195 			}
10196 		}
10197 	}
10198 
10199 	/*
10200 	 * Check the write permission if this is a removable media device,
10201 	 * NDELAY has not been set, and writable permission is requested.
10202 	 *
10203 	 * Note: If NDELAY was set and this is write-protected media the WRITE
10204 	 * attempt will fail with EIO as part of the I/O processing. This is a
10205 	 * more permissive implementation that allows the open to succeed and
10206 	 * WRITE attempts to fail when appropriate.
10207 	 */
10208 	if (un->un_f_chk_wp_open) {
10209 		if ((flag & FWRITE) && (!nodelay)) {
10210 			mutex_exit(SD_MUTEX(un));
10211 			/*
10212 			 * Defer the check for write permission on writable
10213 			 * DVD drive till sdstrategy and will not fail open even
10214 			 * if FWRITE is set as the device can be writable
10215 			 * depending upon the media and the media can change
10216 			 * after the call to open().
10217 			 */
10218 			if (un->un_f_dvdram_writable_device == FALSE) {
10219 				if (ISCD(un) || sr_check_wp(dev)) {
10220 				rval = EROFS;
10221 				mutex_enter(SD_MUTEX(un));
10222 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10223 				    "write to cd or write protected media\n");
10224 				goto open_fail;
10225 				}
10226 			}
10227 			mutex_enter(SD_MUTEX(un));
10228 		}
10229 	}
10230 
10231 	/*
10232 	 * If opening in NDELAY/NONBLOCK mode, just return.
10233 	 * Check if disk is ready and has a valid geometry later.
10234 	 */
10235 	if (!nodelay) {
10236 		sd_ssc_t	*ssc;
10237 
10238 		mutex_exit(SD_MUTEX(un));
10239 		ssc = sd_ssc_init(un);
10240 		rval = sd_ready_and_valid(ssc, part);
10241 		sd_ssc_fini(ssc);
10242 		mutex_enter(SD_MUTEX(un));
10243 		/*
10244 		 * Fail if device is not ready or if the number of disk
10245 		 * blocks is zero or negative for non CD devices.
10246 		 */
10247 
10248 		nblks = 0;
10249 
10250 		if (rval == SD_READY_VALID && (!ISCD(un))) {
10251 			/* if cmlb_partinfo fails, nblks remains 0 */
10252 			mutex_exit(SD_MUTEX(un));
10253 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
10254 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
10255 			mutex_enter(SD_MUTEX(un));
10256 		}
10257 
10258 		if ((rval != SD_READY_VALID) ||
10259 		    (!ISCD(un) && nblks <= 0)) {
10260 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
10261 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10262 			    "device not ready or invalid disk block value\n");
10263 			goto open_fail;
10264 		}
10265 #if defined(__i386) || defined(__amd64)
10266 	} else {
10267 		uchar_t *cp;
10268 		/*
10269 		 * x86 requires special nodelay handling, so that p0 is
10270 		 * always defined and accessible.
10271 		 * Invalidate geometry only if device is not already open.
10272 		 */
10273 		cp = &un->un_ocmap.chkd[0];
10274 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10275 			if (*cp != (uchar_t)0) {
10276 				break;
10277 			}
10278 			cp++;
10279 		}
10280 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10281 			mutex_exit(SD_MUTEX(un));
10282 			cmlb_invalidate(un->un_cmlbhandle,
10283 			    (void *)SD_PATH_DIRECT);
10284 			mutex_enter(SD_MUTEX(un));
10285 		}
10286 
10287 #endif
10288 	}
10289 
10290 	if (otyp == OTYP_LYR) {
10291 		un->un_ocmap.lyropen[part]++;
10292 	} else {
10293 		un->un_ocmap.regopen[otyp] |= partmask;
10294 	}
10295 
10296 	/* Set up open and exclusive open flags */
10297 	if (flag & FEXCL) {
10298 		un->un_exclopen |= (partmask);
10299 	}
10300 
10301 	/*
10302 	 * If the lun is EFI labeled and lun capacity is greater than the
10303 	 * capacity contained in the label, log a sys-event to notify the
10304 	 * interested module.
10305 	 * To avoid an infinite loop of logging sys-event, we only log the
10306 	 * event when the lun is not opened in NDELAY mode. The event handler
10307 	 * should open the lun in NDELAY mode.
10308 	 */
10309 	if (!nodelay) {
10310 		mutex_exit(SD_MUTEX(un));
10311 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
10312 		    (void*)SD_PATH_DIRECT) == 0) {
10313 			mutex_enter(SD_MUTEX(un));
10314 			if (un->un_f_blockcount_is_valid &&
10315 			    un->un_blockcount > label_cap &&
10316 			    un->un_f_expnevent == B_FALSE) {
10317 				un->un_f_expnevent = B_TRUE;
10318 				mutex_exit(SD_MUTEX(un));
10319 				sd_log_lun_expansion_event(un,
10320 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
10321 				mutex_enter(SD_MUTEX(un));
10322 			}
10323 		} else {
10324 			mutex_enter(SD_MUTEX(un));
10325 		}
10326 	}
10327 
10328 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10329 	    "open of part %d type %d\n", part, otyp);
10330 
10331 	mutex_exit(SD_MUTEX(un));
10332 	if (!nodelay) {
10333 		sd_pm_exit(un);
10334 	}
10335 
10336 	sema_v(&un->un_semoclose);
10337 
10338 	mutex_enter(&sd_detach_mutex);
10339 	un->un_opens_in_progress--;
10340 	mutex_exit(&sd_detach_mutex);
10341 
10342 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
10343 	return (DDI_SUCCESS);
10344 
10345 excl_open_fail:
10346 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
10347 	rval = EBUSY;
10348 
10349 open_fail:
10350 	mutex_exit(SD_MUTEX(un));
10351 
10352 	/*
10353 	 * On a failed open we must exit the pm management.
10354 	 */
10355 	if (!nodelay) {
10356 		sd_pm_exit(un);
10357 	}
10358 open_failed_with_pm:
10359 	sema_v(&un->un_semoclose);
10360 
10361 	mutex_enter(&sd_detach_mutex);
10362 	un->un_opens_in_progress--;
10363 	if (otyp == OTYP_LYR) {
10364 		un->un_layer_count--;
10365 	}
10366 	mutex_exit(&sd_detach_mutex);
10367 
10368 	return (rval);
10369 }
10370 
10371 
10372 /*
10373  *    Function: sdclose
10374  *
10375  * Description: Driver's close(9e) entry point function.
10376  *
10377  *   Arguments: dev    - device number
10378  *		flag   - file status flag, informational only
10379  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10380  *		cred_p - user credential pointer
10381  *
10382  * Return Code: ENXIO
10383  *
10384  *     Context: Kernel thread context
10385  */
10386 /* ARGSUSED */
10387 static int
10388 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
10389 {
10390 	struct sd_lun	*un;
10391 	uchar_t		*cp;
10392 	int		part;
10393 	int		nodelay;
10394 	int		rval = 0;
10395 
10396 	/* Validate the open type */
10397 	if (otyp >= OTYPCNT) {
10398 		return (ENXIO);
10399 	}
10400 
10401 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10402 		return (ENXIO);
10403 	}
10404 
10405 	part = SDPART(dev);
10406 	nodelay = flag & (FNDELAY | FNONBLOCK);
10407 
10408 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10409 	    "sdclose: close of part %d type %d\n", part, otyp);
10410 
10411 	/*
10412 	 * We use a semaphore here in order to serialize
10413 	 * open and close requests on the device.
10414 	 */
10415 	sema_p(&un->un_semoclose);
10416 
10417 	mutex_enter(SD_MUTEX(un));
10418 
10419 	/* Don't proceed if power is being changed. */
10420 	while (un->un_state == SD_STATE_PM_CHANGING) {
10421 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10422 	}
10423 
10424 	if (un->un_exclopen & (1 << part)) {
10425 		un->un_exclopen &= ~(1 << part);
10426 	}
10427 
10428 	/* Update the open partition map */
10429 	if (otyp == OTYP_LYR) {
10430 		un->un_ocmap.lyropen[part] -= 1;
10431 	} else {
10432 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
10433 	}
10434 
10435 	cp = &un->un_ocmap.chkd[0];
10436 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10437 		if (*cp != NULL) {
10438 			break;
10439 		}
10440 		cp++;
10441 	}
10442 
10443 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10444 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
10445 
10446 		/*
10447 		 * We avoid persistance upon the last close, and set
10448 		 * the throttle back to the maximum.
10449 		 */
10450 		un->un_throttle = un->un_saved_throttle;
10451 
10452 		if (un->un_state == SD_STATE_OFFLINE) {
10453 			if (un->un_f_is_fibre == FALSE) {
10454 				scsi_log(SD_DEVINFO(un), sd_label,
10455 				    CE_WARN, "offline\n");
10456 			}
10457 			mutex_exit(SD_MUTEX(un));
10458 			cmlb_invalidate(un->un_cmlbhandle,
10459 			    (void *)SD_PATH_DIRECT);
10460 			mutex_enter(SD_MUTEX(un));
10461 
10462 		} else {
10463 			/*
10464 			 * Flush any outstanding writes in NVRAM cache.
10465 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10466 			 * cmd, it may not work for non-Pluto devices.
10467 			 * SYNCHRONIZE CACHE is not required for removables,
10468 			 * except DVD-RAM drives.
10469 			 *
10470 			 * Also note: because SYNCHRONIZE CACHE is currently
10471 			 * the only command issued here that requires the
10472 			 * drive be powered up, only do the power up before
10473 			 * sending the Sync Cache command. If additional
10474 			 * commands are added which require a powered up
10475 			 * drive, the following sequence may have to change.
10476 			 *
10477 			 * And finally, note that parallel SCSI on SPARC
10478 			 * only issues a Sync Cache to DVD-RAM, a newly
10479 			 * supported device.
10480 			 */
10481 #if defined(__i386) || defined(__amd64)
10482 			if ((un->un_f_sync_cache_supported &&
10483 			    un->un_f_sync_cache_required) ||
10484 			    un->un_f_dvdram_writable_device == TRUE) {
10485 #else
10486 			if (un->un_f_dvdram_writable_device == TRUE) {
10487 #endif
10488 				mutex_exit(SD_MUTEX(un));
10489 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10490 					rval =
10491 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10492 					    NULL);
10493 					/* ignore error if not supported */
10494 					if (rval == ENOTSUP) {
10495 						rval = 0;
10496 					} else if (rval != 0) {
10497 						rval = EIO;
10498 					}
10499 					sd_pm_exit(un);
10500 				} else {
10501 					rval = EIO;
10502 				}
10503 				mutex_enter(SD_MUTEX(un));
10504 			}
10505 
10506 			/*
10507 			 * For devices which supports DOOR_LOCK, send an ALLOW
10508 			 * MEDIA REMOVAL command, but don't get upset if it
10509 			 * fails. We need to raise the power of the drive before
10510 			 * we can call sd_send_scsi_DOORLOCK()
10511 			 */
10512 			if (un->un_f_doorlock_supported) {
10513 				mutex_exit(SD_MUTEX(un));
10514 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10515 					sd_ssc_t	*ssc;
10516 
10517 					ssc = sd_ssc_init(un);
10518 					rval = sd_send_scsi_DOORLOCK(ssc,
10519 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10520 					if (rval != 0)
10521 						sd_ssc_assessment(ssc,
10522 						    SD_FMT_IGNORE);
10523 					sd_ssc_fini(ssc);
10524 
10525 					sd_pm_exit(un);
10526 					if (ISCD(un) && (rval != 0) &&
10527 					    (nodelay != 0)) {
10528 						rval = ENXIO;
10529 					}
10530 				} else {
10531 					rval = EIO;
10532 				}
10533 				mutex_enter(SD_MUTEX(un));
10534 			}
10535 
10536 			/*
10537 			 * If a device has removable media, invalidate all
10538 			 * parameters related to media, such as geometry,
10539 			 * blocksize, and blockcount.
10540 			 */
10541 			if (un->un_f_has_removable_media) {
10542 				sr_ejected(un);
10543 			}
10544 
10545 			/*
10546 			 * Destroy the cache (if it exists) which was
10547 			 * allocated for the write maps since this is
10548 			 * the last close for this media.
10549 			 */
10550 			if (un->un_wm_cache) {
10551 				/*
10552 				 * Check if there are pending commands.
10553 				 * and if there are give a warning and
10554 				 * do not destroy the cache.
10555 				 */
10556 				if (un->un_ncmds_in_driver > 0) {
10557 					scsi_log(SD_DEVINFO(un),
10558 					    sd_label, CE_WARN,
10559 					    "Unable to clean up memory "
10560 					    "because of pending I/O\n");
10561 				} else {
10562 					kmem_cache_destroy(
10563 					    un->un_wm_cache);
10564 					un->un_wm_cache = NULL;
10565 				}
10566 			}
10567 		}
10568 	}
10569 
10570 	mutex_exit(SD_MUTEX(un));
10571 	sema_v(&un->un_semoclose);
10572 
10573 	if (otyp == OTYP_LYR) {
10574 		mutex_enter(&sd_detach_mutex);
10575 		/*
10576 		 * The detach routine may run when the layer count
10577 		 * drops to zero.
10578 		 */
10579 		un->un_layer_count--;
10580 		mutex_exit(&sd_detach_mutex);
10581 	}
10582 
10583 	return (rval);
10584 }
10585 
10586 
10587 /*
10588  *    Function: sd_ready_and_valid
10589  *
10590  * Description: Test if device is ready and has a valid geometry.
10591  *
10592  *   Arguments: ssc - sd_ssc_t will contain un
10593  *		un  - driver soft state (unit) structure
10594  *
10595  * Return Code: SD_READY_VALID		ready and valid label
10596  *		SD_NOT_READY_VALID	not ready, no label
10597  *		SD_RESERVED_BY_OTHERS	reservation conflict
10598  *
10599  *     Context: Never called at interrupt context.
10600  */
10601 
10602 static int
10603 sd_ready_and_valid(sd_ssc_t *ssc, int part)
10604 {
10605 	struct sd_errstats	*stp;
10606 	uint64_t		capacity;
10607 	uint_t			lbasize;
10608 	int			rval = SD_READY_VALID;
10609 	char			name_str[48];
10610 	boolean_t		is_valid;
10611 	struct sd_lun		*un;
10612 	int			status;
10613 
10614 	ASSERT(ssc != NULL);
10615 	un = ssc->ssc_un;
10616 	ASSERT(un != NULL);
10617 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10618 
10619 	mutex_enter(SD_MUTEX(un));
10620 	/*
10621 	 * If a device has removable media, we must check if media is
10622 	 * ready when checking if this device is ready and valid.
10623 	 */
10624 	if (un->un_f_has_removable_media) {
10625 		mutex_exit(SD_MUTEX(un));
10626 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10627 
10628 		if (status != 0) {
10629 			rval = SD_NOT_READY_VALID;
10630 			mutex_enter(SD_MUTEX(un));
10631 
10632 			/* Ignore all failed status for removalbe media */
10633 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10634 
10635 			goto done;
10636 		}
10637 
10638 		is_valid = SD_IS_VALID_LABEL(un);
10639 		mutex_enter(SD_MUTEX(un));
10640 		if (!is_valid ||
10641 		    (un->un_f_blockcount_is_valid == FALSE) ||
10642 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10643 
10644 			/* capacity has to be read every open. */
10645 			mutex_exit(SD_MUTEX(un));
10646 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
10647 			    &lbasize, SD_PATH_DIRECT);
10648 
10649 			if (status != 0) {
10650 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10651 
10652 				cmlb_invalidate(un->un_cmlbhandle,
10653 				    (void *)SD_PATH_DIRECT);
10654 				mutex_enter(SD_MUTEX(un));
10655 				rval = SD_NOT_READY_VALID;
10656 
10657 				goto done;
10658 			} else {
10659 				mutex_enter(SD_MUTEX(un));
10660 				sd_update_block_info(un, lbasize, capacity);
10661 			}
10662 		}
10663 
10664 		/*
10665 		 * Check if the media in the device is writable or not.
10666 		 */
10667 		if (!is_valid && ISCD(un)) {
10668 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
10669 		}
10670 
10671 	} else {
10672 		/*
10673 		 * Do a test unit ready to clear any unit attention from non-cd
10674 		 * devices.
10675 		 */
10676 		mutex_exit(SD_MUTEX(un));
10677 
10678 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10679 		if (status != 0) {
10680 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10681 		}
10682 
10683 		mutex_enter(SD_MUTEX(un));
10684 	}
10685 
10686 
10687 	/*
10688 	 * If this is a non 512 block device, allocate space for
10689 	 * the wmap cache. This is being done here since every time
10690 	 * a media is changed this routine will be called and the
10691 	 * block size is a function of media rather than device.
10692 	 */
10693 	if (((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR ||
10694 	    un->un_f_non_devbsize_supported) &&
10695 	    un->un_tgt_blocksize != DEV_BSIZE) ||
10696 	    un->un_f_enable_rmw) {
10697 		if (!(un->un_wm_cache)) {
10698 			(void) snprintf(name_str, sizeof (name_str),
10699 			    "%s%d_cache",
10700 			    ddi_driver_name(SD_DEVINFO(un)),
10701 			    ddi_get_instance(SD_DEVINFO(un)));
10702 			un->un_wm_cache = kmem_cache_create(
10703 			    name_str, sizeof (struct sd_w_map),
10704 			    8, sd_wm_cache_constructor,
10705 			    sd_wm_cache_destructor, NULL,
10706 			    (void *)un, NULL, 0);
10707 			if (!(un->un_wm_cache)) {
10708 				rval = ENOMEM;
10709 				goto done;
10710 			}
10711 		}
10712 	}
10713 
10714 	if (un->un_state == SD_STATE_NORMAL) {
10715 		/*
10716 		 * If the target is not yet ready here (defined by a TUR
10717 		 * failure), invalidate the geometry and print an 'offline'
10718 		 * message. This is a legacy message, as the state of the
10719 		 * target is not actually changed to SD_STATE_OFFLINE.
10720 		 *
10721 		 * If the TUR fails for EACCES (Reservation Conflict),
10722 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
10723 		 * reservation conflict. If the TUR fails for other
10724 		 * reasons, SD_NOT_READY_VALID will be returned.
10725 		 */
10726 		int err;
10727 
10728 		mutex_exit(SD_MUTEX(un));
10729 		err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10730 		mutex_enter(SD_MUTEX(un));
10731 
10732 		if (err != 0) {
10733 			mutex_exit(SD_MUTEX(un));
10734 			cmlb_invalidate(un->un_cmlbhandle,
10735 			    (void *)SD_PATH_DIRECT);
10736 			mutex_enter(SD_MUTEX(un));
10737 			if (err == EACCES) {
10738 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10739 				    "reservation conflict\n");
10740 				rval = SD_RESERVED_BY_OTHERS;
10741 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10742 			} else {
10743 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10744 				    "drive offline\n");
10745 				rval = SD_NOT_READY_VALID;
10746 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
10747 			}
10748 			goto done;
10749 		}
10750 	}
10751 
10752 	if (un->un_f_format_in_progress == FALSE) {
10753 		mutex_exit(SD_MUTEX(un));
10754 
10755 		(void) cmlb_validate(un->un_cmlbhandle, 0,
10756 		    (void *)SD_PATH_DIRECT);
10757 		if (cmlb_partinfo(un->un_cmlbhandle, part, NULL, NULL, NULL,
10758 		    NULL, (void *) SD_PATH_DIRECT) != 0) {
10759 			rval = SD_NOT_READY_VALID;
10760 			mutex_enter(SD_MUTEX(un));
10761 
10762 			goto done;
10763 		}
10764 		if (un->un_f_pkstats_enabled) {
10765 			sd_set_pstats(un);
10766 			SD_TRACE(SD_LOG_IO_PARTITION, un,
10767 			    "sd_ready_and_valid: un:0x%p pstats created and "
10768 			    "set\n", un);
10769 		}
10770 		mutex_enter(SD_MUTEX(un));
10771 	}
10772 
10773 	/*
10774 	 * If this device supports DOOR_LOCK command, try and send
10775 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10776 	 * if it fails. For a CD, however, it is an error
10777 	 */
10778 	if (un->un_f_doorlock_supported) {
10779 		mutex_exit(SD_MUTEX(un));
10780 		status = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
10781 		    SD_PATH_DIRECT);
10782 
10783 		if ((status != 0) && ISCD(un)) {
10784 			rval = SD_NOT_READY_VALID;
10785 			mutex_enter(SD_MUTEX(un));
10786 
10787 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10788 
10789 			goto done;
10790 		} else if (status != 0)
10791 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10792 		mutex_enter(SD_MUTEX(un));
10793 	}
10794 
10795 	/* The state has changed, inform the media watch routines */
10796 	un->un_mediastate = DKIO_INSERTED;
10797 	cv_broadcast(&un->un_state_cv);
10798 	rval = SD_READY_VALID;
10799 
10800 done:
10801 
10802 	/*
10803 	 * Initialize the capacity kstat value, if no media previously
10804 	 * (capacity kstat is 0) and a media has been inserted
10805 	 * (un_blockcount > 0).
10806 	 */
10807 	if (un->un_errstats != NULL) {
10808 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10809 		if ((stp->sd_capacity.value.ui64 == 0) &&
10810 		    (un->un_f_blockcount_is_valid == TRUE)) {
10811 			stp->sd_capacity.value.ui64 =
10812 			    (uint64_t)((uint64_t)un->un_blockcount *
10813 			    un->un_sys_blocksize);
10814 		}
10815 	}
10816 
10817 	mutex_exit(SD_MUTEX(un));
10818 	return (rval);
10819 }
10820 
10821 
10822 /*
10823  *    Function: sdmin
10824  *
10825  * Description: Routine to limit the size of a data transfer. Used in
10826  *		conjunction with physio(9F).
10827  *
10828  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10829  *
10830  *     Context: Kernel thread context.
10831  */
10832 
10833 static void
10834 sdmin(struct buf *bp)
10835 {
10836 	struct sd_lun	*un;
10837 	int		instance;
10838 
10839 	instance = SDUNIT(bp->b_edev);
10840 
10841 	un = ddi_get_soft_state(sd_state, instance);
10842 	ASSERT(un != NULL);
10843 
10844 	/*
10845 	 * We depend on buf breakup to restrict
10846 	 * IO size if it is enabled.
10847 	 */
10848 	if (un->un_buf_breakup_supported) {
10849 		return;
10850 	}
10851 
10852 	if (bp->b_bcount > un->un_max_xfer_size) {
10853 		bp->b_bcount = un->un_max_xfer_size;
10854 	}
10855 }
10856 
10857 
10858 /*
10859  *    Function: sdread
10860  *
10861  * Description: Driver's read(9e) entry point function.
10862  *
10863  *   Arguments: dev   - device number
10864  *		uio   - structure pointer describing where data is to be stored
10865  *			in user's space
10866  *		cred_p  - user credential pointer
10867  *
10868  * Return Code: ENXIO
10869  *		EIO
10870  *		EINVAL
10871  *		value returned by physio
10872  *
10873  *     Context: Kernel thread context.
10874  */
10875 /* ARGSUSED */
10876 static int
10877 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10878 {
10879 	struct sd_lun	*un = NULL;
10880 	int		secmask;
10881 	int		err = 0;
10882 	sd_ssc_t	*ssc;
10883 
10884 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10885 		return (ENXIO);
10886 	}
10887 
10888 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10889 
10890 
10891 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10892 		mutex_enter(SD_MUTEX(un));
10893 		/*
10894 		 * Because the call to sd_ready_and_valid will issue I/O we
10895 		 * must wait here if either the device is suspended or
10896 		 * if it's power level is changing.
10897 		 */
10898 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10899 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10900 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10901 		}
10902 		un->un_ncmds_in_driver++;
10903 		mutex_exit(SD_MUTEX(un));
10904 
10905 		/* Initialize sd_ssc_t for internal uscsi commands */
10906 		ssc = sd_ssc_init(un);
10907 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10908 			err = EIO;
10909 		} else {
10910 			err = 0;
10911 		}
10912 		sd_ssc_fini(ssc);
10913 
10914 		mutex_enter(SD_MUTEX(un));
10915 		un->un_ncmds_in_driver--;
10916 		ASSERT(un->un_ncmds_in_driver >= 0);
10917 		mutex_exit(SD_MUTEX(un));
10918 		if (err != 0)
10919 			return (err);
10920 	}
10921 
10922 	/*
10923 	 * Read requests are restricted to multiples of the system block size.
10924 	 */
10925 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
10926 	    !un->un_f_enable_rmw)
10927 		secmask = un->un_tgt_blocksize - 1;
10928 	else
10929 		secmask = DEV_BSIZE - 1;
10930 
10931 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10932 		SD_ERROR(SD_LOG_READ_WRITE, un,
10933 		    "sdread: file offset not modulo %d\n",
10934 		    secmask + 1);
10935 		err = EINVAL;
10936 	} else if (uio->uio_iov->iov_len & (secmask)) {
10937 		SD_ERROR(SD_LOG_READ_WRITE, un,
10938 		    "sdread: transfer length not modulo %d\n",
10939 		    secmask + 1);
10940 		err = EINVAL;
10941 	} else {
10942 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
10943 	}
10944 
10945 	return (err);
10946 }
10947 
10948 
10949 /*
10950  *    Function: sdwrite
10951  *
10952  * Description: Driver's write(9e) entry point function.
10953  *
10954  *   Arguments: dev   - device number
10955  *		uio   - structure pointer describing where data is stored in
10956  *			user's space
10957  *		cred_p  - user credential pointer
10958  *
10959  * Return Code: ENXIO
10960  *		EIO
10961  *		EINVAL
10962  *		value returned by physio
10963  *
10964  *     Context: Kernel thread context.
10965  */
10966 /* ARGSUSED */
10967 static int
10968 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
10969 {
10970 	struct sd_lun	*un = NULL;
10971 	int		secmask;
10972 	int		err = 0;
10973 	sd_ssc_t	*ssc;
10974 
10975 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10976 		return (ENXIO);
10977 	}
10978 
10979 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10980 
10981 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10982 		mutex_enter(SD_MUTEX(un));
10983 		/*
10984 		 * Because the call to sd_ready_and_valid will issue I/O we
10985 		 * must wait here if either the device is suspended or
10986 		 * if it's power level is changing.
10987 		 */
10988 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10989 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10990 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10991 		}
10992 		un->un_ncmds_in_driver++;
10993 		mutex_exit(SD_MUTEX(un));
10994 
10995 		/* Initialize sd_ssc_t for internal uscsi commands */
10996 		ssc = sd_ssc_init(un);
10997 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10998 			err = EIO;
10999 		} else {
11000 			err = 0;
11001 		}
11002 		sd_ssc_fini(ssc);
11003 
11004 		mutex_enter(SD_MUTEX(un));
11005 		un->un_ncmds_in_driver--;
11006 		ASSERT(un->un_ncmds_in_driver >= 0);
11007 		mutex_exit(SD_MUTEX(un));
11008 		if (err != 0)
11009 			return (err);
11010 	}
11011 
11012 	/*
11013 	 * Write requests are restricted to multiples of the system block size.
11014 	 */
11015 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11016 	    !un->un_f_enable_rmw)
11017 		secmask = un->un_tgt_blocksize - 1;
11018 	else
11019 		secmask = DEV_BSIZE - 1;
11020 
11021 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11022 		SD_ERROR(SD_LOG_READ_WRITE, un,
11023 		    "sdwrite: file offset not modulo %d\n",
11024 		    secmask + 1);
11025 		err = EINVAL;
11026 	} else if (uio->uio_iov->iov_len & (secmask)) {
11027 		SD_ERROR(SD_LOG_READ_WRITE, un,
11028 		    "sdwrite: transfer length not modulo %d\n",
11029 		    secmask + 1);
11030 		err = EINVAL;
11031 	} else {
11032 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
11033 	}
11034 
11035 	return (err);
11036 }
11037 
11038 
11039 /*
11040  *    Function: sdaread
11041  *
11042  * Description: Driver's aread(9e) entry point function.
11043  *
11044  *   Arguments: dev   - device number
11045  *		aio   - structure pointer describing where data is to be stored
11046  *		cred_p  - user credential pointer
11047  *
11048  * Return Code: ENXIO
11049  *		EIO
11050  *		EINVAL
11051  *		value returned by aphysio
11052  *
11053  *     Context: Kernel thread context.
11054  */
11055 /* ARGSUSED */
11056 static int
11057 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11058 {
11059 	struct sd_lun	*un = NULL;
11060 	struct uio	*uio = aio->aio_uio;
11061 	int		secmask;
11062 	int		err = 0;
11063 	sd_ssc_t	*ssc;
11064 
11065 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11066 		return (ENXIO);
11067 	}
11068 
11069 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11070 
11071 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11072 		mutex_enter(SD_MUTEX(un));
11073 		/*
11074 		 * Because the call to sd_ready_and_valid will issue I/O we
11075 		 * must wait here if either the device is suspended or
11076 		 * if it's power level is changing.
11077 		 */
11078 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11079 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11080 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11081 		}
11082 		un->un_ncmds_in_driver++;
11083 		mutex_exit(SD_MUTEX(un));
11084 
11085 		/* Initialize sd_ssc_t for internal uscsi commands */
11086 		ssc = sd_ssc_init(un);
11087 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11088 			err = EIO;
11089 		} else {
11090 			err = 0;
11091 		}
11092 		sd_ssc_fini(ssc);
11093 
11094 		mutex_enter(SD_MUTEX(un));
11095 		un->un_ncmds_in_driver--;
11096 		ASSERT(un->un_ncmds_in_driver >= 0);
11097 		mutex_exit(SD_MUTEX(un));
11098 		if (err != 0)
11099 			return (err);
11100 	}
11101 
11102 	/*
11103 	 * Read requests are restricted to multiples of the system block size.
11104 	 */
11105 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11106 	    !un->un_f_enable_rmw)
11107 		secmask = un->un_tgt_blocksize - 1;
11108 	else
11109 		secmask = DEV_BSIZE - 1;
11110 
11111 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11112 		SD_ERROR(SD_LOG_READ_WRITE, un,
11113 		    "sdaread: file offset not modulo %d\n",
11114 		    secmask + 1);
11115 		err = EINVAL;
11116 	} else if (uio->uio_iov->iov_len & (secmask)) {
11117 		SD_ERROR(SD_LOG_READ_WRITE, un,
11118 		    "sdaread: transfer length not modulo %d\n",
11119 		    secmask + 1);
11120 		err = EINVAL;
11121 	} else {
11122 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
11123 	}
11124 
11125 	return (err);
11126 }
11127 
11128 
11129 /*
11130  *    Function: sdawrite
11131  *
11132  * Description: Driver's awrite(9e) entry point function.
11133  *
11134  *   Arguments: dev   - device number
11135  *		aio   - structure pointer describing where data is stored
11136  *		cred_p  - user credential pointer
11137  *
11138  * Return Code: ENXIO
11139  *		EIO
11140  *		EINVAL
11141  *		value returned by aphysio
11142  *
11143  *     Context: Kernel thread context.
11144  */
11145 /* ARGSUSED */
11146 static int
11147 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11148 {
11149 	struct sd_lun	*un = NULL;
11150 	struct uio	*uio = aio->aio_uio;
11151 	int		secmask;
11152 	int		err = 0;
11153 	sd_ssc_t	*ssc;
11154 
11155 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11156 		return (ENXIO);
11157 	}
11158 
11159 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11160 
11161 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11162 		mutex_enter(SD_MUTEX(un));
11163 		/*
11164 		 * Because the call to sd_ready_and_valid will issue I/O we
11165 		 * must wait here if either the device is suspended or
11166 		 * if it's power level is changing.
11167 		 */
11168 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11169 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11170 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11171 		}
11172 		un->un_ncmds_in_driver++;
11173 		mutex_exit(SD_MUTEX(un));
11174 
11175 		/* Initialize sd_ssc_t for internal uscsi commands */
11176 		ssc = sd_ssc_init(un);
11177 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11178 			err = EIO;
11179 		} else {
11180 			err = 0;
11181 		}
11182 		sd_ssc_fini(ssc);
11183 
11184 		mutex_enter(SD_MUTEX(un));
11185 		un->un_ncmds_in_driver--;
11186 		ASSERT(un->un_ncmds_in_driver >= 0);
11187 		mutex_exit(SD_MUTEX(un));
11188 		if (err != 0)
11189 			return (err);
11190 	}
11191 
11192 	/*
11193 	 * Write requests are restricted to multiples of the system block size.
11194 	 */
11195 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11196 	    !un->un_f_enable_rmw)
11197 		secmask = un->un_tgt_blocksize - 1;
11198 	else
11199 		secmask = DEV_BSIZE - 1;
11200 
11201 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11202 		SD_ERROR(SD_LOG_READ_WRITE, un,
11203 		    "sdawrite: file offset not modulo %d\n",
11204 		    secmask + 1);
11205 		err = EINVAL;
11206 	} else if (uio->uio_iov->iov_len & (secmask)) {
11207 		SD_ERROR(SD_LOG_READ_WRITE, un,
11208 		    "sdawrite: transfer length not modulo %d\n",
11209 		    secmask + 1);
11210 		err = EINVAL;
11211 	} else {
11212 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
11213 	}
11214 
11215 	return (err);
11216 }
11217 
11218 
11219 
11220 
11221 
11222 /*
11223  * Driver IO processing follows the following sequence:
11224  *
11225  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
11226  *         |                |                     ^
11227  *         v                v                     |
11228  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
11229  *         |                |                     |                   |
11230  *         v                |                     |                   |
11231  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
11232  *         |                |                     ^                   ^
11233  *         v                v                     |                   |
11234  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
11235  *         |                |                     |                   |
11236  *     +---+                |                     +------------+      +-------+
11237  *     |                    |                                  |              |
11238  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11239  *     |                    v                                  |              |
11240  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
11241  *     |                    |                                  ^              |
11242  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11243  *     |                    v                                  |              |
11244  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
11245  *     |                    |                                  ^              |
11246  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11247  *     |                    v                                  |              |
11248  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
11249  *     |                    |                                  ^              |
11250  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
11251  *     |                    v                                  |              |
11252  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
11253  *     |                    |                                  ^              |
11254  *     |                    |                                  |              |
11255  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
11256  *                          |                           ^
11257  *                          v                           |
11258  *                   sd_core_iostart()                  |
11259  *                          |                           |
11260  *                          |                           +------>(*destroypkt)()
11261  *                          +-> sd_start_cmds() <-+     |           |
11262  *                          |                     |     |           v
11263  *                          |                     |     |  scsi_destroy_pkt(9F)
11264  *                          |                     |     |
11265  *                          +->(*initpkt)()       +- sdintr()
11266  *                          |  |                        |  |
11267  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
11268  *                          |  +-> scsi_setup_cdb(9F)   |
11269  *                          |                           |
11270  *                          +--> scsi_transport(9F)     |
11271  *                                     |                |
11272  *                                     +----> SCSA ---->+
11273  *
11274  *
11275  * This code is based upon the following presumptions:
11276  *
11277  *   - iostart and iodone functions operate on buf(9S) structures. These
11278  *     functions perform the necessary operations on the buf(9S) and pass
11279  *     them along to the next function in the chain by using the macros
11280  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
11281  *     (for iodone side functions).
11282  *
11283  *   - The iostart side functions may sleep. The iodone side functions
11284  *     are called under interrupt context and may NOT sleep. Therefore
11285  *     iodone side functions also may not call iostart side functions.
11286  *     (NOTE: iostart side functions should NOT sleep for memory, as
11287  *     this could result in deadlock.)
11288  *
11289  *   - An iostart side function may call its corresponding iodone side
11290  *     function directly (if necessary).
11291  *
11292  *   - In the event of an error, an iostart side function can return a buf(9S)
11293  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
11294  *     b_error in the usual way of course).
11295  *
11296  *   - The taskq mechanism may be used by the iodone side functions to dispatch
11297  *     requests to the iostart side functions.  The iostart side functions in
11298  *     this case would be called under the context of a taskq thread, so it's
11299  *     OK for them to block/sleep/spin in this case.
11300  *
11301  *   - iostart side functions may allocate "shadow" buf(9S) structs and
11302  *     pass them along to the next function in the chain.  The corresponding
11303  *     iodone side functions must coalesce the "shadow" bufs and return
11304  *     the "original" buf to the next higher layer.
11305  *
11306  *   - The b_private field of the buf(9S) struct holds a pointer to
11307  *     an sd_xbuf struct, which contains information needed to
11308  *     construct the scsi_pkt for the command.
11309  *
11310  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
11311  *     layer must acquire & release the SD_MUTEX(un) as needed.
11312  */
11313 
11314 
11315 /*
11316  * Create taskq for all targets in the system. This is created at
11317  * _init(9E) and destroyed at _fini(9E).
11318  *
11319  * Note: here we set the minalloc to a reasonably high number to ensure that
11320  * we will have an adequate supply of task entries available at interrupt time.
11321  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
11322  * sd_create_taskq().  Since we do not want to sleep for allocations at
11323  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
11324  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
11325  * requests any one instant in time.
11326  */
11327 #define	SD_TASKQ_NUMTHREADS	8
11328 #define	SD_TASKQ_MINALLOC	256
11329 #define	SD_TASKQ_MAXALLOC	256
11330 
11331 static taskq_t	*sd_tq = NULL;
11332 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
11333 
11334 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
11335 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
11336 
11337 /*
11338  * The following task queue is being created for the write part of
11339  * read-modify-write of non-512 block size devices.
11340  * Limit the number of threads to 1 for now. This number has been chosen
11341  * considering the fact that it applies only to dvd ram drives/MO drives
11342  * currently. Performance for which is not main criteria at this stage.
11343  * Note: It needs to be explored if we can use a single taskq in future
11344  */
11345 #define	SD_WMR_TASKQ_NUMTHREADS	1
11346 static taskq_t	*sd_wmr_tq = NULL;
11347 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
11348 
11349 /*
11350  *    Function: sd_taskq_create
11351  *
11352  * Description: Create taskq thread(s) and preallocate task entries
11353  *
11354  * Return Code: Returns a pointer to the allocated taskq_t.
11355  *
11356  *     Context: Can sleep. Requires blockable context.
11357  *
11358  *       Notes: - The taskq() facility currently is NOT part of the DDI.
11359  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
11360  *		- taskq_create() will block for memory, also it will panic
11361  *		  if it cannot create the requested number of threads.
11362  *		- Currently taskq_create() creates threads that cannot be
11363  *		  swapped.
11364  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
11365  *		  supply of taskq entries at interrupt time (ie, so that we
11366  *		  do not have to sleep for memory)
11367  */
11368 
11369 static void
11370 sd_taskq_create(void)
11371 {
11372 	char	taskq_name[TASKQ_NAMELEN];
11373 
11374 	ASSERT(sd_tq == NULL);
11375 	ASSERT(sd_wmr_tq == NULL);
11376 
11377 	(void) snprintf(taskq_name, sizeof (taskq_name),
11378 	    "%s_drv_taskq", sd_label);
11379 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
11380 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11381 	    TASKQ_PREPOPULATE));
11382 
11383 	(void) snprintf(taskq_name, sizeof (taskq_name),
11384 	    "%s_rmw_taskq", sd_label);
11385 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
11386 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11387 	    TASKQ_PREPOPULATE));
11388 }
11389 
11390 
11391 /*
11392  *    Function: sd_taskq_delete
11393  *
11394  * Description: Complementary cleanup routine for sd_taskq_create().
11395  *
11396  *     Context: Kernel thread context.
11397  */
11398 
11399 static void
11400 sd_taskq_delete(void)
11401 {
11402 	ASSERT(sd_tq != NULL);
11403 	ASSERT(sd_wmr_tq != NULL);
11404 	taskq_destroy(sd_tq);
11405 	taskq_destroy(sd_wmr_tq);
11406 	sd_tq = NULL;
11407 	sd_wmr_tq = NULL;
11408 }
11409 
11410 
11411 /*
11412  *    Function: sdstrategy
11413  *
11414  * Description: Driver's strategy (9E) entry point function.
11415  *
11416  *   Arguments: bp - pointer to buf(9S)
11417  *
11418  * Return Code: Always returns zero
11419  *
11420  *     Context: Kernel thread context.
11421  */
11422 
11423 static int
11424 sdstrategy(struct buf *bp)
11425 {
11426 	struct sd_lun *un;
11427 
11428 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11429 	if (un == NULL) {
11430 		bioerror(bp, EIO);
11431 		bp->b_resid = bp->b_bcount;
11432 		biodone(bp);
11433 		return (0);
11434 	}
11435 
11436 	/* As was done in the past, fail new cmds. if state is dumping. */
11437 	if (un->un_state == SD_STATE_DUMPING) {
11438 		bioerror(bp, ENXIO);
11439 		bp->b_resid = bp->b_bcount;
11440 		biodone(bp);
11441 		return (0);
11442 	}
11443 
11444 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11445 
11446 	/*
11447 	 * Commands may sneak in while we released the mutex in
11448 	 * DDI_SUSPEND, we should block new commands. However, old
11449 	 * commands that are still in the driver at this point should
11450 	 * still be allowed to drain.
11451 	 */
11452 	mutex_enter(SD_MUTEX(un));
11453 	/*
11454 	 * Must wait here if either the device is suspended or
11455 	 * if it's power level is changing.
11456 	 */
11457 	while ((un->un_state == SD_STATE_SUSPENDED) ||
11458 	    (un->un_state == SD_STATE_PM_CHANGING)) {
11459 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11460 	}
11461 
11462 	un->un_ncmds_in_driver++;
11463 
11464 	/*
11465 	 * atapi: Since we are running the CD for now in PIO mode we need to
11466 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11467 	 * the HBA's init_pkt routine.
11468 	 */
11469 	if (un->un_f_cfg_is_atapi == TRUE) {
11470 		mutex_exit(SD_MUTEX(un));
11471 		bp_mapin(bp);
11472 		mutex_enter(SD_MUTEX(un));
11473 	}
11474 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
11475 	    un->un_ncmds_in_driver);
11476 
11477 	if (bp->b_flags & B_WRITE)
11478 		un->un_f_sync_cache_required = TRUE;
11479 
11480 	mutex_exit(SD_MUTEX(un));
11481 
11482 	/*
11483 	 * This will (eventually) allocate the sd_xbuf area and
11484 	 * call sd_xbuf_strategy().  We just want to return the
11485 	 * result of ddi_xbuf_qstrategy so that we have an opt-
11486 	 * imized tail call which saves us a stack frame.
11487 	 */
11488 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
11489 }
11490 
11491 
11492 /*
11493  *    Function: sd_xbuf_strategy
11494  *
11495  * Description: Function for initiating IO operations via the
11496  *		ddi_xbuf_qstrategy() mechanism.
11497  *
11498  *     Context: Kernel thread context.
11499  */
11500 
11501 static void
11502 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11503 {
11504 	struct sd_lun *un = arg;
11505 
11506 	ASSERT(bp != NULL);
11507 	ASSERT(xp != NULL);
11508 	ASSERT(un != NULL);
11509 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11510 
11511 	/*
11512 	 * Initialize the fields in the xbuf and save a pointer to the
11513 	 * xbuf in bp->b_private.
11514 	 */
11515 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11516 
11517 	/* Send the buf down the iostart chain */
11518 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11519 }
11520 
11521 
11522 /*
11523  *    Function: sd_xbuf_init
11524  *
11525  * Description: Prepare the given sd_xbuf struct for use.
11526  *
11527  *   Arguments: un - ptr to softstate
11528  *		bp - ptr to associated buf(9S)
11529  *		xp - ptr to associated sd_xbuf
11530  *		chain_type - IO chain type to use:
11531  *			SD_CHAIN_NULL
11532  *			SD_CHAIN_BUFIO
11533  *			SD_CHAIN_USCSI
11534  *			SD_CHAIN_DIRECT
11535  *			SD_CHAIN_DIRECT_PRIORITY
11536  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11537  *			initialization; may be NULL if none.
11538  *
11539  *     Context: Kernel thread context
11540  */
11541 
11542 static void
11543 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11544 	uchar_t chain_type, void *pktinfop)
11545 {
11546 	int index;
11547 
11548 	ASSERT(un != NULL);
11549 	ASSERT(bp != NULL);
11550 	ASSERT(xp != NULL);
11551 
11552 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11553 	    bp, chain_type);
11554 
11555 	xp->xb_un	= un;
11556 	xp->xb_pktp	= NULL;
11557 	xp->xb_pktinfo	= pktinfop;
11558 	xp->xb_private	= bp->b_private;
11559 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11560 
11561 	/*
11562 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11563 	 * upon the specified chain type to use.
11564 	 */
11565 	switch (chain_type) {
11566 	case SD_CHAIN_NULL:
11567 		/*
11568 		 * Fall thru to just use the values for the buf type, even
11569 		 * tho for the NULL chain these values will never be used.
11570 		 */
11571 		/* FALLTHRU */
11572 	case SD_CHAIN_BUFIO:
11573 		index = un->un_buf_chain_type;
11574 		if ((!un->un_f_has_removable_media) &&
11575 		    (un->un_tgt_blocksize != 0) &&
11576 		    (un->un_tgt_blocksize != DEV_BSIZE ||
11577 		    un->un_f_enable_rmw)) {
11578 			int secmask = 0, blknomask = 0;
11579 			if (un->un_f_enable_rmw) {
11580 				blknomask =
11581 				    (un->un_phy_blocksize / DEV_BSIZE) - 1;
11582 				secmask = un->un_phy_blocksize - 1;
11583 			} else {
11584 				blknomask =
11585 				    (un->un_tgt_blocksize / DEV_BSIZE) - 1;
11586 				secmask = un->un_tgt_blocksize - 1;
11587 			}
11588 
11589 			if ((bp->b_lblkno & (blknomask)) ||
11590 			    (bp->b_bcount & (secmask))) {
11591 				if ((un->un_f_rmw_type !=
11592 				    SD_RMW_TYPE_RETURN_ERROR) ||
11593 				    un->un_f_enable_rmw) {
11594 					if (un->un_f_pm_is_enabled == FALSE)
11595 						index =
11596 						    SD_CHAIN_INFO_MSS_DSK_NO_PM;
11597 					else
11598 						index =
11599 						    SD_CHAIN_INFO_MSS_DISK;
11600 				}
11601 			}
11602 		}
11603 		break;
11604 	case SD_CHAIN_USCSI:
11605 		index = un->un_uscsi_chain_type;
11606 		break;
11607 	case SD_CHAIN_DIRECT:
11608 		index = un->un_direct_chain_type;
11609 		break;
11610 	case SD_CHAIN_DIRECT_PRIORITY:
11611 		index = un->un_priority_chain_type;
11612 		break;
11613 	default:
11614 		/* We're really broken if we ever get here... */
11615 		panic("sd_xbuf_init: illegal chain type!");
11616 		/*NOTREACHED*/
11617 	}
11618 
11619 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11620 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11621 
11622 	/*
11623 	 * It might be a bit easier to simply bzero the entire xbuf above,
11624 	 * but it turns out that since we init a fair number of members anyway,
11625 	 * we save a fair number cycles by doing explicit assignment of zero.
11626 	 */
11627 	xp->xb_pkt_flags	= 0;
11628 	xp->xb_dma_resid	= 0;
11629 	xp->xb_retry_count	= 0;
11630 	xp->xb_victim_retry_count = 0;
11631 	xp->xb_ua_retry_count	= 0;
11632 	xp->xb_nr_retry_count	= 0;
11633 	xp->xb_sense_bp		= NULL;
11634 	xp->xb_sense_status	= 0;
11635 	xp->xb_sense_state	= 0;
11636 	xp->xb_sense_resid	= 0;
11637 	xp->xb_ena		= 0;
11638 
11639 	bp->b_private	= xp;
11640 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11641 	bp->b_resid	= 0;
11642 	bp->av_forw	= NULL;
11643 	bp->av_back	= NULL;
11644 	bioerror(bp, 0);
11645 
11646 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11647 }
11648 
11649 
11650 /*
11651  *    Function: sd_uscsi_strategy
11652  *
11653  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11654  *
11655  *   Arguments: bp - buf struct ptr
11656  *
11657  * Return Code: Always returns 0
11658  *
11659  *     Context: Kernel thread context
11660  */
11661 
11662 static int
11663 sd_uscsi_strategy(struct buf *bp)
11664 {
11665 	struct sd_lun		*un;
11666 	struct sd_uscsi_info	*uip;
11667 	struct sd_xbuf		*xp;
11668 	uchar_t			chain_type;
11669 	uchar_t			cmd;
11670 
11671 	ASSERT(bp != NULL);
11672 
11673 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11674 	if (un == NULL) {
11675 		bioerror(bp, EIO);
11676 		bp->b_resid = bp->b_bcount;
11677 		biodone(bp);
11678 		return (0);
11679 	}
11680 
11681 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11682 
11683 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11684 
11685 	/*
11686 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11687 	 */
11688 	ASSERT(bp->b_private != NULL);
11689 	uip = (struct sd_uscsi_info *)bp->b_private;
11690 	cmd = ((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_cdb[0];
11691 
11692 	mutex_enter(SD_MUTEX(un));
11693 	/*
11694 	 * atapi: Since we are running the CD for now in PIO mode we need to
11695 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11696 	 * the HBA's init_pkt routine.
11697 	 */
11698 	if (un->un_f_cfg_is_atapi == TRUE) {
11699 		mutex_exit(SD_MUTEX(un));
11700 		bp_mapin(bp);
11701 		mutex_enter(SD_MUTEX(un));
11702 	}
11703 	un->un_ncmds_in_driver++;
11704 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11705 	    un->un_ncmds_in_driver);
11706 
11707 	if ((bp->b_flags & B_WRITE) && (bp->b_bcount != 0) &&
11708 	    (cmd != SCMD_MODE_SELECT) && (cmd != SCMD_MODE_SELECT_G1))
11709 		un->un_f_sync_cache_required = TRUE;
11710 
11711 	mutex_exit(SD_MUTEX(un));
11712 
11713 	switch (uip->ui_flags) {
11714 	case SD_PATH_DIRECT:
11715 		chain_type = SD_CHAIN_DIRECT;
11716 		break;
11717 	case SD_PATH_DIRECT_PRIORITY:
11718 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11719 		break;
11720 	default:
11721 		chain_type = SD_CHAIN_USCSI;
11722 		break;
11723 	}
11724 
11725 	/*
11726 	 * We may allocate extra buf for external USCSI commands. If the
11727 	 * application asks for bigger than 20-byte sense data via USCSI,
11728 	 * SCSA layer will allocate 252 bytes sense buf for that command.
11729 	 */
11730 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
11731 	    SENSE_LENGTH) {
11732 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
11733 		    MAX_SENSE_LENGTH, KM_SLEEP);
11734 	} else {
11735 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
11736 	}
11737 
11738 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11739 
11740 	/* Use the index obtained within xbuf_init */
11741 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11742 
11743 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11744 
11745 	return (0);
11746 }
11747 
11748 /*
11749  *    Function: sd_send_scsi_cmd
11750  *
11751  * Description: Runs a USCSI command for user (when called thru sdioctl),
11752  *		or for the driver
11753  *
11754  *   Arguments: dev - the dev_t for the device
11755  *		incmd - ptr to a valid uscsi_cmd struct
11756  *		flag - bit flag, indicating open settings, 32/64 bit type
11757  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11758  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11759  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11760  *			to use the USCSI "direct" chain and bypass the normal
11761  *			command waitq.
11762  *
11763  * Return Code: 0 -  successful completion of the given command
11764  *		EIO - scsi_uscsi_handle_command() failed
11765  *		ENXIO  - soft state not found for specified dev
11766  *		EINVAL
11767  *		EFAULT - copyin/copyout error
11768  *		return code of scsi_uscsi_handle_command():
11769  *			EIO
11770  *			ENXIO
11771  *			EACCES
11772  *
11773  *     Context: Waits for command to complete. Can sleep.
11774  */
11775 
11776 static int
11777 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
11778 	enum uio_seg dataspace, int path_flag)
11779 {
11780 	struct sd_lun	*un;
11781 	sd_ssc_t	*ssc;
11782 	int		rval;
11783 
11784 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11785 	if (un == NULL) {
11786 		return (ENXIO);
11787 	}
11788 
11789 	/*
11790 	 * Using sd_ssc_send to handle uscsi cmd
11791 	 */
11792 	ssc = sd_ssc_init(un);
11793 	rval = sd_ssc_send(ssc, incmd, flag, dataspace, path_flag);
11794 	sd_ssc_fini(ssc);
11795 
11796 	return (rval);
11797 }
11798 
11799 /*
11800  *    Function: sd_ssc_init
11801  *
11802  * Description: Uscsi end-user call this function to initialize necessary
11803  *              fields, such as uscsi_cmd and sd_uscsi_info struct.
11804  *
11805  *              The return value of sd_send_scsi_cmd will be treated as a
11806  *              fault in various conditions. Even it is not Zero, some
11807  *              callers may ignore the return value. That is to say, we can
11808  *              not make an accurate assessment in sdintr, since if a
11809  *              command is failed in sdintr it does not mean the caller of
11810  *              sd_send_scsi_cmd will treat it as a real failure.
11811  *
11812  *              To avoid printing too many error logs for a failed uscsi
11813  *              packet that the caller may not treat it as a failure, the
11814  *              sd will keep silent for handling all uscsi commands.
11815  *
11816  *              During detach->attach and attach-open, for some types of
11817  *              problems, the driver should be providing information about
11818  *              the problem encountered. Device use USCSI_SILENT, which
11819  *              suppresses all driver information. The result is that no
11820  *              information about the problem is available. Being
11821  *              completely silent during this time is inappropriate. The
11822  *              driver needs a more selective filter than USCSI_SILENT, so
11823  *              that information related to faults is provided.
11824  *
11825  *              To make the accurate accessment, the caller  of
11826  *              sd_send_scsi_USCSI_CMD should take the ownership and
11827  *              get necessary information to print error messages.
11828  *
11829  *              If we want to print necessary info of uscsi command, we need to
11830  *              keep the uscsi_cmd and sd_uscsi_info till we can make the
11831  *              assessment. We use sd_ssc_init to alloc necessary
11832  *              structs for sending an uscsi command and we are also
11833  *              responsible for free the memory by calling
11834  *              sd_ssc_fini.
11835  *
11836  *              The calling secquences will look like:
11837  *              sd_ssc_init->
11838  *
11839  *                  ...
11840  *
11841  *                  sd_send_scsi_USCSI_CMD->
11842  *                      sd_ssc_send-> - - - sdintr
11843  *                  ...
11844  *
11845  *                  if we think the return value should be treated as a
11846  *                  failure, we make the accessment here and print out
11847  *                  necessary by retrieving uscsi_cmd and sd_uscsi_info'
11848  *
11849  *                  ...
11850  *
11851  *              sd_ssc_fini
11852  *
11853  *
11854  *   Arguments: un - pointer to driver soft state (unit) structure for this
11855  *                   target.
11856  *
11857  * Return code: sd_ssc_t - pointer to allocated sd_ssc_t struct, it contains
11858  *                         uscsi_cmd and sd_uscsi_info.
11859  *                  NULL - if can not alloc memory for sd_ssc_t struct
11860  *
11861  *     Context: Kernel Thread.
11862  */
11863 static sd_ssc_t *
11864 sd_ssc_init(struct sd_lun *un)
11865 {
11866 	sd_ssc_t		*ssc;
11867 	struct uscsi_cmd	*ucmdp;
11868 	struct sd_uscsi_info	*uip;
11869 
11870 	ASSERT(un != NULL);
11871 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11872 
11873 	/*
11874 	 * Allocate sd_ssc_t structure
11875 	 */
11876 	ssc = kmem_zalloc(sizeof (sd_ssc_t), KM_SLEEP);
11877 
11878 	/*
11879 	 * Allocate uscsi_cmd by calling scsi_uscsi_alloc common routine
11880 	 */
11881 	ucmdp = scsi_uscsi_alloc();
11882 
11883 	/*
11884 	 * Allocate sd_uscsi_info structure
11885 	 */
11886 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11887 
11888 	ssc->ssc_uscsi_cmd = ucmdp;
11889 	ssc->ssc_uscsi_info = uip;
11890 	ssc->ssc_un = un;
11891 
11892 	return (ssc);
11893 }
11894 
11895 /*
11896  * Function: sd_ssc_fini
11897  *
11898  * Description: To free sd_ssc_t and it's hanging off
11899  *
11900  * Arguments: ssc - struct pointer of sd_ssc_t.
11901  */
11902 static void
11903 sd_ssc_fini(sd_ssc_t *ssc)
11904 {
11905 	scsi_uscsi_free(ssc->ssc_uscsi_cmd);
11906 
11907 	if (ssc->ssc_uscsi_info != NULL) {
11908 		kmem_free(ssc->ssc_uscsi_info, sizeof (struct sd_uscsi_info));
11909 		ssc->ssc_uscsi_info = NULL;
11910 	}
11911 
11912 	kmem_free(ssc, sizeof (sd_ssc_t));
11913 	ssc = NULL;
11914 }
11915 
11916 /*
11917  * Function: sd_ssc_send
11918  *
11919  * Description: Runs a USCSI command for user when called through sdioctl,
11920  *              or for the driver.
11921  *
11922  *   Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11923  *                    sd_uscsi_info in.
11924  *		incmd - ptr to a valid uscsi_cmd struct
11925  *		flag - bit flag, indicating open settings, 32/64 bit type
11926  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11927  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11928  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11929  *			to use the USCSI "direct" chain and bypass the normal
11930  *			command waitq.
11931  *
11932  * Return Code: 0 -  successful completion of the given command
11933  *		EIO - scsi_uscsi_handle_command() failed
11934  *		ENXIO  - soft state not found for specified dev
11935  *		ECANCELED - command cancelled due to low power
11936  *		EINVAL
11937  *		EFAULT - copyin/copyout error
11938  *		return code of scsi_uscsi_handle_command():
11939  *			EIO
11940  *			ENXIO
11941  *			EACCES
11942  *
11943  *     Context: Kernel Thread;
11944  *              Waits for command to complete. Can sleep.
11945  */
11946 static int
11947 sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd, int flag,
11948 	enum uio_seg dataspace, int path_flag)
11949 {
11950 	struct sd_uscsi_info	*uip;
11951 	struct uscsi_cmd	*uscmd;
11952 	struct sd_lun		*un;
11953 	dev_t			dev;
11954 
11955 	int	format = 0;
11956 	int	rval;
11957 
11958 	ASSERT(ssc != NULL);
11959 	un = ssc->ssc_un;
11960 	ASSERT(un != NULL);
11961 	uscmd = ssc->ssc_uscsi_cmd;
11962 	ASSERT(uscmd != NULL);
11963 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11964 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
11965 		/*
11966 		 * If enter here, it indicates that the previous uscsi
11967 		 * command has not been processed by sd_ssc_assessment.
11968 		 * This is violating our rules of FMA telemetry processing.
11969 		 * We should print out this message and the last undisposed
11970 		 * uscsi command.
11971 		 */
11972 		if (uscmd->uscsi_cdb != NULL) {
11973 			SD_INFO(SD_LOG_SDTEST, un,
11974 			    "sd_ssc_send is missing the alternative "
11975 			    "sd_ssc_assessment when running command 0x%x.\n",
11976 			    uscmd->uscsi_cdb[0]);
11977 		}
11978 		/*
11979 		 * Set the ssc_flags to SSC_FLAGS_UNKNOWN, which should be
11980 		 * the initial status.
11981 		 */
11982 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11983 	}
11984 
11985 	/*
11986 	 * We need to make sure sd_ssc_send will have sd_ssc_assessment
11987 	 * followed to avoid missing FMA telemetries.
11988 	 */
11989 	ssc->ssc_flags |= SSC_FLAGS_NEED_ASSESSMENT;
11990 
11991 	/*
11992 	 * if USCSI_PMFAILFAST is set and un is in low power, fail the
11993 	 * command immediately.
11994 	 */
11995 	mutex_enter(SD_MUTEX(un));
11996 	mutex_enter(&un->un_pm_mutex);
11997 	if ((uscmd->uscsi_flags & USCSI_PMFAILFAST) &&
11998 	    SD_DEVICE_IS_IN_LOW_POWER(un)) {
11999 		SD_TRACE(SD_LOG_IO, un, "sd_ssc_send:"
12000 		    "un:0x%p is in low power\n", un);
12001 		mutex_exit(&un->un_pm_mutex);
12002 		mutex_exit(SD_MUTEX(un));
12003 		return (ECANCELED);
12004 	}
12005 	mutex_exit(&un->un_pm_mutex);
12006 	mutex_exit(SD_MUTEX(un));
12007 
12008 #ifdef SDDEBUG
12009 	switch (dataspace) {
12010 	case UIO_USERSPACE:
12011 		SD_TRACE(SD_LOG_IO, un,
12012 		    "sd_ssc_send: entry: un:0x%p UIO_USERSPACE\n", un);
12013 		break;
12014 	case UIO_SYSSPACE:
12015 		SD_TRACE(SD_LOG_IO, un,
12016 		    "sd_ssc_send: entry: un:0x%p UIO_SYSSPACE\n", un);
12017 		break;
12018 	default:
12019 		SD_TRACE(SD_LOG_IO, un,
12020 		    "sd_ssc_send: entry: un:0x%p UNEXPECTED SPACE\n", un);
12021 		break;
12022 	}
12023 #endif
12024 
12025 	rval = scsi_uscsi_copyin((intptr_t)incmd, flag,
12026 	    SD_ADDRESS(un), &uscmd);
12027 	if (rval != 0) {
12028 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
12029 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
12030 		return (rval);
12031 	}
12032 
12033 	if ((uscmd->uscsi_cdb != NULL) &&
12034 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
12035 		mutex_enter(SD_MUTEX(un));
12036 		un->un_f_format_in_progress = TRUE;
12037 		mutex_exit(SD_MUTEX(un));
12038 		format = 1;
12039 	}
12040 
12041 	/*
12042 	 * Allocate an sd_uscsi_info struct and fill it with the info
12043 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
12044 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
12045 	 * since we allocate the buf here in this function, we do not
12046 	 * need to preserve the prior contents of b_private.
12047 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
12048 	 */
12049 	uip = ssc->ssc_uscsi_info;
12050 	uip->ui_flags = path_flag;
12051 	uip->ui_cmdp = uscmd;
12052 
12053 	/*
12054 	 * Commands sent with priority are intended for error recovery
12055 	 * situations, and do not have retries performed.
12056 	 */
12057 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
12058 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
12059 	}
12060 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
12061 
12062 	dev = SD_GET_DEV(un);
12063 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
12064 	    sd_uscsi_strategy, NULL, uip);
12065 
12066 	/*
12067 	 * mark ssc_flags right after handle_cmd to make sure
12068 	 * the uscsi has been sent
12069 	 */
12070 	ssc->ssc_flags |= SSC_FLAGS_CMD_ISSUED;
12071 
12072 #ifdef SDDEBUG
12073 	SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
12074 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
12075 	    uscmd->uscsi_status, uscmd->uscsi_resid);
12076 	if (uscmd->uscsi_bufaddr != NULL) {
12077 		SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
12078 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
12079 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
12080 		if (dataspace == UIO_SYSSPACE) {
12081 			SD_DUMP_MEMORY(un, SD_LOG_IO,
12082 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
12083 			    uscmd->uscsi_buflen, SD_LOG_HEX);
12084 		}
12085 	}
12086 #endif
12087 
12088 	if (format == 1) {
12089 		mutex_enter(SD_MUTEX(un));
12090 		un->un_f_format_in_progress = FALSE;
12091 		mutex_exit(SD_MUTEX(un));
12092 	}
12093 
12094 	(void) scsi_uscsi_copyout((intptr_t)incmd, uscmd);
12095 
12096 	return (rval);
12097 }
12098 
12099 /*
12100  *     Function: sd_ssc_print
12101  *
12102  * Description: Print information available to the console.
12103  *
12104  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12105  *                    sd_uscsi_info in.
12106  *            sd_severity - log level.
12107  *     Context: Kernel thread or interrupt context.
12108  */
12109 static void
12110 sd_ssc_print(sd_ssc_t *ssc, int sd_severity)
12111 {
12112 	struct uscsi_cmd	*ucmdp;
12113 	struct scsi_device	*devp;
12114 	dev_info_t 		*devinfo;
12115 	uchar_t			*sensep;
12116 	int			senlen;
12117 	union scsi_cdb		*cdbp;
12118 	uchar_t			com;
12119 	extern struct scsi_key_strings scsi_cmds[];
12120 
12121 	ASSERT(ssc != NULL);
12122 	ASSERT(ssc->ssc_un != NULL);
12123 
12124 	if (SD_FM_LOG(ssc->ssc_un) != SD_FM_LOG_EREPORT)
12125 		return;
12126 	ucmdp = ssc->ssc_uscsi_cmd;
12127 	devp = SD_SCSI_DEVP(ssc->ssc_un);
12128 	devinfo = SD_DEVINFO(ssc->ssc_un);
12129 	ASSERT(ucmdp != NULL);
12130 	ASSERT(devp != NULL);
12131 	ASSERT(devinfo != NULL);
12132 	sensep = (uint8_t *)ucmdp->uscsi_rqbuf;
12133 	senlen = ucmdp->uscsi_rqlen - ucmdp->uscsi_rqresid;
12134 	cdbp = (union scsi_cdb *)ucmdp->uscsi_cdb;
12135 
12136 	/* In certain case (like DOORLOCK), the cdb could be NULL. */
12137 	if (cdbp == NULL)
12138 		return;
12139 	/* We don't print log if no sense data available. */
12140 	if (senlen == 0)
12141 		sensep = NULL;
12142 	com = cdbp->scc_cmd;
12143 	scsi_generic_errmsg(devp, sd_label, sd_severity, 0, 0, com,
12144 	    scsi_cmds, sensep, ssc->ssc_un->un_additional_codes, NULL);
12145 }
12146 
12147 /*
12148  *     Function: sd_ssc_assessment
12149  *
12150  * Description: We use this function to make an assessment at the point
12151  *              where SD driver may encounter a potential error.
12152  *
12153  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12154  *                  sd_uscsi_info in.
12155  *            tp_assess - a hint of strategy for ereport posting.
12156  *            Possible values of tp_assess include:
12157  *                SD_FMT_IGNORE - we don't post any ereport because we're
12158  *                sure that it is ok to ignore the underlying problems.
12159  *                SD_FMT_IGNORE_COMPROMISE - we don't post any ereport for now
12160  *                but it might be not correct to ignore the underlying hardware
12161  *                error.
12162  *                SD_FMT_STATUS_CHECK - we will post an ereport with the
12163  *                payload driver-assessment of value "fail" or
12164  *                "fatal"(depending on what information we have here). This
12165  *                assessment value is usually set when SD driver think there
12166  *                is a potential error occurred(Typically, when return value
12167  *                of the SCSI command is EIO).
12168  *                SD_FMT_STANDARD - we will post an ereport with the payload
12169  *                driver-assessment of value "info". This assessment value is
12170  *                set when the SCSI command returned successfully and with
12171  *                sense data sent back.
12172  *
12173  *     Context: Kernel thread.
12174  */
12175 static void
12176 sd_ssc_assessment(sd_ssc_t *ssc, enum sd_type_assessment tp_assess)
12177 {
12178 	int senlen = 0;
12179 	struct uscsi_cmd *ucmdp = NULL;
12180 	struct sd_lun *un;
12181 
12182 	ASSERT(ssc != NULL);
12183 	un = ssc->ssc_un;
12184 	ASSERT(un != NULL);
12185 	ucmdp = ssc->ssc_uscsi_cmd;
12186 	ASSERT(ucmdp != NULL);
12187 
12188 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
12189 		ssc->ssc_flags &= ~SSC_FLAGS_NEED_ASSESSMENT;
12190 	} else {
12191 		/*
12192 		 * If enter here, it indicates that we have a wrong
12193 		 * calling sequence of sd_ssc_send and sd_ssc_assessment,
12194 		 * both of which should be called in a pair in case of
12195 		 * loss of FMA telemetries.
12196 		 */
12197 		if (ucmdp->uscsi_cdb != NULL) {
12198 			SD_INFO(SD_LOG_SDTEST, un,
12199 			    "sd_ssc_assessment is missing the "
12200 			    "alternative sd_ssc_send when running 0x%x, "
12201 			    "or there are superfluous sd_ssc_assessment for "
12202 			    "the same sd_ssc_send.\n",
12203 			    ucmdp->uscsi_cdb[0]);
12204 		}
12205 		/*
12206 		 * Set the ssc_flags to the initial value to avoid passing
12207 		 * down dirty flags to the following sd_ssc_send function.
12208 		 */
12209 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12210 		return;
12211 	}
12212 
12213 	/*
12214 	 * Only handle an issued command which is waiting for assessment.
12215 	 * A command which is not issued will not have
12216 	 * SSC_FLAGS_INVALID_DATA set, so it'ok we just return here.
12217 	 */
12218 	if (!(ssc->ssc_flags & SSC_FLAGS_CMD_ISSUED)) {
12219 		sd_ssc_print(ssc, SCSI_ERR_INFO);
12220 		return;
12221 	} else {
12222 		/*
12223 		 * For an issued command, we should clear this flag in
12224 		 * order to make the sd_ssc_t structure be used off
12225 		 * multiple uscsi commands.
12226 		 */
12227 		ssc->ssc_flags &= ~SSC_FLAGS_CMD_ISSUED;
12228 	}
12229 
12230 	/*
12231 	 * We will not deal with non-retryable(flag USCSI_DIAGNOSE set)
12232 	 * commands here. And we should clear the ssc_flags before return.
12233 	 */
12234 	if (ucmdp->uscsi_flags & USCSI_DIAGNOSE) {
12235 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12236 		return;
12237 	}
12238 
12239 	switch (tp_assess) {
12240 	case SD_FMT_IGNORE:
12241 	case SD_FMT_IGNORE_COMPROMISE:
12242 		break;
12243 	case SD_FMT_STATUS_CHECK:
12244 		/*
12245 		 * For a failed command(including the succeeded command
12246 		 * with invalid data sent back).
12247 		 */
12248 		sd_ssc_post(ssc, SD_FM_DRV_FATAL);
12249 		break;
12250 	case SD_FMT_STANDARD:
12251 		/*
12252 		 * Always for the succeeded commands probably with sense
12253 		 * data sent back.
12254 		 * Limitation:
12255 		 *	We can only handle a succeeded command with sense
12256 		 *	data sent back when auto-request-sense is enabled.
12257 		 */
12258 		senlen = ssc->ssc_uscsi_cmd->uscsi_rqlen -
12259 		    ssc->ssc_uscsi_cmd->uscsi_rqresid;
12260 		if ((ssc->ssc_uscsi_info->ui_pkt_state & STATE_ARQ_DONE) &&
12261 		    (un->un_f_arq_enabled == TRUE) &&
12262 		    senlen > 0 &&
12263 		    ssc->ssc_uscsi_cmd->uscsi_rqbuf != NULL) {
12264 			sd_ssc_post(ssc, SD_FM_DRV_NOTICE);
12265 		}
12266 		break;
12267 	default:
12268 		/*
12269 		 * Should not have other type of assessment.
12270 		 */
12271 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
12272 		    "sd_ssc_assessment got wrong "
12273 		    "sd_type_assessment %d.\n", tp_assess);
12274 		break;
12275 	}
12276 	/*
12277 	 * Clear up the ssc_flags before return.
12278 	 */
12279 	ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12280 }
12281 
12282 /*
12283  *    Function: sd_ssc_post
12284  *
12285  * Description: 1. read the driver property to get fm-scsi-log flag.
12286  *              2. print log if fm_log_capable is non-zero.
12287  *              3. call sd_ssc_ereport_post to post ereport if possible.
12288  *
12289  *    Context: May be called from kernel thread or interrupt context.
12290  */
12291 static void
12292 sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess)
12293 {
12294 	struct sd_lun	*un;
12295 	int		sd_severity;
12296 
12297 	ASSERT(ssc != NULL);
12298 	un = ssc->ssc_un;
12299 	ASSERT(un != NULL);
12300 
12301 	/*
12302 	 * We may enter here from sd_ssc_assessment(for USCSI command) or
12303 	 * by directly called from sdintr context.
12304 	 * We don't handle a non-disk drive(CD-ROM, removable media).
12305 	 * Clear the ssc_flags before return in case we've set
12306 	 * SSC_FLAGS_INVALID_XXX which should be skipped for a non-disk
12307 	 * driver.
12308 	 */
12309 	if (ISCD(un) || un->un_f_has_removable_media) {
12310 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12311 		return;
12312 	}
12313 
12314 	switch (sd_assess) {
12315 		case SD_FM_DRV_FATAL:
12316 			sd_severity = SCSI_ERR_FATAL;
12317 			break;
12318 		case SD_FM_DRV_RECOVERY:
12319 			sd_severity = SCSI_ERR_RECOVERED;
12320 			break;
12321 		case SD_FM_DRV_RETRY:
12322 			sd_severity = SCSI_ERR_RETRYABLE;
12323 			break;
12324 		case SD_FM_DRV_NOTICE:
12325 			sd_severity = SCSI_ERR_INFO;
12326 			break;
12327 		default:
12328 			sd_severity = SCSI_ERR_UNKNOWN;
12329 	}
12330 	/* print log */
12331 	sd_ssc_print(ssc, sd_severity);
12332 
12333 	/* always post ereport */
12334 	sd_ssc_ereport_post(ssc, sd_assess);
12335 }
12336 
12337 /*
12338  *    Function: sd_ssc_set_info
12339  *
12340  * Description: Mark ssc_flags and set ssc_info which would be the
12341  *              payload of uderr ereport. This function will cause
12342  *              sd_ssc_ereport_post to post uderr ereport only.
12343  *              Besides, when ssc_flags == SSC_FLAGS_INVALID_DATA(USCSI),
12344  *              the function will also call SD_ERROR or scsi_log for a
12345  *              CDROM/removable-media/DDI_FM_NOT_CAPABLE device.
12346  *
12347  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12348  *                  sd_uscsi_info in.
12349  *            ssc_flags - indicate the sub-category of a uderr.
12350  *            comp - this argument is meaningful only when
12351  *                   ssc_flags == SSC_FLAGS_INVALID_DATA, and its possible
12352  *                   values include:
12353  *                   > 0, SD_ERROR is used with comp as the driver logging
12354  *                   component;
12355  *                   = 0, scsi-log is used to log error telemetries;
12356  *                   < 0, no log available for this telemetry.
12357  *
12358  *    Context: Kernel thread or interrupt context
12359  */
12360 static void
12361 sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp, const char *fmt, ...)
12362 {
12363 	va_list	ap;
12364 
12365 	ASSERT(ssc != NULL);
12366 	ASSERT(ssc->ssc_un != NULL);
12367 
12368 	ssc->ssc_flags |= ssc_flags;
12369 	va_start(ap, fmt);
12370 	(void) vsnprintf(ssc->ssc_info, sizeof (ssc->ssc_info), fmt, ap);
12371 	va_end(ap);
12372 
12373 	/*
12374 	 * If SSC_FLAGS_INVALID_DATA is set, it should be a uscsi command
12375 	 * with invalid data sent back. For non-uscsi command, the
12376 	 * following code will be bypassed.
12377 	 */
12378 	if (ssc_flags & SSC_FLAGS_INVALID_DATA) {
12379 		if (SD_FM_LOG(ssc->ssc_un) == SD_FM_LOG_NSUP) {
12380 			/*
12381 			 * If the error belong to certain component and we
12382 			 * do not want it to show up on the console, we
12383 			 * will use SD_ERROR, otherwise scsi_log is
12384 			 * preferred.
12385 			 */
12386 			if (comp > 0) {
12387 				SD_ERROR(comp, ssc->ssc_un, ssc->ssc_info);
12388 			} else if (comp == 0) {
12389 				scsi_log(SD_DEVINFO(ssc->ssc_un), sd_label,
12390 				    CE_WARN, ssc->ssc_info);
12391 			}
12392 		}
12393 	}
12394 }
12395 
12396 /*
12397  *    Function: sd_buf_iodone
12398  *
12399  * Description: Frees the sd_xbuf & returns the buf to its originator.
12400  *
12401  *     Context: May be called from interrupt context.
12402  */
12403 /* ARGSUSED */
12404 static void
12405 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
12406 {
12407 	struct sd_xbuf *xp;
12408 
12409 	ASSERT(un != NULL);
12410 	ASSERT(bp != NULL);
12411 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12412 
12413 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
12414 
12415 	xp = SD_GET_XBUF(bp);
12416 	ASSERT(xp != NULL);
12417 
12418 	/* xbuf is gone after this */
12419 	if (ddi_xbuf_done(bp, un->un_xbuf_attr)) {
12420 		mutex_enter(SD_MUTEX(un));
12421 
12422 		/*
12423 		 * Grab time when the cmd completed.
12424 		 * This is used for determining if the system has been
12425 		 * idle long enough to make it idle to the PM framework.
12426 		 * This is for lowering the overhead, and therefore improving
12427 		 * performance per I/O operation.
12428 		 */
12429 		un->un_pm_idle_time = ddi_get_time();
12430 
12431 		un->un_ncmds_in_driver--;
12432 		ASSERT(un->un_ncmds_in_driver >= 0);
12433 		SD_INFO(SD_LOG_IO, un,
12434 		    "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
12435 		    un->un_ncmds_in_driver);
12436 
12437 		mutex_exit(SD_MUTEX(un));
12438 	}
12439 
12440 	biodone(bp);				/* bp is gone after this */
12441 
12442 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
12443 }
12444 
12445 
12446 /*
12447  *    Function: sd_uscsi_iodone
12448  *
12449  * Description: Frees the sd_xbuf & returns the buf to its originator.
12450  *
12451  *     Context: May be called from interrupt context.
12452  */
12453 /* ARGSUSED */
12454 static void
12455 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12456 {
12457 	struct sd_xbuf *xp;
12458 
12459 	ASSERT(un != NULL);
12460 	ASSERT(bp != NULL);
12461 
12462 	xp = SD_GET_XBUF(bp);
12463 	ASSERT(xp != NULL);
12464 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12465 
12466 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
12467 
12468 	bp->b_private = xp->xb_private;
12469 
12470 	mutex_enter(SD_MUTEX(un));
12471 
12472 	/*
12473 	 * Grab time when the cmd completed.
12474 	 * This is used for determining if the system has been
12475 	 * idle long enough to make it idle to the PM framework.
12476 	 * This is for lowering the overhead, and therefore improving
12477 	 * performance per I/O operation.
12478 	 */
12479 	un->un_pm_idle_time = ddi_get_time();
12480 
12481 	un->un_ncmds_in_driver--;
12482 	ASSERT(un->un_ncmds_in_driver >= 0);
12483 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
12484 	    un->un_ncmds_in_driver);
12485 
12486 	mutex_exit(SD_MUTEX(un));
12487 
12488 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
12489 	    SENSE_LENGTH) {
12490 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
12491 		    MAX_SENSE_LENGTH);
12492 	} else {
12493 		kmem_free(xp, sizeof (struct sd_xbuf));
12494 	}
12495 
12496 	biodone(bp);
12497 
12498 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
12499 }
12500 
12501 
12502 /*
12503  *    Function: sd_mapblockaddr_iostart
12504  *
12505  * Description: Verify request lies within the partition limits for
12506  *		the indicated minor device.  Issue "overrun" buf if
12507  *		request would exceed partition range.  Converts
12508  *		partition-relative block address to absolute.
12509  *
12510  *              Upon exit of this function:
12511  *              1.I/O is aligned
12512  *                 xp->xb_blkno represents the absolute sector address
12513  *              2.I/O is misaligned
12514  *                 xp->xb_blkno represents the absolute logical block address
12515  *                 based on DEV_BSIZE. The logical block address will be
12516  *                 converted to physical sector address in sd_mapblocksize_\
12517  *                 iostart.
12518  *              3.I/O is misaligned but is aligned in "overrun" buf
12519  *                 xp->xb_blkno represents the absolute logical block address
12520  *                 based on DEV_BSIZE. The logical block address will be
12521  *                 converted to physical sector address in sd_mapblocksize_\
12522  *                 iostart. But no RMW will be issued in this case.
12523  *
12524  *     Context: Can sleep
12525  *
12526  *      Issues: This follows what the old code did, in terms of accessing
12527  *		some of the partition info in the unit struct without holding
12528  *		the mutext.  This is a general issue, if the partition info
12529  *		can be altered while IO is in progress... as soon as we send
12530  *		a buf, its partitioning can be invalid before it gets to the
12531  *		device.  Probably the right fix is to move partitioning out
12532  *		of the driver entirely.
12533  */
12534 
12535 static void
12536 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
12537 {
12538 	diskaddr_t	nblocks;	/* #blocks in the given partition */
12539 	daddr_t	blocknum;	/* Block number specified by the buf */
12540 	size_t	requested_nblocks;
12541 	size_t	available_nblocks;
12542 	int	partition;
12543 	diskaddr_t	partition_offset;
12544 	struct sd_xbuf *xp;
12545 	int secmask = 0, blknomask = 0;
12546 	ushort_t is_aligned = TRUE;
12547 
12548 	ASSERT(un != NULL);
12549 	ASSERT(bp != NULL);
12550 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12551 
12552 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12553 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
12554 
12555 	xp = SD_GET_XBUF(bp);
12556 	ASSERT(xp != NULL);
12557 
12558 	/*
12559 	 * If the geometry is not indicated as valid, attempt to access
12560 	 * the unit & verify the geometry/label. This can be the case for
12561 	 * removable-media devices, of if the device was opened in
12562 	 * NDELAY/NONBLOCK mode.
12563 	 */
12564 	partition = SDPART(bp->b_edev);
12565 
12566 	if (!SD_IS_VALID_LABEL(un)) {
12567 		sd_ssc_t *ssc;
12568 		/*
12569 		 * Initialize sd_ssc_t for internal uscsi commands
12570 		 * In case of potential porformance issue, we need
12571 		 * to alloc memory only if there is invalid label
12572 		 */
12573 		ssc = sd_ssc_init(un);
12574 
12575 		if (sd_ready_and_valid(ssc, partition) != SD_READY_VALID) {
12576 			/*
12577 			 * For removable devices it is possible to start an
12578 			 * I/O without a media by opening the device in nodelay
12579 			 * mode. Also for writable CDs there can be many
12580 			 * scenarios where there is no geometry yet but volume
12581 			 * manager is trying to issue a read() just because
12582 			 * it can see TOC on the CD. So do not print a message
12583 			 * for removables.
12584 			 */
12585 			if (!un->un_f_has_removable_media) {
12586 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12587 				    "i/o to invalid geometry\n");
12588 			}
12589 			bioerror(bp, EIO);
12590 			bp->b_resid = bp->b_bcount;
12591 			SD_BEGIN_IODONE(index, un, bp);
12592 
12593 			sd_ssc_fini(ssc);
12594 			return;
12595 		}
12596 		sd_ssc_fini(ssc);
12597 	}
12598 
12599 	nblocks = 0;
12600 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
12601 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
12602 
12603 	if (un->un_f_enable_rmw) {
12604 		blknomask = (un->un_phy_blocksize / DEV_BSIZE) - 1;
12605 		secmask = un->un_phy_blocksize - 1;
12606 	} else {
12607 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
12608 		secmask = un->un_tgt_blocksize - 1;
12609 	}
12610 
12611 	if ((bp->b_lblkno & (blknomask)) || (bp->b_bcount & (secmask))) {
12612 		is_aligned = FALSE;
12613 	}
12614 
12615 	if (!(NOT_DEVBSIZE(un)) || un->un_f_enable_rmw) {
12616 		/*
12617 		 * If I/O is aligned, no need to involve RMW(Read Modify Write)
12618 		 * Convert the logical block number to target's physical sector
12619 		 * number.
12620 		 */
12621 		if (is_aligned) {
12622 			xp->xb_blkno = SD_SYS2TGTBLOCK(un, xp->xb_blkno);
12623 		} else {
12624 			switch (un->un_f_rmw_type) {
12625 			case SD_RMW_TYPE_RETURN_ERROR:
12626 				if (un->un_f_enable_rmw)
12627 					break;
12628 				else {
12629 					bp->b_flags |= B_ERROR;
12630 					goto error_exit;
12631 				}
12632 
12633 			case SD_RMW_TYPE_DEFAULT:
12634 				mutex_enter(SD_MUTEX(un));
12635 				if (!un->un_f_enable_rmw &&
12636 				    un->un_rmw_msg_timeid == NULL) {
12637 					scsi_log(SD_DEVINFO(un), sd_label,
12638 					    CE_WARN, "I/O request is not "
12639 					    "aligned with %d disk sector size. "
12640 					    "It is handled through Read Modify "
12641 					    "Write but the performance is "
12642 					    "very low.\n",
12643 					    un->un_tgt_blocksize);
12644 					un->un_rmw_msg_timeid =
12645 					    timeout(sd_rmw_msg_print_handler,
12646 					    un, SD_RMW_MSG_PRINT_TIMEOUT);
12647 				} else {
12648 					un->un_rmw_incre_count ++;
12649 				}
12650 				mutex_exit(SD_MUTEX(un));
12651 				break;
12652 
12653 			case SD_RMW_TYPE_NO_WARNING:
12654 			default:
12655 				break;
12656 			}
12657 
12658 			nblocks = SD_TGT2SYSBLOCK(un, nblocks);
12659 			partition_offset = SD_TGT2SYSBLOCK(un,
12660 			    partition_offset);
12661 		}
12662 	}
12663 
12664 	/*
12665 	 * blocknum is the starting block number of the request. At this
12666 	 * point it is still relative to the start of the minor device.
12667 	 */
12668 	blocknum = xp->xb_blkno;
12669 
12670 	/*
12671 	 * Legacy: If the starting block number is one past the last block
12672 	 * in the partition, do not set B_ERROR in the buf.
12673 	 */
12674 	if (blocknum == nblocks)  {
12675 		goto error_exit;
12676 	}
12677 
12678 	/*
12679 	 * Confirm that the first block of the request lies within the
12680 	 * partition limits. Also the requested number of bytes must be
12681 	 * a multiple of the system block size.
12682 	 */
12683 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12684 	    ((bp->b_bcount & (DEV_BSIZE - 1)) != 0)) {
12685 		bp->b_flags |= B_ERROR;
12686 		goto error_exit;
12687 	}
12688 
12689 	/*
12690 	 * If the requsted # blocks exceeds the available # blocks, that
12691 	 * is an overrun of the partition.
12692 	 */
12693 	if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12694 		requested_nblocks = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
12695 	} else {
12696 		requested_nblocks = SD_BYTES2SYSBLOCKS(bp->b_bcount);
12697 	}
12698 
12699 	available_nblocks = (size_t)(nblocks - blocknum);
12700 	ASSERT(nblocks >= blocknum);
12701 
12702 	if (requested_nblocks > available_nblocks) {
12703 		size_t resid;
12704 
12705 		/*
12706 		 * Allocate an "overrun" buf to allow the request to proceed
12707 		 * for the amount of space available in the partition. The
12708 		 * amount not transferred will be added into the b_resid
12709 		 * when the operation is complete. The overrun buf
12710 		 * replaces the original buf here, and the original buf
12711 		 * is saved inside the overrun buf, for later use.
12712 		 */
12713 		if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12714 			resid = SD_TGTBLOCKS2BYTES(un,
12715 			    (offset_t)(requested_nblocks - available_nblocks));
12716 		} else {
12717 			resid = SD_SYSBLOCKS2BYTES(
12718 			    (offset_t)(requested_nblocks - available_nblocks));
12719 		}
12720 
12721 		size_t count = bp->b_bcount - resid;
12722 		/*
12723 		 * Note: count is an unsigned entity thus it'll NEVER
12724 		 * be less than 0 so ASSERT the original values are
12725 		 * correct.
12726 		 */
12727 		ASSERT(bp->b_bcount >= resid);
12728 
12729 		bp = sd_bioclone_alloc(bp, count, blocknum,
12730 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
12731 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12732 		ASSERT(xp != NULL);
12733 	}
12734 
12735 	/* At this point there should be no residual for this buf. */
12736 	ASSERT(bp->b_resid == 0);
12737 
12738 	/* Convert the block number to an absolute address. */
12739 	xp->xb_blkno += partition_offset;
12740 
12741 	SD_NEXT_IOSTART(index, un, bp);
12742 
12743 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12744 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12745 
12746 	return;
12747 
12748 error_exit:
12749 	bp->b_resid = bp->b_bcount;
12750 	SD_BEGIN_IODONE(index, un, bp);
12751 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12752 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12753 }
12754 
12755 
12756 /*
12757  *    Function: sd_mapblockaddr_iodone
12758  *
12759  * Description: Completion-side processing for partition management.
12760  *
12761  *     Context: May be called under interrupt context
12762  */
12763 
12764 static void
12765 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12766 {
12767 	/* int	partition; */	/* Not used, see below. */
12768 	ASSERT(un != NULL);
12769 	ASSERT(bp != NULL);
12770 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12771 
12772 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12773 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12774 
12775 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
12776 		/*
12777 		 * We have an "overrun" buf to deal with...
12778 		 */
12779 		struct sd_xbuf	*xp;
12780 		struct buf	*obp;	/* ptr to the original buf */
12781 
12782 		xp = SD_GET_XBUF(bp);
12783 		ASSERT(xp != NULL);
12784 
12785 		/* Retrieve the pointer to the original buf */
12786 		obp = (struct buf *)xp->xb_private;
12787 		ASSERT(obp != NULL);
12788 
12789 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12790 		bioerror(obp, bp->b_error);
12791 
12792 		sd_bioclone_free(bp);
12793 
12794 		/*
12795 		 * Get back the original buf.
12796 		 * Note that since the restoration of xb_blkno below
12797 		 * was removed, the sd_xbuf is not needed.
12798 		 */
12799 		bp = obp;
12800 		/*
12801 		 * xp = SD_GET_XBUF(bp);
12802 		 * ASSERT(xp != NULL);
12803 		 */
12804 	}
12805 
12806 	/*
12807 	 * Convert sd->xb_blkno back to a minor-device relative value.
12808 	 * Note: this has been commented out, as it is not needed in the
12809 	 * current implementation of the driver (ie, since this function
12810 	 * is at the top of the layering chains, so the info will be
12811 	 * discarded) and it is in the "hot" IO path.
12812 	 *
12813 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12814 	 * xp->xb_blkno -= un->un_offset[partition];
12815 	 */
12816 
12817 	SD_NEXT_IODONE(index, un, bp);
12818 
12819 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12820 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12821 }
12822 
12823 
12824 /*
12825  *    Function: sd_mapblocksize_iostart
12826  *
12827  * Description: Convert between system block size (un->un_sys_blocksize)
12828  *		and target block size (un->un_tgt_blocksize).
12829  *
12830  *     Context: Can sleep to allocate resources.
12831  *
12832  * Assumptions: A higher layer has already performed any partition validation,
12833  *		and converted the xp->xb_blkno to an absolute value relative
12834  *		to the start of the device.
12835  *
12836  *		It is also assumed that the higher layer has implemented
12837  *		an "overrun" mechanism for the case where the request would
12838  *		read/write beyond the end of a partition.  In this case we
12839  *		assume (and ASSERT) that bp->b_resid == 0.
12840  *
12841  *		Note: The implementation for this routine assumes the target
12842  *		block size remains constant between allocation and transport.
12843  */
12844 
12845 static void
12846 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12847 {
12848 	struct sd_mapblocksize_info	*bsp;
12849 	struct sd_xbuf			*xp;
12850 	offset_t first_byte;
12851 	daddr_t	start_block, end_block;
12852 	daddr_t	request_bytes;
12853 	ushort_t is_aligned = FALSE;
12854 
12855 	ASSERT(un != NULL);
12856 	ASSERT(bp != NULL);
12857 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12858 	ASSERT(bp->b_resid == 0);
12859 
12860 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12861 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12862 
12863 	/*
12864 	 * For a non-writable CD, a write request is an error
12865 	 */
12866 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12867 	    (un->un_f_mmc_writable_media == FALSE)) {
12868 		bioerror(bp, EIO);
12869 		bp->b_resid = bp->b_bcount;
12870 		SD_BEGIN_IODONE(index, un, bp);
12871 		return;
12872 	}
12873 
12874 	/*
12875 	 * We do not need a shadow buf if the device is using
12876 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12877 	 * In this case there is no layer-private data block allocated.
12878 	 */
12879 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
12880 	    (bp->b_bcount == 0)) {
12881 		goto done;
12882 	}
12883 
12884 #if defined(__i386) || defined(__amd64)
12885 	/* We do not support non-block-aligned transfers for ROD devices */
12886 	ASSERT(!ISROD(un));
12887 #endif
12888 
12889 	xp = SD_GET_XBUF(bp);
12890 	ASSERT(xp != NULL);
12891 
12892 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12893 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12894 	    un->un_tgt_blocksize, DEV_BSIZE);
12895 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12896 	    "request start block:0x%x\n", xp->xb_blkno);
12897 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12898 	    "request len:0x%x\n", bp->b_bcount);
12899 
12900 	/*
12901 	 * Allocate the layer-private data area for the mapblocksize layer.
12902 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12903 	 * struct to store the pointer to their layer-private data block, but
12904 	 * each layer also has the responsibility of restoring the prior
12905 	 * contents of xb_private before returning the buf/xbuf to the
12906 	 * higher layer that sent it.
12907 	 *
12908 	 * Here we save the prior contents of xp->xb_private into the
12909 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12910 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12911 	 * the layer-private area and returning the buf/xbuf to the layer
12912 	 * that sent it.
12913 	 *
12914 	 * Note that here we use kmem_zalloc for the allocation as there are
12915 	 * parts of the mapblocksize code that expect certain fields to be
12916 	 * zero unless explicitly set to a required value.
12917 	 */
12918 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12919 	bsp->mbs_oprivate = xp->xb_private;
12920 	xp->xb_private = bsp;
12921 
12922 	/*
12923 	 * This treats the data on the disk (target) as an array of bytes.
12924 	 * first_byte is the byte offset, from the beginning of the device,
12925 	 * to the location of the request. This is converted from a
12926 	 * un->un_sys_blocksize block address to a byte offset, and then back
12927 	 * to a block address based upon a un->un_tgt_blocksize block size.
12928 	 *
12929 	 * xp->xb_blkno should be absolute upon entry into this function,
12930 	 * but, but it is based upon partitions that use the "system"
12931 	 * block size. It must be adjusted to reflect the block size of
12932 	 * the target.
12933 	 *
12934 	 * Note that end_block is actually the block that follows the last
12935 	 * block of the request, but that's what is needed for the computation.
12936 	 */
12937 	first_byte  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
12938 	if (un->un_f_enable_rmw) {
12939 		start_block = xp->xb_blkno =
12940 		    (first_byte / un->un_phy_blocksize) *
12941 		    (un->un_phy_blocksize / DEV_BSIZE);
12942 		end_block   = ((first_byte + bp->b_bcount +
12943 		    un->un_phy_blocksize - 1) / un->un_phy_blocksize) *
12944 		    (un->un_phy_blocksize / DEV_BSIZE);
12945 	} else {
12946 		start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
12947 		end_block   = (first_byte + bp->b_bcount +
12948 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
12949 	}
12950 
12951 	/* request_bytes is rounded up to a multiple of the target block size */
12952 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
12953 
12954 	/*
12955 	 * See if the starting address of the request and the request
12956 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
12957 	 * then we do not need to allocate a shadow buf to handle the request.
12958 	 */
12959 	if (un->un_f_enable_rmw) {
12960 		if (((first_byte % un->un_phy_blocksize) == 0) &&
12961 		    ((bp->b_bcount % un->un_phy_blocksize) == 0)) {
12962 			is_aligned = TRUE;
12963 		}
12964 	} else {
12965 		if (((first_byte % un->un_tgt_blocksize) == 0) &&
12966 		    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
12967 			is_aligned = TRUE;
12968 		}
12969 	}
12970 
12971 	if ((bp->b_flags & B_READ) == 0) {
12972 		/*
12973 		 * Lock the range for a write operation. An aligned request is
12974 		 * considered a simple write; otherwise the request must be a
12975 		 * read-modify-write.
12976 		 */
12977 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
12978 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
12979 	}
12980 
12981 	/*
12982 	 * Alloc a shadow buf if the request is not aligned. Also, this is
12983 	 * where the READ command is generated for a read-modify-write. (The
12984 	 * write phase is deferred until after the read completes.)
12985 	 */
12986 	if (is_aligned == FALSE) {
12987 
12988 		struct sd_mapblocksize_info	*shadow_bsp;
12989 		struct sd_xbuf	*shadow_xp;
12990 		struct buf	*shadow_bp;
12991 
12992 		/*
12993 		 * Allocate the shadow buf and it associated xbuf. Note that
12994 		 * after this call the xb_blkno value in both the original
12995 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
12996 		 * same: absolute relative to the start of the device, and
12997 		 * adjusted for the target block size. The b_blkno in the
12998 		 * shadow buf will also be set to this value. We should never
12999 		 * change b_blkno in the original bp however.
13000 		 *
13001 		 * Note also that the shadow buf will always need to be a
13002 		 * READ command, regardless of whether the incoming command
13003 		 * is a READ or a WRITE.
13004 		 */
13005 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
13006 		    xp->xb_blkno,
13007 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
13008 
13009 		shadow_xp = SD_GET_XBUF(shadow_bp);
13010 
13011 		/*
13012 		 * Allocate the layer-private data for the shadow buf.
13013 		 * (No need to preserve xb_private in the shadow xbuf.)
13014 		 */
13015 		shadow_xp->xb_private = shadow_bsp =
13016 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
13017 
13018 		/*
13019 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
13020 		 * to figure out where the start of the user data is (based upon
13021 		 * the system block size) in the data returned by the READ
13022 		 * command (which will be based upon the target blocksize). Note
13023 		 * that this is only really used if the request is unaligned.
13024 		 */
13025 		if (un->un_f_enable_rmw) {
13026 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
13027 			    ((offset_t)xp->xb_blkno * un->un_sys_blocksize));
13028 			ASSERT((bsp->mbs_copy_offset >= 0) &&
13029 			    (bsp->mbs_copy_offset < un->un_phy_blocksize));
13030 		} else {
13031 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
13032 			    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
13033 			ASSERT((bsp->mbs_copy_offset >= 0) &&
13034 			    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
13035 		}
13036 
13037 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
13038 
13039 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
13040 
13041 		/* Transfer the wmap (if any) to the shadow buf */
13042 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
13043 		bsp->mbs_wmp = NULL;
13044 
13045 		/*
13046 		 * The shadow buf goes on from here in place of the
13047 		 * original buf.
13048 		 */
13049 		shadow_bsp->mbs_orig_bp = bp;
13050 		bp = shadow_bp;
13051 	}
13052 
13053 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
13054 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
13055 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
13056 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
13057 	    request_bytes);
13058 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
13059 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
13060 
13061 done:
13062 	SD_NEXT_IOSTART(index, un, bp);
13063 
13064 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
13065 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
13066 }
13067 
13068 
13069 /*
13070  *    Function: sd_mapblocksize_iodone
13071  *
13072  * Description: Completion side processing for block-size mapping.
13073  *
13074  *     Context: May be called under interrupt context
13075  */
13076 
13077 static void
13078 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
13079 {
13080 	struct sd_mapblocksize_info	*bsp;
13081 	struct sd_xbuf	*xp;
13082 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
13083 	struct buf	*orig_bp;	/* ptr to the original buf */
13084 	offset_t	shadow_end;
13085 	offset_t	request_end;
13086 	offset_t	shadow_start;
13087 	ssize_t		copy_offset;
13088 	size_t		copy_length;
13089 	size_t		shortfall;
13090 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
13091 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
13092 
13093 	ASSERT(un != NULL);
13094 	ASSERT(bp != NULL);
13095 
13096 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
13097 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
13098 
13099 	/*
13100 	 * There is no shadow buf or layer-private data if the target is
13101 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
13102 	 */
13103 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
13104 	    (bp->b_bcount == 0)) {
13105 		goto exit;
13106 	}
13107 
13108 	xp = SD_GET_XBUF(bp);
13109 	ASSERT(xp != NULL);
13110 
13111 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
13112 	bsp = xp->xb_private;
13113 
13114 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
13115 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
13116 
13117 	if (is_write) {
13118 		/*
13119 		 * For a WRITE request we must free up the block range that
13120 		 * we have locked up.  This holds regardless of whether this is
13121 		 * an aligned write request or a read-modify-write request.
13122 		 */
13123 		sd_range_unlock(un, bsp->mbs_wmp);
13124 		bsp->mbs_wmp = NULL;
13125 	}
13126 
13127 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
13128 		/*
13129 		 * An aligned read or write command will have no shadow buf;
13130 		 * there is not much else to do with it.
13131 		 */
13132 		goto done;
13133 	}
13134 
13135 	orig_bp = bsp->mbs_orig_bp;
13136 	ASSERT(orig_bp != NULL);
13137 	orig_xp = SD_GET_XBUF(orig_bp);
13138 	ASSERT(orig_xp != NULL);
13139 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13140 
13141 	if (!is_write && has_wmap) {
13142 		/*
13143 		 * A READ with a wmap means this is the READ phase of a
13144 		 * read-modify-write. If an error occurred on the READ then
13145 		 * we do not proceed with the WRITE phase or copy any data.
13146 		 * Just release the write maps and return with an error.
13147 		 */
13148 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
13149 			orig_bp->b_resid = orig_bp->b_bcount;
13150 			bioerror(orig_bp, bp->b_error);
13151 			sd_range_unlock(un, bsp->mbs_wmp);
13152 			goto freebuf_done;
13153 		}
13154 	}
13155 
13156 	/*
13157 	 * Here is where we set up to copy the data from the shadow buf
13158 	 * into the space associated with the original buf.
13159 	 *
13160 	 * To deal with the conversion between block sizes, these
13161 	 * computations treat the data as an array of bytes, with the
13162 	 * first byte (byte 0) corresponding to the first byte in the
13163 	 * first block on the disk.
13164 	 */
13165 
13166 	/*
13167 	 * shadow_start and shadow_len indicate the location and size of
13168 	 * the data returned with the shadow IO request.
13169 	 */
13170 	if (un->un_f_enable_rmw) {
13171 		shadow_start  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
13172 	} else {
13173 		shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
13174 	}
13175 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
13176 
13177 	/*
13178 	 * copy_offset gives the offset (in bytes) from the start of the first
13179 	 * block of the READ request to the beginning of the data.  We retrieve
13180 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
13181 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
13182 	 * data to be copied (in bytes).
13183 	 */
13184 	copy_offset  = bsp->mbs_copy_offset;
13185 	if (un->un_f_enable_rmw) {
13186 		ASSERT((copy_offset >= 0) &&
13187 		    (copy_offset < un->un_phy_blocksize));
13188 	} else {
13189 		ASSERT((copy_offset >= 0) &&
13190 		    (copy_offset < un->un_tgt_blocksize));
13191 	}
13192 
13193 	copy_length  = orig_bp->b_bcount;
13194 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
13195 
13196 	/*
13197 	 * Set up the resid and error fields of orig_bp as appropriate.
13198 	 */
13199 	if (shadow_end >= request_end) {
13200 		/* We got all the requested data; set resid to zero */
13201 		orig_bp->b_resid = 0;
13202 	} else {
13203 		/*
13204 		 * We failed to get enough data to fully satisfy the original
13205 		 * request. Just copy back whatever data we got and set
13206 		 * up the residual and error code as required.
13207 		 *
13208 		 * 'shortfall' is the amount by which the data received with the
13209 		 * shadow buf has "fallen short" of the requested amount.
13210 		 */
13211 		shortfall = (size_t)(request_end - shadow_end);
13212 
13213 		if (shortfall > orig_bp->b_bcount) {
13214 			/*
13215 			 * We did not get enough data to even partially
13216 			 * fulfill the original request.  The residual is
13217 			 * equal to the amount requested.
13218 			 */
13219 			orig_bp->b_resid = orig_bp->b_bcount;
13220 		} else {
13221 			/*
13222 			 * We did not get all the data that we requested
13223 			 * from the device, but we will try to return what
13224 			 * portion we did get.
13225 			 */
13226 			orig_bp->b_resid = shortfall;
13227 		}
13228 		ASSERT(copy_length >= orig_bp->b_resid);
13229 		copy_length  -= orig_bp->b_resid;
13230 	}
13231 
13232 	/* Propagate the error code from the shadow buf to the original buf */
13233 	bioerror(orig_bp, bp->b_error);
13234 
13235 	if (is_write) {
13236 		goto freebuf_done;	/* No data copying for a WRITE */
13237 	}
13238 
13239 	if (has_wmap) {
13240 		/*
13241 		 * This is a READ command from the READ phase of a
13242 		 * read-modify-write request. We have to copy the data given
13243 		 * by the user OVER the data returned by the READ command,
13244 		 * then convert the command from a READ to a WRITE and send
13245 		 * it back to the target.
13246 		 */
13247 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
13248 		    copy_length);
13249 
13250 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
13251 
13252 		/*
13253 		 * Dispatch the WRITE command to the taskq thread, which
13254 		 * will in turn send the command to the target. When the
13255 		 * WRITE command completes, we (sd_mapblocksize_iodone())
13256 		 * will get called again as part of the iodone chain
13257 		 * processing for it. Note that we will still be dealing
13258 		 * with the shadow buf at that point.
13259 		 */
13260 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
13261 		    KM_NOSLEEP) != 0) {
13262 			/*
13263 			 * Dispatch was successful so we are done. Return
13264 			 * without going any higher up the iodone chain. Do
13265 			 * not free up any layer-private data until after the
13266 			 * WRITE completes.
13267 			 */
13268 			return;
13269 		}
13270 
13271 		/*
13272 		 * Dispatch of the WRITE command failed; set up the error
13273 		 * condition and send this IO back up the iodone chain.
13274 		 */
13275 		bioerror(orig_bp, EIO);
13276 		orig_bp->b_resid = orig_bp->b_bcount;
13277 
13278 	} else {
13279 		/*
13280 		 * This is a regular READ request (ie, not a RMW). Copy the
13281 		 * data from the shadow buf into the original buf. The
13282 		 * copy_offset compensates for any "misalignment" between the
13283 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
13284 		 * original buf (with its un->un_sys_blocksize blocks).
13285 		 */
13286 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
13287 		    copy_length);
13288 	}
13289 
13290 freebuf_done:
13291 
13292 	/*
13293 	 * At this point we still have both the shadow buf AND the original
13294 	 * buf to deal with, as well as the layer-private data area in each.
13295 	 * Local variables are as follows:
13296 	 *
13297 	 * bp -- points to shadow buf
13298 	 * xp -- points to xbuf of shadow buf
13299 	 * bsp -- points to layer-private data area of shadow buf
13300 	 * orig_bp -- points to original buf
13301 	 *
13302 	 * First free the shadow buf and its associated xbuf, then free the
13303 	 * layer-private data area from the shadow buf. There is no need to
13304 	 * restore xb_private in the shadow xbuf.
13305 	 */
13306 	sd_shadow_buf_free(bp);
13307 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13308 
13309 	/*
13310 	 * Now update the local variables to point to the original buf, xbuf,
13311 	 * and layer-private area.
13312 	 */
13313 	bp = orig_bp;
13314 	xp = SD_GET_XBUF(bp);
13315 	ASSERT(xp != NULL);
13316 	ASSERT(xp == orig_xp);
13317 	bsp = xp->xb_private;
13318 	ASSERT(bsp != NULL);
13319 
13320 done:
13321 	/*
13322 	 * Restore xb_private to whatever it was set to by the next higher
13323 	 * layer in the chain, then free the layer-private data area.
13324 	 */
13325 	xp->xb_private = bsp->mbs_oprivate;
13326 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13327 
13328 exit:
13329 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
13330 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
13331 
13332 	SD_NEXT_IODONE(index, un, bp);
13333 }
13334 
13335 
13336 /*
13337  *    Function: sd_checksum_iostart
13338  *
13339  * Description: A stub function for a layer that's currently not used.
13340  *		For now just a placeholder.
13341  *
13342  *     Context: Kernel thread context
13343  */
13344 
13345 static void
13346 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
13347 {
13348 	ASSERT(un != NULL);
13349 	ASSERT(bp != NULL);
13350 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13351 	SD_NEXT_IOSTART(index, un, bp);
13352 }
13353 
13354 
13355 /*
13356  *    Function: sd_checksum_iodone
13357  *
13358  * Description: A stub function for a layer that's currently not used.
13359  *		For now just a placeholder.
13360  *
13361  *     Context: May be called under interrupt context
13362  */
13363 
13364 static void
13365 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
13366 {
13367 	ASSERT(un != NULL);
13368 	ASSERT(bp != NULL);
13369 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13370 	SD_NEXT_IODONE(index, un, bp);
13371 }
13372 
13373 
13374 /*
13375  *    Function: sd_checksum_uscsi_iostart
13376  *
13377  * Description: A stub function for a layer that's currently not used.
13378  *		For now just a placeholder.
13379  *
13380  *     Context: Kernel thread context
13381  */
13382 
13383 static void
13384 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
13385 {
13386 	ASSERT(un != NULL);
13387 	ASSERT(bp != NULL);
13388 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13389 	SD_NEXT_IOSTART(index, un, bp);
13390 }
13391 
13392 
13393 /*
13394  *    Function: sd_checksum_uscsi_iodone
13395  *
13396  * Description: A stub function for a layer that's currently not used.
13397  *		For now just a placeholder.
13398  *
13399  *     Context: May be called under interrupt context
13400  */
13401 
13402 static void
13403 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
13404 {
13405 	ASSERT(un != NULL);
13406 	ASSERT(bp != NULL);
13407 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13408 	SD_NEXT_IODONE(index, un, bp);
13409 }
13410 
13411 
13412 /*
13413  *    Function: sd_pm_iostart
13414  *
13415  * Description: iostart-side routine for Power mangement.
13416  *
13417  *     Context: Kernel thread context
13418  */
13419 
13420 static void
13421 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
13422 {
13423 	ASSERT(un != NULL);
13424 	ASSERT(bp != NULL);
13425 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13426 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13427 
13428 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
13429 
13430 	if (sd_pm_entry(un) != DDI_SUCCESS) {
13431 		/*
13432 		 * Set up to return the failed buf back up the 'iodone'
13433 		 * side of the calling chain.
13434 		 */
13435 		bioerror(bp, EIO);
13436 		bp->b_resid = bp->b_bcount;
13437 
13438 		SD_BEGIN_IODONE(index, un, bp);
13439 
13440 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13441 		return;
13442 	}
13443 
13444 	SD_NEXT_IOSTART(index, un, bp);
13445 
13446 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13447 }
13448 
13449 
13450 /*
13451  *    Function: sd_pm_iodone
13452  *
13453  * Description: iodone-side routine for power mangement.
13454  *
13455  *     Context: may be called from interrupt context
13456  */
13457 
13458 static void
13459 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
13460 {
13461 	ASSERT(un != NULL);
13462 	ASSERT(bp != NULL);
13463 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13464 
13465 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
13466 
13467 	/*
13468 	 * After attach the following flag is only read, so don't
13469 	 * take the penalty of acquiring a mutex for it.
13470 	 */
13471 	if (un->un_f_pm_is_enabled == TRUE) {
13472 		sd_pm_exit(un);
13473 	}
13474 
13475 	SD_NEXT_IODONE(index, un, bp);
13476 
13477 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
13478 }
13479 
13480 
13481 /*
13482  *    Function: sd_core_iostart
13483  *
13484  * Description: Primary driver function for enqueuing buf(9S) structs from
13485  *		the system and initiating IO to the target device
13486  *
13487  *     Context: Kernel thread context. Can sleep.
13488  *
13489  * Assumptions:  - The given xp->xb_blkno is absolute
13490  *		   (ie, relative to the start of the device).
13491  *		 - The IO is to be done using the native blocksize of
13492  *		   the device, as specified in un->un_tgt_blocksize.
13493  */
13494 /* ARGSUSED */
13495 static void
13496 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
13497 {
13498 	struct sd_xbuf *xp;
13499 
13500 	ASSERT(un != NULL);
13501 	ASSERT(bp != NULL);
13502 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13503 	ASSERT(bp->b_resid == 0);
13504 
13505 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
13506 
13507 	xp = SD_GET_XBUF(bp);
13508 	ASSERT(xp != NULL);
13509 
13510 	mutex_enter(SD_MUTEX(un));
13511 
13512 	/*
13513 	 * If we are currently in the failfast state, fail any new IO
13514 	 * that has B_FAILFAST set, then return.
13515 	 */
13516 	if ((bp->b_flags & B_FAILFAST) &&
13517 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
13518 		mutex_exit(SD_MUTEX(un));
13519 		bioerror(bp, EIO);
13520 		bp->b_resid = bp->b_bcount;
13521 		SD_BEGIN_IODONE(index, un, bp);
13522 		return;
13523 	}
13524 
13525 	if (SD_IS_DIRECT_PRIORITY(xp)) {
13526 		/*
13527 		 * Priority command -- transport it immediately.
13528 		 *
13529 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
13530 		 * because all direct priority commands should be associated
13531 		 * with error recovery actions which we don't want to retry.
13532 		 */
13533 		sd_start_cmds(un, bp);
13534 	} else {
13535 		/*
13536 		 * Normal command -- add it to the wait queue, then start
13537 		 * transporting commands from the wait queue.
13538 		 */
13539 		sd_add_buf_to_waitq(un, bp);
13540 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13541 		sd_start_cmds(un, NULL);
13542 	}
13543 
13544 	mutex_exit(SD_MUTEX(un));
13545 
13546 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
13547 }
13548 
13549 
13550 /*
13551  *    Function: sd_init_cdb_limits
13552  *
13553  * Description: This is to handle scsi_pkt initialization differences
13554  *		between the driver platforms.
13555  *
13556  *		Legacy behaviors:
13557  *
13558  *		If the block number or the sector count exceeds the
13559  *		capabilities of a Group 0 command, shift over to a
13560  *		Group 1 command. We don't blindly use Group 1
13561  *		commands because a) some drives (CDC Wren IVs) get a
13562  *		bit confused, and b) there is probably a fair amount
13563  *		of speed difference for a target to receive and decode
13564  *		a 10 byte command instead of a 6 byte command.
13565  *
13566  *		The xfer time difference of 6 vs 10 byte CDBs is
13567  *		still significant so this code is still worthwhile.
13568  *		10 byte CDBs are very inefficient with the fas HBA driver
13569  *		and older disks. Each CDB byte took 1 usec with some
13570  *		popular disks.
13571  *
13572  *     Context: Must be called at attach time
13573  */
13574 
13575 static void
13576 sd_init_cdb_limits(struct sd_lun *un)
13577 {
13578 	int hba_cdb_limit;
13579 
13580 	/*
13581 	 * Use CDB_GROUP1 commands for most devices except for
13582 	 * parallel SCSI fixed drives in which case we get better
13583 	 * performance using CDB_GROUP0 commands (where applicable).
13584 	 */
13585 	un->un_mincdb = SD_CDB_GROUP1;
13586 #if !defined(__fibre)
13587 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
13588 	    !un->un_f_has_removable_media) {
13589 		un->un_mincdb = SD_CDB_GROUP0;
13590 	}
13591 #endif
13592 
13593 	/*
13594 	 * Try to read the max-cdb-length supported by HBA.
13595 	 */
13596 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
13597 	if (0 >= un->un_max_hba_cdb) {
13598 		un->un_max_hba_cdb = CDB_GROUP4;
13599 		hba_cdb_limit = SD_CDB_GROUP4;
13600 	} else if (0 < un->un_max_hba_cdb &&
13601 	    un->un_max_hba_cdb < CDB_GROUP1) {
13602 		hba_cdb_limit = SD_CDB_GROUP0;
13603 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
13604 	    un->un_max_hba_cdb < CDB_GROUP5) {
13605 		hba_cdb_limit = SD_CDB_GROUP1;
13606 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
13607 	    un->un_max_hba_cdb < CDB_GROUP4) {
13608 		hba_cdb_limit = SD_CDB_GROUP5;
13609 	} else {
13610 		hba_cdb_limit = SD_CDB_GROUP4;
13611 	}
13612 
13613 	/*
13614 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
13615 	 * commands for fixed disks unless we are building for a 32 bit
13616 	 * kernel.
13617 	 */
13618 #ifdef _LP64
13619 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13620 	    min(hba_cdb_limit, SD_CDB_GROUP4);
13621 #else
13622 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13623 	    min(hba_cdb_limit, SD_CDB_GROUP1);
13624 #endif
13625 
13626 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
13627 	    ? sizeof (struct scsi_arq_status) : 1);
13628 	un->un_cmd_timeout = (ushort_t)sd_io_time;
13629 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
13630 }
13631 
13632 
13633 /*
13634  *    Function: sd_initpkt_for_buf
13635  *
13636  * Description: Allocate and initialize for transport a scsi_pkt struct,
13637  *		based upon the info specified in the given buf struct.
13638  *
13639  *		Assumes the xb_blkno in the request is absolute (ie,
13640  *		relative to the start of the device (NOT partition!).
13641  *		Also assumes that the request is using the native block
13642  *		size of the device (as returned by the READ CAPACITY
13643  *		command).
13644  *
13645  * Return Code: SD_PKT_ALLOC_SUCCESS
13646  *		SD_PKT_ALLOC_FAILURE
13647  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13648  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13649  *
13650  *     Context: Kernel thread and may be called from software interrupt context
13651  *		as part of a sdrunout callback. This function may not block or
13652  *		call routines that block
13653  */
13654 
13655 static int
13656 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
13657 {
13658 	struct sd_xbuf	*xp;
13659 	struct scsi_pkt *pktp = NULL;
13660 	struct sd_lun	*un;
13661 	size_t		blockcount;
13662 	daddr_t		startblock;
13663 	int		rval;
13664 	int		cmd_flags;
13665 
13666 	ASSERT(bp != NULL);
13667 	ASSERT(pktpp != NULL);
13668 	xp = SD_GET_XBUF(bp);
13669 	ASSERT(xp != NULL);
13670 	un = SD_GET_UN(bp);
13671 	ASSERT(un != NULL);
13672 	ASSERT(mutex_owned(SD_MUTEX(un)));
13673 	ASSERT(bp->b_resid == 0);
13674 
13675 	SD_TRACE(SD_LOG_IO_CORE, un,
13676 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13677 
13678 	mutex_exit(SD_MUTEX(un));
13679 
13680 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13681 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13682 		/*
13683 		 * Already have a scsi_pkt -- just need DMA resources.
13684 		 * We must recompute the CDB in case the mapping returns
13685 		 * a nonzero pkt_resid.
13686 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13687 		 * that is being retried, the unmap/remap of the DMA resouces
13688 		 * will result in the entire transfer starting over again
13689 		 * from the very first block.
13690 		 */
13691 		ASSERT(xp->xb_pktp != NULL);
13692 		pktp = xp->xb_pktp;
13693 	} else {
13694 		pktp = NULL;
13695 	}
13696 #endif /* __i386 || __amd64 */
13697 
13698 	startblock = xp->xb_blkno;	/* Absolute block num. */
13699 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13700 
13701 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13702 
13703 	/*
13704 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13705 	 * call scsi_init_pkt, and build the CDB.
13706 	 */
13707 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13708 	    cmd_flags, sdrunout, (caddr_t)un,
13709 	    startblock, blockcount);
13710 
13711 	if (rval == 0) {
13712 		/*
13713 		 * Success.
13714 		 *
13715 		 * If partial DMA is being used and required for this transfer.
13716 		 * set it up here.
13717 		 */
13718 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13719 		    (pktp->pkt_resid != 0)) {
13720 
13721 			/*
13722 			 * Save the CDB length and pkt_resid for the
13723 			 * next xfer
13724 			 */
13725 			xp->xb_dma_resid = pktp->pkt_resid;
13726 
13727 			/* rezero resid */
13728 			pktp->pkt_resid = 0;
13729 
13730 		} else {
13731 			xp->xb_dma_resid = 0;
13732 		}
13733 
13734 		pktp->pkt_flags = un->un_tagflags;
13735 		pktp->pkt_time  = un->un_cmd_timeout;
13736 		pktp->pkt_comp  = sdintr;
13737 
13738 		pktp->pkt_private = bp;
13739 		*pktpp = pktp;
13740 
13741 		SD_TRACE(SD_LOG_IO_CORE, un,
13742 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13743 
13744 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13745 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13746 #endif
13747 
13748 		mutex_enter(SD_MUTEX(un));
13749 		return (SD_PKT_ALLOC_SUCCESS);
13750 
13751 	}
13752 
13753 	/*
13754 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13755 	 * from sd_setup_rw_pkt.
13756 	 */
13757 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13758 
13759 	if (rval == SD_PKT_ALLOC_FAILURE) {
13760 		*pktpp = NULL;
13761 		/*
13762 		 * Set the driver state to RWAIT to indicate the driver
13763 		 * is waiting on resource allocations. The driver will not
13764 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13765 		 */
13766 		mutex_enter(SD_MUTEX(un));
13767 		New_state(un, SD_STATE_RWAIT);
13768 
13769 		SD_ERROR(SD_LOG_IO_CORE, un,
13770 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13771 
13772 		if ((bp->b_flags & B_ERROR) != 0) {
13773 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13774 		}
13775 		return (SD_PKT_ALLOC_FAILURE);
13776 	} else {
13777 		/*
13778 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13779 		 *
13780 		 * This should never happen.  Maybe someone messed with the
13781 		 * kernel's minphys?
13782 		 */
13783 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13784 		    "Request rejected: too large for CDB: "
13785 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13786 		SD_ERROR(SD_LOG_IO_CORE, un,
13787 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13788 		mutex_enter(SD_MUTEX(un));
13789 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13790 
13791 	}
13792 }
13793 
13794 
13795 /*
13796  *    Function: sd_destroypkt_for_buf
13797  *
13798  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13799  *
13800  *     Context: Kernel thread or interrupt context
13801  */
13802 
13803 static void
13804 sd_destroypkt_for_buf(struct buf *bp)
13805 {
13806 	ASSERT(bp != NULL);
13807 	ASSERT(SD_GET_UN(bp) != NULL);
13808 
13809 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13810 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13811 
13812 	ASSERT(SD_GET_PKTP(bp) != NULL);
13813 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13814 
13815 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13816 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13817 }
13818 
13819 /*
13820  *    Function: sd_setup_rw_pkt
13821  *
13822  * Description: Determines appropriate CDB group for the requested LBA
13823  *		and transfer length, calls scsi_init_pkt, and builds
13824  *		the CDB.  Do not use for partial DMA transfers except
13825  *		for the initial transfer since the CDB size must
13826  *		remain constant.
13827  *
13828  *     Context: Kernel thread and may be called from software interrupt
13829  *		context as part of a sdrunout callback. This function may not
13830  *		block or call routines that block
13831  */
13832 
13833 
13834 int
13835 sd_setup_rw_pkt(struct sd_lun *un,
13836     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13837     int (*callback)(caddr_t), caddr_t callback_arg,
13838     diskaddr_t lba, uint32_t blockcount)
13839 {
13840 	struct scsi_pkt *return_pktp;
13841 	union scsi_cdb *cdbp;
13842 	struct sd_cdbinfo *cp = NULL;
13843 	int i;
13844 
13845 	/*
13846 	 * See which size CDB to use, based upon the request.
13847 	 */
13848 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13849 
13850 		/*
13851 		 * Check lba and block count against sd_cdbtab limits.
13852 		 * In the partial DMA case, we have to use the same size
13853 		 * CDB for all the transfers.  Check lba + blockcount
13854 		 * against the max LBA so we know that segment of the
13855 		 * transfer can use the CDB we select.
13856 		 */
13857 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13858 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13859 
13860 			/*
13861 			 * The command will fit into the CDB type
13862 			 * specified by sd_cdbtab[i].
13863 			 */
13864 			cp = sd_cdbtab + i;
13865 
13866 			/*
13867 			 * Call scsi_init_pkt so we can fill in the
13868 			 * CDB.
13869 			 */
13870 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13871 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13872 			    flags, callback, callback_arg);
13873 
13874 			if (return_pktp != NULL) {
13875 
13876 				/*
13877 				 * Return new value of pkt
13878 				 */
13879 				*pktpp = return_pktp;
13880 
13881 				/*
13882 				 * To be safe, zero the CDB insuring there is
13883 				 * no leftover data from a previous command.
13884 				 */
13885 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13886 
13887 				/*
13888 				 * Handle partial DMA mapping
13889 				 */
13890 				if (return_pktp->pkt_resid != 0) {
13891 
13892 					/*
13893 					 * Not going to xfer as many blocks as
13894 					 * originally expected
13895 					 */
13896 					blockcount -=
13897 					    SD_BYTES2TGTBLOCKS(un,
13898 					    return_pktp->pkt_resid);
13899 				}
13900 
13901 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13902 
13903 				/*
13904 				 * Set command byte based on the CDB
13905 				 * type we matched.
13906 				 */
13907 				cdbp->scc_cmd = cp->sc_grpmask |
13908 				    ((bp->b_flags & B_READ) ?
13909 				    SCMD_READ : SCMD_WRITE);
13910 
13911 				SD_FILL_SCSI1_LUN(un, return_pktp);
13912 
13913 				/*
13914 				 * Fill in LBA and length
13915 				 */
13916 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13917 				    (cp->sc_grpcode == CDB_GROUP4) ||
13918 				    (cp->sc_grpcode == CDB_GROUP0) ||
13919 				    (cp->sc_grpcode == CDB_GROUP5));
13920 
13921 				if (cp->sc_grpcode == CDB_GROUP1) {
13922 					FORMG1ADDR(cdbp, lba);
13923 					FORMG1COUNT(cdbp, blockcount);
13924 					return (0);
13925 				} else if (cp->sc_grpcode == CDB_GROUP4) {
13926 					FORMG4LONGADDR(cdbp, lba);
13927 					FORMG4COUNT(cdbp, blockcount);
13928 					return (0);
13929 				} else if (cp->sc_grpcode == CDB_GROUP0) {
13930 					FORMG0ADDR(cdbp, lba);
13931 					FORMG0COUNT(cdbp, blockcount);
13932 					return (0);
13933 				} else if (cp->sc_grpcode == CDB_GROUP5) {
13934 					FORMG5ADDR(cdbp, lba);
13935 					FORMG5COUNT(cdbp, blockcount);
13936 					return (0);
13937 				}
13938 
13939 				/*
13940 				 * It should be impossible to not match one
13941 				 * of the CDB types above, so we should never
13942 				 * reach this point.  Set the CDB command byte
13943 				 * to test-unit-ready to avoid writing
13944 				 * to somewhere we don't intend.
13945 				 */
13946 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
13947 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13948 			} else {
13949 				/*
13950 				 * Couldn't get scsi_pkt
13951 				 */
13952 				return (SD_PKT_ALLOC_FAILURE);
13953 			}
13954 		}
13955 	}
13956 
13957 	/*
13958 	 * None of the available CDB types were suitable.  This really
13959 	 * should never happen:  on a 64 bit system we support
13960 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
13961 	 * and on a 32 bit system we will refuse to bind to a device
13962 	 * larger than 2TB so addresses will never be larger than 32 bits.
13963 	 */
13964 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13965 }
13966 
13967 /*
13968  *    Function: sd_setup_next_rw_pkt
13969  *
13970  * Description: Setup packet for partial DMA transfers, except for the
13971  * 		initial transfer.  sd_setup_rw_pkt should be used for
13972  *		the initial transfer.
13973  *
13974  *     Context: Kernel thread and may be called from interrupt context.
13975  */
13976 
13977 int
13978 sd_setup_next_rw_pkt(struct sd_lun *un,
13979     struct scsi_pkt *pktp, struct buf *bp,
13980     diskaddr_t lba, uint32_t blockcount)
13981 {
13982 	uchar_t com;
13983 	union scsi_cdb *cdbp;
13984 	uchar_t cdb_group_id;
13985 
13986 	ASSERT(pktp != NULL);
13987 	ASSERT(pktp->pkt_cdbp != NULL);
13988 
13989 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
13990 	com = cdbp->scc_cmd;
13991 	cdb_group_id = CDB_GROUPID(com);
13992 
13993 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
13994 	    (cdb_group_id == CDB_GROUPID_1) ||
13995 	    (cdb_group_id == CDB_GROUPID_4) ||
13996 	    (cdb_group_id == CDB_GROUPID_5));
13997 
13998 	/*
13999 	 * Move pkt to the next portion of the xfer.
14000 	 * func is NULL_FUNC so we do not have to release
14001 	 * the disk mutex here.
14002 	 */
14003 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
14004 	    NULL_FUNC, NULL) == pktp) {
14005 		/* Success.  Handle partial DMA */
14006 		if (pktp->pkt_resid != 0) {
14007 			blockcount -=
14008 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
14009 		}
14010 
14011 		cdbp->scc_cmd = com;
14012 		SD_FILL_SCSI1_LUN(un, pktp);
14013 		if (cdb_group_id == CDB_GROUPID_1) {
14014 			FORMG1ADDR(cdbp, lba);
14015 			FORMG1COUNT(cdbp, blockcount);
14016 			return (0);
14017 		} else if (cdb_group_id == CDB_GROUPID_4) {
14018 			FORMG4LONGADDR(cdbp, lba);
14019 			FORMG4COUNT(cdbp, blockcount);
14020 			return (0);
14021 		} else if (cdb_group_id == CDB_GROUPID_0) {
14022 			FORMG0ADDR(cdbp, lba);
14023 			FORMG0COUNT(cdbp, blockcount);
14024 			return (0);
14025 		} else if (cdb_group_id == CDB_GROUPID_5) {
14026 			FORMG5ADDR(cdbp, lba);
14027 			FORMG5COUNT(cdbp, blockcount);
14028 			return (0);
14029 		}
14030 
14031 		/* Unreachable */
14032 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
14033 	}
14034 
14035 	/*
14036 	 * Error setting up next portion of cmd transfer.
14037 	 * Something is definitely very wrong and this
14038 	 * should not happen.
14039 	 */
14040 	return (SD_PKT_ALLOC_FAILURE);
14041 }
14042 
14043 /*
14044  *    Function: sd_initpkt_for_uscsi
14045  *
14046  * Description: Allocate and initialize for transport a scsi_pkt struct,
14047  *		based upon the info specified in the given uscsi_cmd struct.
14048  *
14049  * Return Code: SD_PKT_ALLOC_SUCCESS
14050  *		SD_PKT_ALLOC_FAILURE
14051  *		SD_PKT_ALLOC_FAILURE_NO_DMA
14052  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
14053  *
14054  *     Context: Kernel thread and may be called from software interrupt context
14055  *		as part of a sdrunout callback. This function may not block or
14056  *		call routines that block
14057  */
14058 
14059 static int
14060 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
14061 {
14062 	struct uscsi_cmd *uscmd;
14063 	struct sd_xbuf	*xp;
14064 	struct scsi_pkt	*pktp;
14065 	struct sd_lun	*un;
14066 	uint32_t	flags = 0;
14067 
14068 	ASSERT(bp != NULL);
14069 	ASSERT(pktpp != NULL);
14070 	xp = SD_GET_XBUF(bp);
14071 	ASSERT(xp != NULL);
14072 	un = SD_GET_UN(bp);
14073 	ASSERT(un != NULL);
14074 	ASSERT(mutex_owned(SD_MUTEX(un)));
14075 
14076 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14077 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14078 	ASSERT(uscmd != NULL);
14079 
14080 	SD_TRACE(SD_LOG_IO_CORE, un,
14081 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
14082 
14083 	/*
14084 	 * Allocate the scsi_pkt for the command.
14085 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
14086 	 *	 during scsi_init_pkt time and will continue to use the
14087 	 *	 same path as long as the same scsi_pkt is used without
14088 	 *	 intervening scsi_dma_free(). Since uscsi command does
14089 	 *	 not call scsi_dmafree() before retry failed command, it
14090 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
14091 	 *	 set such that scsi_vhci can use other available path for
14092 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
14093 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
14094 	 */
14095 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14096 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
14097 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
14098 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
14099 		    - sizeof (struct scsi_extended_sense)), 0,
14100 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
14101 		    sdrunout, (caddr_t)un);
14102 	} else {
14103 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
14104 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
14105 		    sizeof (struct scsi_arq_status), 0,
14106 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
14107 		    sdrunout, (caddr_t)un);
14108 	}
14109 
14110 	if (pktp == NULL) {
14111 		*pktpp = NULL;
14112 		/*
14113 		 * Set the driver state to RWAIT to indicate the driver
14114 		 * is waiting on resource allocations. The driver will not
14115 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
14116 		 */
14117 		New_state(un, SD_STATE_RWAIT);
14118 
14119 		SD_ERROR(SD_LOG_IO_CORE, un,
14120 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
14121 
14122 		if ((bp->b_flags & B_ERROR) != 0) {
14123 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
14124 		}
14125 		return (SD_PKT_ALLOC_FAILURE);
14126 	}
14127 
14128 	/*
14129 	 * We do not do DMA breakup for USCSI commands, so return failure
14130 	 * here if all the needed DMA resources were not allocated.
14131 	 */
14132 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
14133 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
14134 		scsi_destroy_pkt(pktp);
14135 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
14136 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
14137 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
14138 	}
14139 
14140 	/* Init the cdb from the given uscsi struct */
14141 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
14142 	    uscmd->uscsi_cdb[0], 0, 0, 0);
14143 
14144 	SD_FILL_SCSI1_LUN(un, pktp);
14145 
14146 	/*
14147 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
14148 	 * for listing of the supported flags.
14149 	 */
14150 
14151 	if (uscmd->uscsi_flags & USCSI_SILENT) {
14152 		flags |= FLAG_SILENT;
14153 	}
14154 
14155 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
14156 		flags |= FLAG_DIAGNOSE;
14157 	}
14158 
14159 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
14160 		flags |= FLAG_ISOLATE;
14161 	}
14162 
14163 	if (un->un_f_is_fibre == FALSE) {
14164 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
14165 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
14166 		}
14167 	}
14168 
14169 	/*
14170 	 * Set the pkt flags here so we save time later.
14171 	 * Note: These flags are NOT in the uscsi man page!!!
14172 	 */
14173 	if (uscmd->uscsi_flags & USCSI_HEAD) {
14174 		flags |= FLAG_HEAD;
14175 	}
14176 
14177 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
14178 		flags |= FLAG_NOINTR;
14179 	}
14180 
14181 	/*
14182 	 * For tagged queueing, things get a bit complicated.
14183 	 * Check first for head of queue and last for ordered queue.
14184 	 * If neither head nor order, use the default driver tag flags.
14185 	 */
14186 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
14187 		if (uscmd->uscsi_flags & USCSI_HTAG) {
14188 			flags |= FLAG_HTAG;
14189 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
14190 			flags |= FLAG_OTAG;
14191 		} else {
14192 			flags |= un->un_tagflags & FLAG_TAGMASK;
14193 		}
14194 	}
14195 
14196 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
14197 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
14198 	}
14199 
14200 	pktp->pkt_flags = flags;
14201 
14202 	/* Transfer uscsi information to scsi_pkt */
14203 	(void) scsi_uscsi_pktinit(uscmd, pktp);
14204 
14205 	/* Copy the caller's CDB into the pkt... */
14206 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
14207 
14208 	if (uscmd->uscsi_timeout == 0) {
14209 		pktp->pkt_time = un->un_uscsi_timeout;
14210 	} else {
14211 		pktp->pkt_time = uscmd->uscsi_timeout;
14212 	}
14213 
14214 	/* need it later to identify USCSI request in sdintr */
14215 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
14216 
14217 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
14218 
14219 	pktp->pkt_private = bp;
14220 	pktp->pkt_comp = sdintr;
14221 	*pktpp = pktp;
14222 
14223 	SD_TRACE(SD_LOG_IO_CORE, un,
14224 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
14225 
14226 	return (SD_PKT_ALLOC_SUCCESS);
14227 }
14228 
14229 
14230 /*
14231  *    Function: sd_destroypkt_for_uscsi
14232  *
14233  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
14234  *		IOs.. Also saves relevant info into the associated uscsi_cmd
14235  *		struct.
14236  *
14237  *     Context: May be called under interrupt context
14238  */
14239 
14240 static void
14241 sd_destroypkt_for_uscsi(struct buf *bp)
14242 {
14243 	struct uscsi_cmd *uscmd;
14244 	struct sd_xbuf	*xp;
14245 	struct scsi_pkt	*pktp;
14246 	struct sd_lun	*un;
14247 	struct sd_uscsi_info *suip;
14248 
14249 	ASSERT(bp != NULL);
14250 	xp = SD_GET_XBUF(bp);
14251 	ASSERT(xp != NULL);
14252 	un = SD_GET_UN(bp);
14253 	ASSERT(un != NULL);
14254 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14255 	pktp = SD_GET_PKTP(bp);
14256 	ASSERT(pktp != NULL);
14257 
14258 	SD_TRACE(SD_LOG_IO_CORE, un,
14259 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
14260 
14261 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14262 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14263 	ASSERT(uscmd != NULL);
14264 
14265 	/* Save the status and the residual into the uscsi_cmd struct */
14266 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
14267 	uscmd->uscsi_resid  = bp->b_resid;
14268 
14269 	/* Transfer scsi_pkt information to uscsi */
14270 	(void) scsi_uscsi_pktfini(pktp, uscmd);
14271 
14272 	/*
14273 	 * If enabled, copy any saved sense data into the area specified
14274 	 * by the uscsi command.
14275 	 */
14276 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
14277 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
14278 		/*
14279 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
14280 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
14281 		 */
14282 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
14283 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
14284 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14285 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14286 			    MAX_SENSE_LENGTH);
14287 		} else {
14288 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14289 			    SENSE_LENGTH);
14290 		}
14291 	}
14292 	/*
14293 	 * The following assignments are for SCSI FMA.
14294 	 */
14295 	ASSERT(xp->xb_private != NULL);
14296 	suip = (struct sd_uscsi_info *)xp->xb_private;
14297 	suip->ui_pkt_reason = pktp->pkt_reason;
14298 	suip->ui_pkt_state = pktp->pkt_state;
14299 	suip->ui_pkt_statistics = pktp->pkt_statistics;
14300 	suip->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
14301 
14302 	/* We are done with the scsi_pkt; free it now */
14303 	ASSERT(SD_GET_PKTP(bp) != NULL);
14304 	scsi_destroy_pkt(SD_GET_PKTP(bp));
14305 
14306 	SD_TRACE(SD_LOG_IO_CORE, un,
14307 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
14308 }
14309 
14310 
14311 /*
14312  *    Function: sd_bioclone_alloc
14313  *
14314  * Description: Allocate a buf(9S) and init it as per the given buf
14315  *		and the various arguments.  The associated sd_xbuf
14316  *		struct is (nearly) duplicated.  The struct buf *bp
14317  *		argument is saved in new_xp->xb_private.
14318  *
14319  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14320  *		datalen - size of data area for the shadow bp
14321  *		blkno - starting LBA
14322  *		func - function pointer for b_iodone in the shadow buf. (May
14323  *			be NULL if none.)
14324  *
14325  * Return Code: Pointer to allocates buf(9S) struct
14326  *
14327  *     Context: Can sleep.
14328  */
14329 
14330 static struct buf *
14331 sd_bioclone_alloc(struct buf *bp, size_t datalen,
14332 	daddr_t blkno, int (*func)(struct buf *))
14333 {
14334 	struct	sd_lun	*un;
14335 	struct	sd_xbuf	*xp;
14336 	struct	sd_xbuf	*new_xp;
14337 	struct	buf	*new_bp;
14338 
14339 	ASSERT(bp != NULL);
14340 	xp = SD_GET_XBUF(bp);
14341 	ASSERT(xp != NULL);
14342 	un = SD_GET_UN(bp);
14343 	ASSERT(un != NULL);
14344 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14345 
14346 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
14347 	    NULL, KM_SLEEP);
14348 
14349 	new_bp->b_lblkno	= blkno;
14350 
14351 	/*
14352 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14353 	 * original xbuf into it.
14354 	 */
14355 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14356 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14357 
14358 	/*
14359 	 * The given bp is automatically saved in the xb_private member
14360 	 * of the new xbuf.  Callers are allowed to depend on this.
14361 	 */
14362 	new_xp->xb_private = bp;
14363 
14364 	new_bp->b_private  = new_xp;
14365 
14366 	return (new_bp);
14367 }
14368 
14369 /*
14370  *    Function: sd_shadow_buf_alloc
14371  *
14372  * Description: Allocate a buf(9S) and init it as per the given buf
14373  *		and the various arguments.  The associated sd_xbuf
14374  *		struct is (nearly) duplicated.  The struct buf *bp
14375  *		argument is saved in new_xp->xb_private.
14376  *
14377  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14378  *		datalen - size of data area for the shadow bp
14379  *		bflags - B_READ or B_WRITE (pseudo flag)
14380  *		blkno - starting LBA
14381  *		func - function pointer for b_iodone in the shadow buf. (May
14382  *			be NULL if none.)
14383  *
14384  * Return Code: Pointer to allocates buf(9S) struct
14385  *
14386  *     Context: Can sleep.
14387  */
14388 
14389 static struct buf *
14390 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
14391 	daddr_t blkno, int (*func)(struct buf *))
14392 {
14393 	struct	sd_lun	*un;
14394 	struct	sd_xbuf	*xp;
14395 	struct	sd_xbuf	*new_xp;
14396 	struct	buf	*new_bp;
14397 
14398 	ASSERT(bp != NULL);
14399 	xp = SD_GET_XBUF(bp);
14400 	ASSERT(xp != NULL);
14401 	un = SD_GET_UN(bp);
14402 	ASSERT(un != NULL);
14403 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14404 
14405 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
14406 		bp_mapin(bp);
14407 	}
14408 
14409 	bflags &= (B_READ | B_WRITE);
14410 #if defined(__i386) || defined(__amd64)
14411 	new_bp = getrbuf(KM_SLEEP);
14412 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
14413 	new_bp->b_bcount = datalen;
14414 	new_bp->b_flags = bflags |
14415 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
14416 #else
14417 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
14418 	    datalen, bflags, SLEEP_FUNC, NULL);
14419 #endif
14420 	new_bp->av_forw	= NULL;
14421 	new_bp->av_back	= NULL;
14422 	new_bp->b_dev	= bp->b_dev;
14423 	new_bp->b_blkno	= blkno;
14424 	new_bp->b_iodone = func;
14425 	new_bp->b_edev	= bp->b_edev;
14426 	new_bp->b_resid	= 0;
14427 
14428 	/* We need to preserve the B_FAILFAST flag */
14429 	if (bp->b_flags & B_FAILFAST) {
14430 		new_bp->b_flags |= B_FAILFAST;
14431 	}
14432 
14433 	/*
14434 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14435 	 * original xbuf into it.
14436 	 */
14437 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14438 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14439 
14440 	/* Need later to copy data between the shadow buf & original buf! */
14441 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
14442 
14443 	/*
14444 	 * The given bp is automatically saved in the xb_private member
14445 	 * of the new xbuf.  Callers are allowed to depend on this.
14446 	 */
14447 	new_xp->xb_private = bp;
14448 
14449 	new_bp->b_private  = new_xp;
14450 
14451 	return (new_bp);
14452 }
14453 
14454 /*
14455  *    Function: sd_bioclone_free
14456  *
14457  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
14458  *		in the larger than partition operation.
14459  *
14460  *     Context: May be called under interrupt context
14461  */
14462 
14463 static void
14464 sd_bioclone_free(struct buf *bp)
14465 {
14466 	struct sd_xbuf	*xp;
14467 
14468 	ASSERT(bp != NULL);
14469 	xp = SD_GET_XBUF(bp);
14470 	ASSERT(xp != NULL);
14471 
14472 	/*
14473 	 * Call bp_mapout() before freeing the buf,  in case a lower
14474 	 * layer or HBA  had done a bp_mapin().  we must do this here
14475 	 * as we are the "originator" of the shadow buf.
14476 	 */
14477 	bp_mapout(bp);
14478 
14479 	/*
14480 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14481 	 * never gets confused by a stale value in this field. (Just a little
14482 	 * extra defensiveness here.)
14483 	 */
14484 	bp->b_iodone = NULL;
14485 
14486 	freerbuf(bp);
14487 
14488 	kmem_free(xp, sizeof (struct sd_xbuf));
14489 }
14490 
14491 /*
14492  *    Function: sd_shadow_buf_free
14493  *
14494  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
14495  *
14496  *     Context: May be called under interrupt context
14497  */
14498 
14499 static void
14500 sd_shadow_buf_free(struct buf *bp)
14501 {
14502 	struct sd_xbuf	*xp;
14503 
14504 	ASSERT(bp != NULL);
14505 	xp = SD_GET_XBUF(bp);
14506 	ASSERT(xp != NULL);
14507 
14508 #if defined(__sparc)
14509 	/*
14510 	 * Call bp_mapout() before freeing the buf,  in case a lower
14511 	 * layer or HBA  had done a bp_mapin().  we must do this here
14512 	 * as we are the "originator" of the shadow buf.
14513 	 */
14514 	bp_mapout(bp);
14515 #endif
14516 
14517 	/*
14518 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14519 	 * never gets confused by a stale value in this field. (Just a little
14520 	 * extra defensiveness here.)
14521 	 */
14522 	bp->b_iodone = NULL;
14523 
14524 #if defined(__i386) || defined(__amd64)
14525 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
14526 	freerbuf(bp);
14527 #else
14528 	scsi_free_consistent_buf(bp);
14529 #endif
14530 
14531 	kmem_free(xp, sizeof (struct sd_xbuf));
14532 }
14533 
14534 
14535 /*
14536  *    Function: sd_print_transport_rejected_message
14537  *
14538  * Description: This implements the ludicrously complex rules for printing
14539  *		a "transport rejected" message.  This is to address the
14540  *		specific problem of having a flood of this error message
14541  *		produced when a failover occurs.
14542  *
14543  *     Context: Any.
14544  */
14545 
14546 static void
14547 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
14548 	int code)
14549 {
14550 	ASSERT(un != NULL);
14551 	ASSERT(mutex_owned(SD_MUTEX(un)));
14552 	ASSERT(xp != NULL);
14553 
14554 	/*
14555 	 * Print the "transport rejected" message under the following
14556 	 * conditions:
14557 	 *
14558 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
14559 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
14560 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
14561 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
14562 	 *   scsi_transport(9F) (which indicates that the target might have
14563 	 *   gone off-line).  This uses the un->un_tran_fatal_count
14564 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
14565 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
14566 	 *   from scsi_transport().
14567 	 *
14568 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
14569 	 * the preceeding cases in order for the message to be printed.
14570 	 */
14571 	if (((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) &&
14572 	    (SD_FM_LOG(un) == SD_FM_LOG_NSUP)) {
14573 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
14574 		    (code != TRAN_FATAL_ERROR) ||
14575 		    (un->un_tran_fatal_count == 1)) {
14576 			switch (code) {
14577 			case TRAN_BADPKT:
14578 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14579 				    "transport rejected bad packet\n");
14580 				break;
14581 			case TRAN_FATAL_ERROR:
14582 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14583 				    "transport rejected fatal error\n");
14584 				break;
14585 			default:
14586 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14587 				    "transport rejected (%d)\n", code);
14588 				break;
14589 			}
14590 		}
14591 	}
14592 }
14593 
14594 
14595 /*
14596  *    Function: sd_add_buf_to_waitq
14597  *
14598  * Description: Add the given buf(9S) struct to the wait queue for the
14599  *		instance.  If sorting is enabled, then the buf is added
14600  *		to the queue via an elevator sort algorithm (a la
14601  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
14602  *		If sorting is not enabled, then the buf is just added
14603  *		to the end of the wait queue.
14604  *
14605  * Return Code: void
14606  *
14607  *     Context: Does not sleep/block, therefore technically can be called
14608  *		from any context.  However if sorting is enabled then the
14609  *		execution time is indeterminate, and may take long if
14610  *		the wait queue grows large.
14611  */
14612 
14613 static void
14614 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
14615 {
14616 	struct buf *ap;
14617 
14618 	ASSERT(bp != NULL);
14619 	ASSERT(un != NULL);
14620 	ASSERT(mutex_owned(SD_MUTEX(un)));
14621 
14622 	/* If the queue is empty, add the buf as the only entry & return. */
14623 	if (un->un_waitq_headp == NULL) {
14624 		ASSERT(un->un_waitq_tailp == NULL);
14625 		un->un_waitq_headp = un->un_waitq_tailp = bp;
14626 		bp->av_forw = NULL;
14627 		return;
14628 	}
14629 
14630 	ASSERT(un->un_waitq_tailp != NULL);
14631 
14632 	/*
14633 	 * If sorting is disabled, just add the buf to the tail end of
14634 	 * the wait queue and return.
14635 	 */
14636 	if (un->un_f_disksort_disabled || un->un_f_enable_rmw) {
14637 		un->un_waitq_tailp->av_forw = bp;
14638 		un->un_waitq_tailp = bp;
14639 		bp->av_forw = NULL;
14640 		return;
14641 	}
14642 
14643 	/*
14644 	 * Sort thru the list of requests currently on the wait queue
14645 	 * and add the new buf request at the appropriate position.
14646 	 *
14647 	 * The un->un_waitq_headp is an activity chain pointer on which
14648 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
14649 	 * first queue holds those requests which are positioned after
14650 	 * the current SD_GET_BLKNO() (in the first request); the second holds
14651 	 * requests which came in after their SD_GET_BLKNO() number was passed.
14652 	 * Thus we implement a one way scan, retracting after reaching
14653 	 * the end of the drive to the first request on the second
14654 	 * queue, at which time it becomes the first queue.
14655 	 * A one-way scan is natural because of the way UNIX read-ahead
14656 	 * blocks are allocated.
14657 	 *
14658 	 * If we lie after the first request, then we must locate the
14659 	 * second request list and add ourselves to it.
14660 	 */
14661 	ap = un->un_waitq_headp;
14662 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
14663 		while (ap->av_forw != NULL) {
14664 			/*
14665 			 * Look for an "inversion" in the (normally
14666 			 * ascending) block numbers. This indicates
14667 			 * the start of the second request list.
14668 			 */
14669 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14670 				/*
14671 				 * Search the second request list for the
14672 				 * first request at a larger block number.
14673 				 * We go before that; however if there is
14674 				 * no such request, we go at the end.
14675 				 */
14676 				do {
14677 					if (SD_GET_BLKNO(bp) <
14678 					    SD_GET_BLKNO(ap->av_forw)) {
14679 						goto insert;
14680 					}
14681 					ap = ap->av_forw;
14682 				} while (ap->av_forw != NULL);
14683 				goto insert;		/* after last */
14684 			}
14685 			ap = ap->av_forw;
14686 		}
14687 
14688 		/*
14689 		 * No inversions... we will go after the last, and
14690 		 * be the first request in the second request list.
14691 		 */
14692 		goto insert;
14693 	}
14694 
14695 	/*
14696 	 * Request is at/after the current request...
14697 	 * sort in the first request list.
14698 	 */
14699 	while (ap->av_forw != NULL) {
14700 		/*
14701 		 * We want to go after the current request (1) if
14702 		 * there is an inversion after it (i.e. it is the end
14703 		 * of the first request list), or (2) if the next
14704 		 * request is a larger block no. than our request.
14705 		 */
14706 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14707 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14708 			goto insert;
14709 		}
14710 		ap = ap->av_forw;
14711 	}
14712 
14713 	/*
14714 	 * Neither a second list nor a larger request, therefore
14715 	 * we go at the end of the first list (which is the same
14716 	 * as the end of the whole schebang).
14717 	 */
14718 insert:
14719 	bp->av_forw = ap->av_forw;
14720 	ap->av_forw = bp;
14721 
14722 	/*
14723 	 * If we inserted onto the tail end of the waitq, make sure the
14724 	 * tail pointer is updated.
14725 	 */
14726 	if (ap == un->un_waitq_tailp) {
14727 		un->un_waitq_tailp = bp;
14728 	}
14729 }
14730 
14731 
14732 /*
14733  *    Function: sd_start_cmds
14734  *
14735  * Description: Remove and transport cmds from the driver queues.
14736  *
14737  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14738  *
14739  *		immed_bp - ptr to a buf to be transported immediately. Only
14740  *		the immed_bp is transported; bufs on the waitq are not
14741  *		processed and the un_retry_bp is not checked.  If immed_bp is
14742  *		NULL, then normal queue processing is performed.
14743  *
14744  *     Context: May be called from kernel thread context, interrupt context,
14745  *		or runout callback context. This function may not block or
14746  *		call routines that block.
14747  */
14748 
14749 static void
14750 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14751 {
14752 	struct	sd_xbuf	*xp;
14753 	struct	buf	*bp;
14754 	void	(*statp)(kstat_io_t *);
14755 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14756 	void	(*saved_statp)(kstat_io_t *);
14757 #endif
14758 	int	rval;
14759 	struct sd_fm_internal *sfip = NULL;
14760 
14761 	ASSERT(un != NULL);
14762 	ASSERT(mutex_owned(SD_MUTEX(un)));
14763 	ASSERT(un->un_ncmds_in_transport >= 0);
14764 	ASSERT(un->un_throttle >= 0);
14765 
14766 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14767 
14768 	do {
14769 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14770 		saved_statp = NULL;
14771 #endif
14772 
14773 		/*
14774 		 * If we are syncing or dumping, fail the command to
14775 		 * avoid recursively calling back into scsi_transport().
14776 		 * The dump I/O itself uses a separate code path so this
14777 		 * only prevents non-dump I/O from being sent while dumping.
14778 		 * File system sync takes place before dumping begins.
14779 		 * During panic, filesystem I/O is allowed provided
14780 		 * un_in_callback is <= 1.  This is to prevent recursion
14781 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14782 		 * sd_start_cmds and so on.  See panic.c for more information
14783 		 * about the states the system can be in during panic.
14784 		 */
14785 		if ((un->un_state == SD_STATE_DUMPING) ||
14786 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14787 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14788 			    "sd_start_cmds: panicking\n");
14789 			goto exit;
14790 		}
14791 
14792 		if ((bp = immed_bp) != NULL) {
14793 			/*
14794 			 * We have a bp that must be transported immediately.
14795 			 * It's OK to transport the immed_bp here without doing
14796 			 * the throttle limit check because the immed_bp is
14797 			 * always used in a retry/recovery case. This means
14798 			 * that we know we are not at the throttle limit by
14799 			 * virtue of the fact that to get here we must have
14800 			 * already gotten a command back via sdintr(). This also
14801 			 * relies on (1) the command on un_retry_bp preventing
14802 			 * further commands from the waitq from being issued;
14803 			 * and (2) the code in sd_retry_command checking the
14804 			 * throttle limit before issuing a delayed or immediate
14805 			 * retry. This holds even if the throttle limit is
14806 			 * currently ratcheted down from its maximum value.
14807 			 */
14808 			statp = kstat_runq_enter;
14809 			if (bp == un->un_retry_bp) {
14810 				ASSERT((un->un_retry_statp == NULL) ||
14811 				    (un->un_retry_statp == kstat_waitq_enter) ||
14812 				    (un->un_retry_statp ==
14813 				    kstat_runq_back_to_waitq));
14814 				/*
14815 				 * If the waitq kstat was incremented when
14816 				 * sd_set_retry_bp() queued this bp for a retry,
14817 				 * then we must set up statp so that the waitq
14818 				 * count will get decremented correctly below.
14819 				 * Also we must clear un->un_retry_statp to
14820 				 * ensure that we do not act on a stale value
14821 				 * in this field.
14822 				 */
14823 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14824 				    (un->un_retry_statp ==
14825 				    kstat_runq_back_to_waitq)) {
14826 					statp = kstat_waitq_to_runq;
14827 				}
14828 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14829 				saved_statp = un->un_retry_statp;
14830 #endif
14831 				un->un_retry_statp = NULL;
14832 
14833 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14834 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14835 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14836 				    un, un->un_retry_bp, un->un_throttle,
14837 				    un->un_ncmds_in_transport);
14838 			} else {
14839 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14840 				    "processing priority bp:0x%p\n", bp);
14841 			}
14842 
14843 		} else if ((bp = un->un_waitq_headp) != NULL) {
14844 			/*
14845 			 * A command on the waitq is ready to go, but do not
14846 			 * send it if:
14847 			 *
14848 			 * (1) the throttle limit has been reached, or
14849 			 * (2) a retry is pending, or
14850 			 * (3) a START_STOP_UNIT callback pending, or
14851 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14852 			 *	command is pending.
14853 			 *
14854 			 * For all of these conditions, IO processing will
14855 			 * restart after the condition is cleared.
14856 			 */
14857 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14858 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14859 				    "sd_start_cmds: exiting, "
14860 				    "throttle limit reached!\n");
14861 				goto exit;
14862 			}
14863 			if (un->un_retry_bp != NULL) {
14864 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14865 				    "sd_start_cmds: exiting, retry pending!\n");
14866 				goto exit;
14867 			}
14868 			if (un->un_startstop_timeid != NULL) {
14869 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14870 				    "sd_start_cmds: exiting, "
14871 				    "START_STOP pending!\n");
14872 				goto exit;
14873 			}
14874 			if (un->un_direct_priority_timeid != NULL) {
14875 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14876 				    "sd_start_cmds: exiting, "
14877 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14878 				goto exit;
14879 			}
14880 
14881 			/* Dequeue the command */
14882 			un->un_waitq_headp = bp->av_forw;
14883 			if (un->un_waitq_headp == NULL) {
14884 				un->un_waitq_tailp = NULL;
14885 			}
14886 			bp->av_forw = NULL;
14887 			statp = kstat_waitq_to_runq;
14888 			SD_TRACE(SD_LOG_IO_CORE, un,
14889 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14890 
14891 		} else {
14892 			/* No work to do so bail out now */
14893 			SD_TRACE(SD_LOG_IO_CORE, un,
14894 			    "sd_start_cmds: no more work, exiting!\n");
14895 			goto exit;
14896 		}
14897 
14898 		/*
14899 		 * Reset the state to normal. This is the mechanism by which
14900 		 * the state transitions from either SD_STATE_RWAIT or
14901 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14902 		 * If state is SD_STATE_PM_CHANGING then this command is
14903 		 * part of the device power control and the state must
14904 		 * not be put back to normal. Doing so would would
14905 		 * allow new commands to proceed when they shouldn't,
14906 		 * the device may be going off.
14907 		 */
14908 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14909 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14910 			New_state(un, SD_STATE_NORMAL);
14911 		}
14912 
14913 		xp = SD_GET_XBUF(bp);
14914 		ASSERT(xp != NULL);
14915 
14916 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14917 		/*
14918 		 * Allocate the scsi_pkt if we need one, or attach DMA
14919 		 * resources if we have a scsi_pkt that needs them. The
14920 		 * latter should only occur for commands that are being
14921 		 * retried.
14922 		 */
14923 		if ((xp->xb_pktp == NULL) ||
14924 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
14925 #else
14926 		if (xp->xb_pktp == NULL) {
14927 #endif
14928 			/*
14929 			 * There is no scsi_pkt allocated for this buf. Call
14930 			 * the initpkt function to allocate & init one.
14931 			 *
14932 			 * The scsi_init_pkt runout callback functionality is
14933 			 * implemented as follows:
14934 			 *
14935 			 * 1) The initpkt function always calls
14936 			 *    scsi_init_pkt(9F) with sdrunout specified as the
14937 			 *    callback routine.
14938 			 * 2) A successful packet allocation is initialized and
14939 			 *    the I/O is transported.
14940 			 * 3) The I/O associated with an allocation resource
14941 			 *    failure is left on its queue to be retried via
14942 			 *    runout or the next I/O.
14943 			 * 4) The I/O associated with a DMA error is removed
14944 			 *    from the queue and failed with EIO. Processing of
14945 			 *    the transport queues is also halted to be
14946 			 *    restarted via runout or the next I/O.
14947 			 * 5) The I/O associated with a CDB size or packet
14948 			 *    size error is removed from the queue and failed
14949 			 *    with EIO. Processing of the transport queues is
14950 			 *    continued.
14951 			 *
14952 			 * Note: there is no interface for canceling a runout
14953 			 * callback. To prevent the driver from detaching or
14954 			 * suspending while a runout is pending the driver
14955 			 * state is set to SD_STATE_RWAIT
14956 			 *
14957 			 * Note: using the scsi_init_pkt callback facility can
14958 			 * result in an I/O request persisting at the head of
14959 			 * the list which cannot be satisfied even after
14960 			 * multiple retries. In the future the driver may
14961 			 * implement some kind of maximum runout count before
14962 			 * failing an I/O.
14963 			 *
14964 			 * Note: the use of funcp below may seem superfluous,
14965 			 * but it helps warlock figure out the correct
14966 			 * initpkt function calls (see [s]sd.wlcmd).
14967 			 */
14968 			struct scsi_pkt	*pktp;
14969 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
14970 
14971 			ASSERT(bp != un->un_rqs_bp);
14972 
14973 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
14974 			switch ((*funcp)(bp, &pktp)) {
14975 			case  SD_PKT_ALLOC_SUCCESS:
14976 				xp->xb_pktp = pktp;
14977 				SD_TRACE(SD_LOG_IO_CORE, un,
14978 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
14979 				    pktp);
14980 				goto got_pkt;
14981 
14982 			case SD_PKT_ALLOC_FAILURE:
14983 				/*
14984 				 * Temporary (hopefully) resource depletion.
14985 				 * Since retries and RQS commands always have a
14986 				 * scsi_pkt allocated, these cases should never
14987 				 * get here. So the only cases this needs to
14988 				 * handle is a bp from the waitq (which we put
14989 				 * back onto the waitq for sdrunout), or a bp
14990 				 * sent as an immed_bp (which we just fail).
14991 				 */
14992 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14993 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
14994 
14995 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
14996 
14997 				if (bp == immed_bp) {
14998 					/*
14999 					 * If SD_XB_DMA_FREED is clear, then
15000 					 * this is a failure to allocate a
15001 					 * scsi_pkt, and we must fail the
15002 					 * command.
15003 					 */
15004 					if ((xp->xb_pkt_flags &
15005 					    SD_XB_DMA_FREED) == 0) {
15006 						break;
15007 					}
15008 
15009 					/*
15010 					 * If this immediate command is NOT our
15011 					 * un_retry_bp, then we must fail it.
15012 					 */
15013 					if (bp != un->un_retry_bp) {
15014 						break;
15015 					}
15016 
15017 					/*
15018 					 * We get here if this cmd is our
15019 					 * un_retry_bp that was DMAFREED, but
15020 					 * scsi_init_pkt() failed to reallocate
15021 					 * DMA resources when we attempted to
15022 					 * retry it. This can happen when an
15023 					 * mpxio failover is in progress, but
15024 					 * we don't want to just fail the
15025 					 * command in this case.
15026 					 *
15027 					 * Use timeout(9F) to restart it after
15028 					 * a 100ms delay.  We don't want to
15029 					 * let sdrunout() restart it, because
15030 					 * sdrunout() is just supposed to start
15031 					 * commands that are sitting on the
15032 					 * wait queue.  The un_retry_bp stays
15033 					 * set until the command completes, but
15034 					 * sdrunout can be called many times
15035 					 * before that happens.  Since sdrunout
15036 					 * cannot tell if the un_retry_bp is
15037 					 * already in the transport, it could
15038 					 * end up calling scsi_transport() for
15039 					 * the un_retry_bp multiple times.
15040 					 *
15041 					 * Also: don't schedule the callback
15042 					 * if some other callback is already
15043 					 * pending.
15044 					 */
15045 					if (un->un_retry_statp == NULL) {
15046 						/*
15047 						 * restore the kstat pointer to
15048 						 * keep kstat counts coherent
15049 						 * when we do retry the command.
15050 						 */
15051 						un->un_retry_statp =
15052 						    saved_statp;
15053 					}
15054 
15055 					if ((un->un_startstop_timeid == NULL) &&
15056 					    (un->un_retry_timeid == NULL) &&
15057 					    (un->un_direct_priority_timeid ==
15058 					    NULL)) {
15059 
15060 						un->un_retry_timeid =
15061 						    timeout(
15062 						    sd_start_retry_command,
15063 						    un, SD_RESTART_TIMEOUT);
15064 					}
15065 					goto exit;
15066 				}
15067 
15068 #else
15069 				if (bp == immed_bp) {
15070 					break;	/* Just fail the command */
15071 				}
15072 #endif
15073 
15074 				/* Add the buf back to the head of the waitq */
15075 				bp->av_forw = un->un_waitq_headp;
15076 				un->un_waitq_headp = bp;
15077 				if (un->un_waitq_tailp == NULL) {
15078 					un->un_waitq_tailp = bp;
15079 				}
15080 				goto exit;
15081 
15082 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
15083 				/*
15084 				 * HBA DMA resource failure. Fail the command
15085 				 * and continue processing of the queues.
15086 				 */
15087 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15088 				    "sd_start_cmds: "
15089 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
15090 				break;
15091 
15092 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
15093 				/*
15094 				 * Note:x86: Partial DMA mapping not supported
15095 				 * for USCSI commands, and all the needed DMA
15096 				 * resources were not allocated.
15097 				 */
15098 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15099 				    "sd_start_cmds: "
15100 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
15101 				break;
15102 
15103 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
15104 				/*
15105 				 * Note:x86: Request cannot fit into CDB based
15106 				 * on lba and len.
15107 				 */
15108 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15109 				    "sd_start_cmds: "
15110 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
15111 				break;
15112 
15113 			default:
15114 				/* Should NEVER get here! */
15115 				panic("scsi_initpkt error");
15116 				/*NOTREACHED*/
15117 			}
15118 
15119 			/*
15120 			 * Fatal error in allocating a scsi_pkt for this buf.
15121 			 * Update kstats & return the buf with an error code.
15122 			 * We must use sd_return_failed_command_no_restart() to
15123 			 * avoid a recursive call back into sd_start_cmds().
15124 			 * However this also means that we must keep processing
15125 			 * the waitq here in order to avoid stalling.
15126 			 */
15127 			if (statp == kstat_waitq_to_runq) {
15128 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
15129 			}
15130 			sd_return_failed_command_no_restart(un, bp, EIO);
15131 			if (bp == immed_bp) {
15132 				/* immed_bp is gone by now, so clear this */
15133 				immed_bp = NULL;
15134 			}
15135 			continue;
15136 		}
15137 got_pkt:
15138 		if (bp == immed_bp) {
15139 			/* goto the head of the class.... */
15140 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15141 		}
15142 
15143 		un->un_ncmds_in_transport++;
15144 		SD_UPDATE_KSTATS(un, statp, bp);
15145 
15146 		/*
15147 		 * Call scsi_transport() to send the command to the target.
15148 		 * According to SCSA architecture, we must drop the mutex here
15149 		 * before calling scsi_transport() in order to avoid deadlock.
15150 		 * Note that the scsi_pkt's completion routine can be executed
15151 		 * (from interrupt context) even before the call to
15152 		 * scsi_transport() returns.
15153 		 */
15154 		SD_TRACE(SD_LOG_IO_CORE, un,
15155 		    "sd_start_cmds: calling scsi_transport()\n");
15156 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
15157 
15158 		mutex_exit(SD_MUTEX(un));
15159 		rval = scsi_transport(xp->xb_pktp);
15160 		mutex_enter(SD_MUTEX(un));
15161 
15162 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15163 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
15164 
15165 		switch (rval) {
15166 		case TRAN_ACCEPT:
15167 			/* Clear this with every pkt accepted by the HBA */
15168 			un->un_tran_fatal_count = 0;
15169 			break;	/* Success; try the next cmd (if any) */
15170 
15171 		case TRAN_BUSY:
15172 			un->un_ncmds_in_transport--;
15173 			ASSERT(un->un_ncmds_in_transport >= 0);
15174 
15175 			/*
15176 			 * Don't retry request sense, the sense data
15177 			 * is lost when another request is sent.
15178 			 * Free up the rqs buf and retry
15179 			 * the original failed cmd.  Update kstat.
15180 			 */
15181 			if (bp == un->un_rqs_bp) {
15182 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15183 				bp = sd_mark_rqs_idle(un, xp);
15184 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15185 				    NULL, NULL, EIO, un->un_busy_timeout / 500,
15186 				    kstat_waitq_enter);
15187 				goto exit;
15188 			}
15189 
15190 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
15191 			/*
15192 			 * Free the DMA resources for the  scsi_pkt. This will
15193 			 * allow mpxio to select another path the next time
15194 			 * we call scsi_transport() with this scsi_pkt.
15195 			 * See sdintr() for the rationalization behind this.
15196 			 */
15197 			if ((un->un_f_is_fibre == TRUE) &&
15198 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15199 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
15200 				scsi_dmafree(xp->xb_pktp);
15201 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15202 			}
15203 #endif
15204 
15205 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
15206 				/*
15207 				 * Commands that are SD_PATH_DIRECT_PRIORITY
15208 				 * are for error recovery situations. These do
15209 				 * not use the normal command waitq, so if they
15210 				 * get a TRAN_BUSY we cannot put them back onto
15211 				 * the waitq for later retry. One possible
15212 				 * problem is that there could already be some
15213 				 * other command on un_retry_bp that is waiting
15214 				 * for this one to complete, so we would be
15215 				 * deadlocked if we put this command back onto
15216 				 * the waitq for later retry (since un_retry_bp
15217 				 * must complete before the driver gets back to
15218 				 * commands on the waitq).
15219 				 *
15220 				 * To avoid deadlock we must schedule a callback
15221 				 * that will restart this command after a set
15222 				 * interval.  This should keep retrying for as
15223 				 * long as the underlying transport keeps
15224 				 * returning TRAN_BUSY (just like for other
15225 				 * commands).  Use the same timeout interval as
15226 				 * for the ordinary TRAN_BUSY retry.
15227 				 */
15228 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15229 				    "sd_start_cmds: scsi_transport() returned "
15230 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
15231 
15232 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15233 				un->un_direct_priority_timeid =
15234 				    timeout(sd_start_direct_priority_command,
15235 				    bp, un->un_busy_timeout / 500);
15236 
15237 				goto exit;
15238 			}
15239 
15240 			/*
15241 			 * For TRAN_BUSY, we want to reduce the throttle value,
15242 			 * unless we are retrying a command.
15243 			 */
15244 			if (bp != un->un_retry_bp) {
15245 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
15246 			}
15247 
15248 			/*
15249 			 * Set up the bp to be tried again 10 ms later.
15250 			 * Note:x86: Is there a timeout value in the sd_lun
15251 			 * for this condition?
15252 			 */
15253 			sd_set_retry_bp(un, bp, un->un_busy_timeout / 500,
15254 			    kstat_runq_back_to_waitq);
15255 			goto exit;
15256 
15257 		case TRAN_FATAL_ERROR:
15258 			un->un_tran_fatal_count++;
15259 			/* FALLTHRU */
15260 
15261 		case TRAN_BADPKT:
15262 		default:
15263 			un->un_ncmds_in_transport--;
15264 			ASSERT(un->un_ncmds_in_transport >= 0);
15265 
15266 			/*
15267 			 * If this is our REQUEST SENSE command with a
15268 			 * transport error, we must get back the pointers
15269 			 * to the original buf, and mark the REQUEST
15270 			 * SENSE command as "available".
15271 			 */
15272 			if (bp == un->un_rqs_bp) {
15273 				bp = sd_mark_rqs_idle(un, xp);
15274 				xp = SD_GET_XBUF(bp);
15275 			} else {
15276 				/*
15277 				 * Legacy behavior: do not update transport
15278 				 * error count for request sense commands.
15279 				 */
15280 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
15281 			}
15282 
15283 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15284 			sd_print_transport_rejected_message(un, xp, rval);
15285 
15286 			/*
15287 			 * This command will be terminated by SD driver due
15288 			 * to a fatal transport error. We should post
15289 			 * ereport.io.scsi.cmd.disk.tran with driver-assessment
15290 			 * of "fail" for any command to indicate this
15291 			 * situation.
15292 			 */
15293 			if (xp->xb_ena > 0) {
15294 				ASSERT(un->un_fm_private != NULL);
15295 				sfip = un->un_fm_private;
15296 				sfip->fm_ssc.ssc_flags |= SSC_FLAGS_TRAN_ABORT;
15297 				sd_ssc_extract_info(&sfip->fm_ssc, un,
15298 				    xp->xb_pktp, bp, xp);
15299 				sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15300 			}
15301 
15302 			/*
15303 			 * We must use sd_return_failed_command_no_restart() to
15304 			 * avoid a recursive call back into sd_start_cmds().
15305 			 * However this also means that we must keep processing
15306 			 * the waitq here in order to avoid stalling.
15307 			 */
15308 			sd_return_failed_command_no_restart(un, bp, EIO);
15309 
15310 			/*
15311 			 * Notify any threads waiting in sd_ddi_suspend() that
15312 			 * a command completion has occurred.
15313 			 */
15314 			if (un->un_state == SD_STATE_SUSPENDED) {
15315 				cv_broadcast(&un->un_disk_busy_cv);
15316 			}
15317 
15318 			if (bp == immed_bp) {
15319 				/* immed_bp is gone by now, so clear this */
15320 				immed_bp = NULL;
15321 			}
15322 			break;
15323 		}
15324 
15325 	} while (immed_bp == NULL);
15326 
15327 exit:
15328 	ASSERT(mutex_owned(SD_MUTEX(un)));
15329 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
15330 }
15331 
15332 
15333 /*
15334  *    Function: sd_return_command
15335  *
15336  * Description: Returns a command to its originator (with or without an
15337  *		error).  Also starts commands waiting to be transported
15338  *		to the target.
15339  *
15340  *     Context: May be called from interrupt, kernel, or timeout context
15341  */
15342 
15343 static void
15344 sd_return_command(struct sd_lun *un, struct buf *bp)
15345 {
15346 	struct sd_xbuf *xp;
15347 	struct scsi_pkt *pktp;
15348 	struct sd_fm_internal *sfip;
15349 
15350 	ASSERT(bp != NULL);
15351 	ASSERT(un != NULL);
15352 	ASSERT(mutex_owned(SD_MUTEX(un)));
15353 	ASSERT(bp != un->un_rqs_bp);
15354 	xp = SD_GET_XBUF(bp);
15355 	ASSERT(xp != NULL);
15356 
15357 	pktp = SD_GET_PKTP(bp);
15358 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15359 	ASSERT(sfip != NULL);
15360 
15361 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
15362 
15363 	/*
15364 	 * Note: check for the "sdrestart failed" case.
15365 	 */
15366 	if ((un->un_partial_dma_supported == 1) &&
15367 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
15368 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
15369 	    (xp->xb_pktp->pkt_resid == 0)) {
15370 
15371 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
15372 			/*
15373 			 * Successfully set up next portion of cmd
15374 			 * transfer, try sending it
15375 			 */
15376 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15377 			    NULL, NULL, 0, (clock_t)0, NULL);
15378 			sd_start_cmds(un, NULL);
15379 			return;	/* Note:x86: need a return here? */
15380 		}
15381 	}
15382 
15383 	/*
15384 	 * If this is the failfast bp, clear it from un_failfast_bp. This
15385 	 * can happen if upon being re-tried the failfast bp either
15386 	 * succeeded or encountered another error (possibly even a different
15387 	 * error than the one that precipitated the failfast state, but in
15388 	 * that case it would have had to exhaust retries as well). Regardless,
15389 	 * this should not occur whenever the instance is in the active
15390 	 * failfast state.
15391 	 */
15392 	if (bp == un->un_failfast_bp) {
15393 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15394 		un->un_failfast_bp = NULL;
15395 	}
15396 
15397 	/*
15398 	 * Clear the failfast state upon successful completion of ANY cmd.
15399 	 */
15400 	if (bp->b_error == 0) {
15401 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15402 		/*
15403 		 * If this is a successful command, but used to be retried,
15404 		 * we will take it as a recovered command and post an
15405 		 * ereport with driver-assessment of "recovered".
15406 		 */
15407 		if (xp->xb_ena > 0) {
15408 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15409 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RECOVERY);
15410 		}
15411 	} else {
15412 		/*
15413 		 * If this is a failed non-USCSI command we will post an
15414 		 * ereport with driver-assessment set accordingly("fail" or
15415 		 * "fatal").
15416 		 */
15417 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15418 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15419 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15420 		}
15421 	}
15422 
15423 	/*
15424 	 * This is used if the command was retried one or more times. Show that
15425 	 * we are done with it, and allow processing of the waitq to resume.
15426 	 */
15427 	if (bp == un->un_retry_bp) {
15428 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15429 		    "sd_return_command: un:0x%p: "
15430 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15431 		un->un_retry_bp = NULL;
15432 		un->un_retry_statp = NULL;
15433 	}
15434 
15435 	SD_UPDATE_RDWR_STATS(un, bp);
15436 	SD_UPDATE_PARTITION_STATS(un, bp);
15437 
15438 	switch (un->un_state) {
15439 	case SD_STATE_SUSPENDED:
15440 		/*
15441 		 * Notify any threads waiting in sd_ddi_suspend() that
15442 		 * a command completion has occurred.
15443 		 */
15444 		cv_broadcast(&un->un_disk_busy_cv);
15445 		break;
15446 	default:
15447 		sd_start_cmds(un, NULL);
15448 		break;
15449 	}
15450 
15451 	/* Return this command up the iodone chain to its originator. */
15452 	mutex_exit(SD_MUTEX(un));
15453 
15454 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15455 	xp->xb_pktp = NULL;
15456 
15457 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15458 
15459 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15460 	mutex_enter(SD_MUTEX(un));
15461 
15462 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
15463 }
15464 
15465 
15466 /*
15467  *    Function: sd_return_failed_command
15468  *
15469  * Description: Command completion when an error occurred.
15470  *
15471  *     Context: May be called from interrupt context
15472  */
15473 
15474 static void
15475 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
15476 {
15477 	ASSERT(bp != NULL);
15478 	ASSERT(un != NULL);
15479 	ASSERT(mutex_owned(SD_MUTEX(un)));
15480 
15481 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15482 	    "sd_return_failed_command: entry\n");
15483 
15484 	/*
15485 	 * b_resid could already be nonzero due to a partial data
15486 	 * transfer, so do not change it here.
15487 	 */
15488 	SD_BIOERROR(bp, errcode);
15489 
15490 	sd_return_command(un, bp);
15491 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15492 	    "sd_return_failed_command: exit\n");
15493 }
15494 
15495 
15496 /*
15497  *    Function: sd_return_failed_command_no_restart
15498  *
15499  * Description: Same as sd_return_failed_command, but ensures that no
15500  *		call back into sd_start_cmds will be issued.
15501  *
15502  *     Context: May be called from interrupt context
15503  */
15504 
15505 static void
15506 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
15507 	int errcode)
15508 {
15509 	struct sd_xbuf *xp;
15510 
15511 	ASSERT(bp != NULL);
15512 	ASSERT(un != NULL);
15513 	ASSERT(mutex_owned(SD_MUTEX(un)));
15514 	xp = SD_GET_XBUF(bp);
15515 	ASSERT(xp != NULL);
15516 	ASSERT(errcode != 0);
15517 
15518 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15519 	    "sd_return_failed_command_no_restart: entry\n");
15520 
15521 	/*
15522 	 * b_resid could already be nonzero due to a partial data
15523 	 * transfer, so do not change it here.
15524 	 */
15525 	SD_BIOERROR(bp, errcode);
15526 
15527 	/*
15528 	 * If this is the failfast bp, clear it. This can happen if the
15529 	 * failfast bp encounterd a fatal error when we attempted to
15530 	 * re-try it (such as a scsi_transport(9F) failure).  However
15531 	 * we should NOT be in an active failfast state if the failfast
15532 	 * bp is not NULL.
15533 	 */
15534 	if (bp == un->un_failfast_bp) {
15535 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15536 		un->un_failfast_bp = NULL;
15537 	}
15538 
15539 	if (bp == un->un_retry_bp) {
15540 		/*
15541 		 * This command was retried one or more times. Show that we are
15542 		 * done with it, and allow processing of the waitq to resume.
15543 		 */
15544 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15545 		    "sd_return_failed_command_no_restart: "
15546 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15547 		un->un_retry_bp = NULL;
15548 		un->un_retry_statp = NULL;
15549 	}
15550 
15551 	SD_UPDATE_RDWR_STATS(un, bp);
15552 	SD_UPDATE_PARTITION_STATS(un, bp);
15553 
15554 	mutex_exit(SD_MUTEX(un));
15555 
15556 	if (xp->xb_pktp != NULL) {
15557 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15558 		xp->xb_pktp = NULL;
15559 	}
15560 
15561 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15562 
15563 	mutex_enter(SD_MUTEX(un));
15564 
15565 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15566 	    "sd_return_failed_command_no_restart: exit\n");
15567 }
15568 
15569 
15570 /*
15571  *    Function: sd_retry_command
15572  *
15573  * Description: queue up a command for retry, or (optionally) fail it
15574  *		if retry counts are exhausted.
15575  *
15576  *   Arguments: un - Pointer to the sd_lun struct for the target.
15577  *
15578  *		bp - Pointer to the buf for the command to be retried.
15579  *
15580  *		retry_check_flag - Flag to see which (if any) of the retry
15581  *		   counts should be decremented/checked. If the indicated
15582  *		   retry count is exhausted, then the command will not be
15583  *		   retried; it will be failed instead. This should use a
15584  *		   value equal to one of the following:
15585  *
15586  *			SD_RETRIES_NOCHECK
15587  *			SD_RESD_RETRIES_STANDARD
15588  *			SD_RETRIES_VICTIM
15589  *
15590  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
15591  *		   if the check should be made to see of FLAG_ISOLATE is set
15592  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
15593  *		   not retried, it is simply failed.
15594  *
15595  *		user_funcp - Ptr to function to call before dispatching the
15596  *		   command. May be NULL if no action needs to be performed.
15597  *		   (Primarily intended for printing messages.)
15598  *
15599  *		user_arg - Optional argument to be passed along to
15600  *		   the user_funcp call.
15601  *
15602  *		failure_code - errno return code to set in the bp if the
15603  *		   command is going to be failed.
15604  *
15605  *		retry_delay - Retry delay interval in (clock_t) units. May
15606  *		   be zero which indicates that the retry should be retried
15607  *		   immediately (ie, without an intervening delay).
15608  *
15609  *		statp - Ptr to kstat function to be updated if the command
15610  *		   is queued for a delayed retry. May be NULL if no kstat
15611  *		   update is desired.
15612  *
15613  *     Context: May be called from interrupt context.
15614  */
15615 
15616 static void
15617 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
15618 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
15619 	code), void *user_arg, int failure_code,  clock_t retry_delay,
15620 	void (*statp)(kstat_io_t *))
15621 {
15622 	struct sd_xbuf	*xp;
15623 	struct scsi_pkt	*pktp;
15624 	struct sd_fm_internal *sfip;
15625 
15626 	ASSERT(un != NULL);
15627 	ASSERT(mutex_owned(SD_MUTEX(un)));
15628 	ASSERT(bp != NULL);
15629 	xp = SD_GET_XBUF(bp);
15630 	ASSERT(xp != NULL);
15631 	pktp = SD_GET_PKTP(bp);
15632 	ASSERT(pktp != NULL);
15633 
15634 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15635 	ASSERT(sfip != NULL);
15636 
15637 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15638 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
15639 
15640 	/*
15641 	 * If we are syncing or dumping, fail the command to avoid
15642 	 * recursively calling back into scsi_transport().
15643 	 */
15644 	if (ddi_in_panic()) {
15645 		goto fail_command_no_log;
15646 	}
15647 
15648 	/*
15649 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
15650 	 * log an error and fail the command.
15651 	 */
15652 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15653 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
15654 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
15655 		sd_dump_memory(un, SD_LOG_IO, "CDB",
15656 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15657 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15658 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15659 		goto fail_command;
15660 	}
15661 
15662 	/*
15663 	 * If we are suspended, then put the command onto head of the
15664 	 * wait queue since we don't want to start more commands, and
15665 	 * clear the un_retry_bp. Next time when we are resumed, will
15666 	 * handle the command in the wait queue.
15667 	 */
15668 	switch (un->un_state) {
15669 	case SD_STATE_SUSPENDED:
15670 	case SD_STATE_DUMPING:
15671 		bp->av_forw = un->un_waitq_headp;
15672 		un->un_waitq_headp = bp;
15673 		if (un->un_waitq_tailp == NULL) {
15674 			un->un_waitq_tailp = bp;
15675 		}
15676 		if (bp == un->un_retry_bp) {
15677 			un->un_retry_bp = NULL;
15678 			un->un_retry_statp = NULL;
15679 		}
15680 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15681 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15682 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15683 		return;
15684 	default:
15685 		break;
15686 	}
15687 
15688 	/*
15689 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15690 	 * is set; if it is then we do not want to retry the command.
15691 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15692 	 */
15693 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15694 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15695 			goto fail_command;
15696 		}
15697 	}
15698 
15699 
15700 	/*
15701 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15702 	 * command timeout or a selection timeout has occurred. This means
15703 	 * that we were unable to establish an kind of communication with
15704 	 * the target, and subsequent retries and/or commands are likely
15705 	 * to encounter similar results and take a long time to complete.
15706 	 *
15707 	 * If this is a failfast error condition, we need to update the
15708 	 * failfast state, even if this bp does not have B_FAILFAST set.
15709 	 */
15710 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15711 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15712 			ASSERT(un->un_failfast_bp == NULL);
15713 			/*
15714 			 * If we are already in the active failfast state, and
15715 			 * another failfast error condition has been detected,
15716 			 * then fail this command if it has B_FAILFAST set.
15717 			 * If B_FAILFAST is clear, then maintain the legacy
15718 			 * behavior of retrying heroically, even tho this will
15719 			 * take a lot more time to fail the command.
15720 			 */
15721 			if (bp->b_flags & B_FAILFAST) {
15722 				goto fail_command;
15723 			}
15724 		} else {
15725 			/*
15726 			 * We're not in the active failfast state, but we
15727 			 * have a failfast error condition, so we must begin
15728 			 * transition to the next state. We do this regardless
15729 			 * of whether or not this bp has B_FAILFAST set.
15730 			 */
15731 			if (un->un_failfast_bp == NULL) {
15732 				/*
15733 				 * This is the first bp to meet a failfast
15734 				 * condition so save it on un_failfast_bp &
15735 				 * do normal retry processing. Do not enter
15736 				 * active failfast state yet. This marks
15737 				 * entry into the "failfast pending" state.
15738 				 */
15739 				un->un_failfast_bp = bp;
15740 
15741 			} else if (un->un_failfast_bp == bp) {
15742 				/*
15743 				 * This is the second time *this* bp has
15744 				 * encountered a failfast error condition,
15745 				 * so enter active failfast state & flush
15746 				 * queues as appropriate.
15747 				 */
15748 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15749 				un->un_failfast_bp = NULL;
15750 				sd_failfast_flushq(un);
15751 
15752 				/*
15753 				 * Fail this bp now if B_FAILFAST set;
15754 				 * otherwise continue with retries. (It would
15755 				 * be pretty ironic if this bp succeeded on a
15756 				 * subsequent retry after we just flushed all
15757 				 * the queues).
15758 				 */
15759 				if (bp->b_flags & B_FAILFAST) {
15760 					goto fail_command;
15761 				}
15762 
15763 #if !defined(lint) && !defined(__lint)
15764 			} else {
15765 				/*
15766 				 * If neither of the preceeding conditionals
15767 				 * was true, it means that there is some
15768 				 * *other* bp that has met an inital failfast
15769 				 * condition and is currently either being
15770 				 * retried or is waiting to be retried. In
15771 				 * that case we should perform normal retry
15772 				 * processing on *this* bp, since there is a
15773 				 * chance that the current failfast condition
15774 				 * is transient and recoverable. If that does
15775 				 * not turn out to be the case, then retries
15776 				 * will be cleared when the wait queue is
15777 				 * flushed anyway.
15778 				 */
15779 #endif
15780 			}
15781 		}
15782 	} else {
15783 		/*
15784 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15785 		 * likely were able to at least establish some level of
15786 		 * communication with the target and subsequent commands
15787 		 * and/or retries are likely to get through to the target,
15788 		 * In this case we want to be aggressive about clearing
15789 		 * the failfast state. Note that this does not affect
15790 		 * the "failfast pending" condition.
15791 		 */
15792 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15793 	}
15794 
15795 
15796 	/*
15797 	 * Check the specified retry count to see if we can still do
15798 	 * any retries with this pkt before we should fail it.
15799 	 */
15800 	switch (retry_check_flag & SD_RETRIES_MASK) {
15801 	case SD_RETRIES_VICTIM:
15802 		/*
15803 		 * Check the victim retry count. If exhausted, then fall
15804 		 * thru & check against the standard retry count.
15805 		 */
15806 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15807 			/* Increment count & proceed with the retry */
15808 			xp->xb_victim_retry_count++;
15809 			break;
15810 		}
15811 		/* Victim retries exhausted, fall back to std. retries... */
15812 		/* FALLTHRU */
15813 
15814 	case SD_RETRIES_STANDARD:
15815 		if (xp->xb_retry_count >= un->un_retry_count) {
15816 			/* Retries exhausted, fail the command */
15817 			SD_TRACE(SD_LOG_IO_CORE, un,
15818 			    "sd_retry_command: retries exhausted!\n");
15819 			/*
15820 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15821 			 * commands with nonzero pkt_resid.
15822 			 */
15823 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15824 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15825 			    (pktp->pkt_resid != 0)) {
15826 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15827 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15828 					SD_UPDATE_B_RESID(bp, pktp);
15829 				}
15830 			}
15831 			goto fail_command;
15832 		}
15833 		xp->xb_retry_count++;
15834 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15835 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15836 		break;
15837 
15838 	case SD_RETRIES_UA:
15839 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15840 			/* Retries exhausted, fail the command */
15841 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15842 			    "Unit Attention retries exhausted. "
15843 			    "Check the target.\n");
15844 			goto fail_command;
15845 		}
15846 		xp->xb_ua_retry_count++;
15847 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15848 		    "sd_retry_command: retry count:%d\n",
15849 		    xp->xb_ua_retry_count);
15850 		break;
15851 
15852 	case SD_RETRIES_BUSY:
15853 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15854 			/* Retries exhausted, fail the command */
15855 			SD_TRACE(SD_LOG_IO_CORE, un,
15856 			    "sd_retry_command: retries exhausted!\n");
15857 			goto fail_command;
15858 		}
15859 		xp->xb_retry_count++;
15860 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15861 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15862 		break;
15863 
15864 	case SD_RETRIES_NOCHECK:
15865 	default:
15866 		/* No retry count to check. Just proceed with the retry */
15867 		break;
15868 	}
15869 
15870 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15871 
15872 	/*
15873 	 * If this is a non-USCSI command being retried
15874 	 * during execution last time, we should post an ereport with
15875 	 * driver-assessment of the value "retry".
15876 	 * For partial DMA, request sense and STATUS_QFULL, there are no
15877 	 * hardware errors, we bypass ereport posting.
15878 	 */
15879 	if (failure_code != 0) {
15880 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15881 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15882 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RETRY);
15883 		}
15884 	}
15885 
15886 	/*
15887 	 * If we were given a zero timeout, we must attempt to retry the
15888 	 * command immediately (ie, without a delay).
15889 	 */
15890 	if (retry_delay == 0) {
15891 		/*
15892 		 * Check some limiting conditions to see if we can actually
15893 		 * do the immediate retry.  If we cannot, then we must
15894 		 * fall back to queueing up a delayed retry.
15895 		 */
15896 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15897 			/*
15898 			 * We are at the throttle limit for the target,
15899 			 * fall back to delayed retry.
15900 			 */
15901 			retry_delay = un->un_busy_timeout;
15902 			statp = kstat_waitq_enter;
15903 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15904 			    "sd_retry_command: immed. retry hit "
15905 			    "throttle!\n");
15906 		} else {
15907 			/*
15908 			 * We're clear to proceed with the immediate retry.
15909 			 * First call the user-provided function (if any)
15910 			 */
15911 			if (user_funcp != NULL) {
15912 				(*user_funcp)(un, bp, user_arg,
15913 				    SD_IMMEDIATE_RETRY_ISSUED);
15914 #ifdef __lock_lint
15915 				sd_print_incomplete_msg(un, bp, user_arg,
15916 				    SD_IMMEDIATE_RETRY_ISSUED);
15917 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15918 				    SD_IMMEDIATE_RETRY_ISSUED);
15919 				sd_print_sense_failed_msg(un, bp, user_arg,
15920 				    SD_IMMEDIATE_RETRY_ISSUED);
15921 #endif
15922 			}
15923 
15924 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15925 			    "sd_retry_command: issuing immediate retry\n");
15926 
15927 			/*
15928 			 * Call sd_start_cmds() to transport the command to
15929 			 * the target.
15930 			 */
15931 			sd_start_cmds(un, bp);
15932 
15933 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15934 			    "sd_retry_command exit\n");
15935 			return;
15936 		}
15937 	}
15938 
15939 	/*
15940 	 * Set up to retry the command after a delay.
15941 	 * First call the user-provided function (if any)
15942 	 */
15943 	if (user_funcp != NULL) {
15944 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
15945 	}
15946 
15947 	sd_set_retry_bp(un, bp, retry_delay, statp);
15948 
15949 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15950 	return;
15951 
15952 fail_command:
15953 
15954 	if (user_funcp != NULL) {
15955 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
15956 	}
15957 
15958 fail_command_no_log:
15959 
15960 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15961 	    "sd_retry_command: returning failed command\n");
15962 
15963 	sd_return_failed_command(un, bp, failure_code);
15964 
15965 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15966 }
15967 
15968 
15969 /*
15970  *    Function: sd_set_retry_bp
15971  *
15972  * Description: Set up the given bp for retry.
15973  *
15974  *   Arguments: un - ptr to associated softstate
15975  *		bp - ptr to buf(9S) for the command
15976  *		retry_delay - time interval before issuing retry (may be 0)
15977  *		statp - optional pointer to kstat function
15978  *
15979  *     Context: May be called under interrupt context
15980  */
15981 
15982 static void
15983 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
15984 	void (*statp)(kstat_io_t *))
15985 {
15986 	ASSERT(un != NULL);
15987 	ASSERT(mutex_owned(SD_MUTEX(un)));
15988 	ASSERT(bp != NULL);
15989 
15990 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15991 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
15992 
15993 	/*
15994 	 * Indicate that the command is being retried. This will not allow any
15995 	 * other commands on the wait queue to be transported to the target
15996 	 * until this command has been completed (success or failure). The
15997 	 * "retry command" is not transported to the target until the given
15998 	 * time delay expires, unless the user specified a 0 retry_delay.
15999 	 *
16000 	 * Note: the timeout(9F) callback routine is what actually calls
16001 	 * sd_start_cmds() to transport the command, with the exception of a
16002 	 * zero retry_delay. The only current implementor of a zero retry delay
16003 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
16004 	 */
16005 	if (un->un_retry_bp == NULL) {
16006 		ASSERT(un->un_retry_statp == NULL);
16007 		un->un_retry_bp = bp;
16008 
16009 		/*
16010 		 * If the user has not specified a delay the command should
16011 		 * be queued and no timeout should be scheduled.
16012 		 */
16013 		if (retry_delay == 0) {
16014 			/*
16015 			 * Save the kstat pointer that will be used in the
16016 			 * call to SD_UPDATE_KSTATS() below, so that
16017 			 * sd_start_cmds() can correctly decrement the waitq
16018 			 * count when it is time to transport this command.
16019 			 */
16020 			un->un_retry_statp = statp;
16021 			goto done;
16022 		}
16023 	}
16024 
16025 	if (un->un_retry_bp == bp) {
16026 		/*
16027 		 * Save the kstat pointer that will be used in the call to
16028 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
16029 		 * correctly decrement the waitq count when it is time to
16030 		 * transport this command.
16031 		 */
16032 		un->un_retry_statp = statp;
16033 
16034 		/*
16035 		 * Schedule a timeout if:
16036 		 *   1) The user has specified a delay.
16037 		 *   2) There is not a START_STOP_UNIT callback pending.
16038 		 *
16039 		 * If no delay has been specified, then it is up to the caller
16040 		 * to ensure that IO processing continues without stalling.
16041 		 * Effectively, this means that the caller will issue the
16042 		 * required call to sd_start_cmds(). The START_STOP_UNIT
16043 		 * callback does this after the START STOP UNIT command has
16044 		 * completed. In either of these cases we should not schedule
16045 		 * a timeout callback here.  Also don't schedule the timeout if
16046 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
16047 		 */
16048 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
16049 		    (un->un_direct_priority_timeid == NULL)) {
16050 			un->un_retry_timeid =
16051 			    timeout(sd_start_retry_command, un, retry_delay);
16052 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16053 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
16054 			    " bp:0x%p un_retry_timeid:0x%p\n",
16055 			    un, bp, un->un_retry_timeid);
16056 		}
16057 	} else {
16058 		/*
16059 		 * We only get in here if there is already another command
16060 		 * waiting to be retried.  In this case, we just put the
16061 		 * given command onto the wait queue, so it can be transported
16062 		 * after the current retry command has completed.
16063 		 *
16064 		 * Also we have to make sure that if the command at the head
16065 		 * of the wait queue is the un_failfast_bp, that we do not
16066 		 * put ahead of it any other commands that are to be retried.
16067 		 */
16068 		if ((un->un_failfast_bp != NULL) &&
16069 		    (un->un_failfast_bp == un->un_waitq_headp)) {
16070 			/*
16071 			 * Enqueue this command AFTER the first command on
16072 			 * the wait queue (which is also un_failfast_bp).
16073 			 */
16074 			bp->av_forw = un->un_waitq_headp->av_forw;
16075 			un->un_waitq_headp->av_forw = bp;
16076 			if (un->un_waitq_headp == un->un_waitq_tailp) {
16077 				un->un_waitq_tailp = bp;
16078 			}
16079 		} else {
16080 			/* Enqueue this command at the head of the waitq. */
16081 			bp->av_forw = un->un_waitq_headp;
16082 			un->un_waitq_headp = bp;
16083 			if (un->un_waitq_tailp == NULL) {
16084 				un->un_waitq_tailp = bp;
16085 			}
16086 		}
16087 
16088 		if (statp == NULL) {
16089 			statp = kstat_waitq_enter;
16090 		}
16091 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16092 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
16093 	}
16094 
16095 done:
16096 	if (statp != NULL) {
16097 		SD_UPDATE_KSTATS(un, statp, bp);
16098 	}
16099 
16100 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16101 	    "sd_set_retry_bp: exit un:0x%p\n", un);
16102 }
16103 
16104 
16105 /*
16106  *    Function: sd_start_retry_command
16107  *
16108  * Description: Start the command that has been waiting on the target's
16109  *		retry queue.  Called from timeout(9F) context after the
16110  *		retry delay interval has expired.
16111  *
16112  *   Arguments: arg - pointer to associated softstate for the device.
16113  *
16114  *     Context: timeout(9F) thread context.  May not sleep.
16115  */
16116 
16117 static void
16118 sd_start_retry_command(void *arg)
16119 {
16120 	struct sd_lun *un = arg;
16121 
16122 	ASSERT(un != NULL);
16123 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16124 
16125 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16126 	    "sd_start_retry_command: entry\n");
16127 
16128 	mutex_enter(SD_MUTEX(un));
16129 
16130 	un->un_retry_timeid = NULL;
16131 
16132 	if (un->un_retry_bp != NULL) {
16133 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16134 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
16135 		    un, un->un_retry_bp);
16136 		sd_start_cmds(un, un->un_retry_bp);
16137 	}
16138 
16139 	mutex_exit(SD_MUTEX(un));
16140 
16141 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16142 	    "sd_start_retry_command: exit\n");
16143 }
16144 
16145 /*
16146  *    Function: sd_rmw_msg_print_handler
16147  *
16148  * Description: If RMW mode is enabled and warning message is triggered
16149  *              print I/O count during a fixed interval.
16150  *
16151  *   Arguments: arg - pointer to associated softstate for the device.
16152  *
16153  *     Context: timeout(9F) thread context. May not sleep.
16154  */
16155 static void
16156 sd_rmw_msg_print_handler(void *arg)
16157 {
16158 	struct sd_lun *un = arg;
16159 
16160 	ASSERT(un != NULL);
16161 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16162 
16163 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16164 	    "sd_rmw_msg_print_handler: entry\n");
16165 
16166 	mutex_enter(SD_MUTEX(un));
16167 
16168 	if (un->un_rmw_incre_count > 0) {
16169 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16170 		    "%"PRIu64" I/O requests are not aligned with %d disk "
16171 		    "sector size in %ld seconds. They are handled through "
16172 		    "Read Modify Write but the performance is very low!\n",
16173 		    un->un_rmw_incre_count, un->un_tgt_blocksize,
16174 		    drv_hztousec(SD_RMW_MSG_PRINT_TIMEOUT) / 1000000);
16175 		un->un_rmw_incre_count = 0;
16176 		un->un_rmw_msg_timeid = timeout(sd_rmw_msg_print_handler,
16177 		    un, SD_RMW_MSG_PRINT_TIMEOUT);
16178 	} else {
16179 		un->un_rmw_msg_timeid = NULL;
16180 	}
16181 
16182 	mutex_exit(SD_MUTEX(un));
16183 
16184 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16185 	    "sd_rmw_msg_print_handler: exit\n");
16186 }
16187 
16188 /*
16189  *    Function: sd_start_direct_priority_command
16190  *
16191  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
16192  *		received TRAN_BUSY when we called scsi_transport() to send it
16193  *		to the underlying HBA. This function is called from timeout(9F)
16194  *		context after the delay interval has expired.
16195  *
16196  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
16197  *
16198  *     Context: timeout(9F) thread context.  May not sleep.
16199  */
16200 
16201 static void
16202 sd_start_direct_priority_command(void *arg)
16203 {
16204 	struct buf	*priority_bp = arg;
16205 	struct sd_lun	*un;
16206 
16207 	ASSERT(priority_bp != NULL);
16208 	un = SD_GET_UN(priority_bp);
16209 	ASSERT(un != NULL);
16210 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16211 
16212 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16213 	    "sd_start_direct_priority_command: entry\n");
16214 
16215 	mutex_enter(SD_MUTEX(un));
16216 	un->un_direct_priority_timeid = NULL;
16217 	sd_start_cmds(un, priority_bp);
16218 	mutex_exit(SD_MUTEX(un));
16219 
16220 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16221 	    "sd_start_direct_priority_command: exit\n");
16222 }
16223 
16224 
16225 /*
16226  *    Function: sd_send_request_sense_command
16227  *
16228  * Description: Sends a REQUEST SENSE command to the target
16229  *
16230  *     Context: May be called from interrupt context.
16231  */
16232 
16233 static void
16234 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
16235 	struct scsi_pkt *pktp)
16236 {
16237 	ASSERT(bp != NULL);
16238 	ASSERT(un != NULL);
16239 	ASSERT(mutex_owned(SD_MUTEX(un)));
16240 
16241 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
16242 	    "entry: buf:0x%p\n", bp);
16243 
16244 	/*
16245 	 * If we are syncing or dumping, then fail the command to avoid a
16246 	 * recursive callback into scsi_transport(). Also fail the command
16247 	 * if we are suspended (legacy behavior).
16248 	 */
16249 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
16250 	    (un->un_state == SD_STATE_DUMPING)) {
16251 		sd_return_failed_command(un, bp, EIO);
16252 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16253 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
16254 		return;
16255 	}
16256 
16257 	/*
16258 	 * Retry the failed command and don't issue the request sense if:
16259 	 *    1) the sense buf is busy
16260 	 *    2) we have 1 or more outstanding commands on the target
16261 	 *    (the sense data will be cleared or invalidated any way)
16262 	 *
16263 	 * Note: There could be an issue with not checking a retry limit here,
16264 	 * the problem is determining which retry limit to check.
16265 	 */
16266 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
16267 		/* Don't retry if the command is flagged as non-retryable */
16268 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16269 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
16270 			    NULL, NULL, 0, un->un_busy_timeout,
16271 			    kstat_waitq_enter);
16272 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16273 			    "sd_send_request_sense_command: "
16274 			    "at full throttle, retrying exit\n");
16275 		} else {
16276 			sd_return_failed_command(un, bp, EIO);
16277 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16278 			    "sd_send_request_sense_command: "
16279 			    "at full throttle, non-retryable exit\n");
16280 		}
16281 		return;
16282 	}
16283 
16284 	sd_mark_rqs_busy(un, bp);
16285 	sd_start_cmds(un, un->un_rqs_bp);
16286 
16287 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16288 	    "sd_send_request_sense_command: exit\n");
16289 }
16290 
16291 
16292 /*
16293  *    Function: sd_mark_rqs_busy
16294  *
16295  * Description: Indicate that the request sense bp for this instance is
16296  *		in use.
16297  *
16298  *     Context: May be called under interrupt context
16299  */
16300 
16301 static void
16302 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
16303 {
16304 	struct sd_xbuf	*sense_xp;
16305 
16306 	ASSERT(un != NULL);
16307 	ASSERT(bp != NULL);
16308 	ASSERT(mutex_owned(SD_MUTEX(un)));
16309 	ASSERT(un->un_sense_isbusy == 0);
16310 
16311 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
16312 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
16313 
16314 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
16315 	ASSERT(sense_xp != NULL);
16316 
16317 	SD_INFO(SD_LOG_IO, un,
16318 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
16319 
16320 	ASSERT(sense_xp->xb_pktp != NULL);
16321 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
16322 	    == (FLAG_SENSING | FLAG_HEAD));
16323 
16324 	un->un_sense_isbusy = 1;
16325 	un->un_rqs_bp->b_resid = 0;
16326 	sense_xp->xb_pktp->pkt_resid  = 0;
16327 	sense_xp->xb_pktp->pkt_reason = 0;
16328 
16329 	/* So we can get back the bp at interrupt time! */
16330 	sense_xp->xb_sense_bp = bp;
16331 
16332 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
16333 
16334 	/*
16335 	 * Mark this buf as awaiting sense data. (This is already set in
16336 	 * the pkt_flags for the RQS packet.)
16337 	 */
16338 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
16339 
16340 	/* Request sense down same path */
16341 	if (scsi_pkt_allocated_correctly((SD_GET_XBUF(bp))->xb_pktp) &&
16342 	    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance)
16343 		sense_xp->xb_pktp->pkt_path_instance =
16344 		    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance;
16345 
16346 	sense_xp->xb_retry_count	= 0;
16347 	sense_xp->xb_victim_retry_count = 0;
16348 	sense_xp->xb_ua_retry_count	= 0;
16349 	sense_xp->xb_nr_retry_count 	= 0;
16350 	sense_xp->xb_dma_resid  = 0;
16351 
16352 	/* Clean up the fields for auto-request sense */
16353 	sense_xp->xb_sense_status = 0;
16354 	sense_xp->xb_sense_state  = 0;
16355 	sense_xp->xb_sense_resid  = 0;
16356 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
16357 
16358 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
16359 }
16360 
16361 
16362 /*
16363  *    Function: sd_mark_rqs_idle
16364  *
16365  * Description: SD_MUTEX must be held continuously through this routine
16366  *		to prevent reuse of the rqs struct before the caller can
16367  *		complete it's processing.
16368  *
16369  * Return Code: Pointer to the RQS buf
16370  *
16371  *     Context: May be called under interrupt context
16372  */
16373 
16374 static struct buf *
16375 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
16376 {
16377 	struct buf *bp;
16378 	ASSERT(un != NULL);
16379 	ASSERT(sense_xp != NULL);
16380 	ASSERT(mutex_owned(SD_MUTEX(un)));
16381 	ASSERT(un->un_sense_isbusy != 0);
16382 
16383 	un->un_sense_isbusy = 0;
16384 	bp = sense_xp->xb_sense_bp;
16385 	sense_xp->xb_sense_bp = NULL;
16386 
16387 	/* This pkt is no longer interested in getting sense data */
16388 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
16389 
16390 	return (bp);
16391 }
16392 
16393 
16394 
16395 /*
16396  *    Function: sd_alloc_rqs
16397  *
16398  * Description: Set up the unit to receive auto request sense data
16399  *
16400  * Return Code: DDI_SUCCESS or DDI_FAILURE
16401  *
16402  *     Context: Called under attach(9E) context
16403  */
16404 
16405 static int
16406 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
16407 {
16408 	struct sd_xbuf *xp;
16409 
16410 	ASSERT(un != NULL);
16411 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16412 	ASSERT(un->un_rqs_bp == NULL);
16413 	ASSERT(un->un_rqs_pktp == NULL);
16414 
16415 	/*
16416 	 * First allocate the required buf and scsi_pkt structs, then set up
16417 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
16418 	 */
16419 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
16420 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
16421 	if (un->un_rqs_bp == NULL) {
16422 		return (DDI_FAILURE);
16423 	}
16424 
16425 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
16426 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
16427 
16428 	if (un->un_rqs_pktp == NULL) {
16429 		sd_free_rqs(un);
16430 		return (DDI_FAILURE);
16431 	}
16432 
16433 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
16434 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
16435 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
16436 
16437 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
16438 
16439 	/* Set up the other needed members in the ARQ scsi_pkt. */
16440 	un->un_rqs_pktp->pkt_comp   = sdintr;
16441 	un->un_rqs_pktp->pkt_time   = sd_io_time;
16442 	un->un_rqs_pktp->pkt_flags |=
16443 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
16444 
16445 	/*
16446 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
16447 	 * provide any intpkt, destroypkt routines as we take care of
16448 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
16449 	 */
16450 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
16451 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
16452 	xp->xb_pktp = un->un_rqs_pktp;
16453 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
16454 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
16455 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
16456 
16457 	/*
16458 	 * Save the pointer to the request sense private bp so it can
16459 	 * be retrieved in sdintr.
16460 	 */
16461 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
16462 	ASSERT(un->un_rqs_bp->b_private == xp);
16463 
16464 	/*
16465 	 * See if the HBA supports auto-request sense for the specified
16466 	 * target/lun. If it does, then try to enable it (if not already
16467 	 * enabled).
16468 	 *
16469 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
16470 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
16471 	 * return success.  However, in both of these cases ARQ is always
16472 	 * enabled and scsi_ifgetcap will always return true. The best approach
16473 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
16474 	 *
16475 	 * The 3rd case is the HBA (adp) always return enabled on
16476 	 * scsi_ifgetgetcap even when it's not enable, the best approach
16477 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
16478 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
16479 	 */
16480 
16481 	if (un->un_f_is_fibre == TRUE) {
16482 		un->un_f_arq_enabled = TRUE;
16483 	} else {
16484 #if defined(__i386) || defined(__amd64)
16485 		/*
16486 		 * Circumvent the Adaptec bug, remove this code when
16487 		 * the bug is fixed
16488 		 */
16489 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
16490 #endif
16491 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
16492 		case 0:
16493 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16494 			    "sd_alloc_rqs: HBA supports ARQ\n");
16495 			/*
16496 			 * ARQ is supported by this HBA but currently is not
16497 			 * enabled. Attempt to enable it and if successful then
16498 			 * mark this instance as ARQ enabled.
16499 			 */
16500 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
16501 			    == 1) {
16502 				/* Successfully enabled ARQ in the HBA */
16503 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16504 				    "sd_alloc_rqs: ARQ enabled\n");
16505 				un->un_f_arq_enabled = TRUE;
16506 			} else {
16507 				/* Could not enable ARQ in the HBA */
16508 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16509 				    "sd_alloc_rqs: failed ARQ enable\n");
16510 				un->un_f_arq_enabled = FALSE;
16511 			}
16512 			break;
16513 		case 1:
16514 			/*
16515 			 * ARQ is supported by this HBA and is already enabled.
16516 			 * Just mark ARQ as enabled for this instance.
16517 			 */
16518 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16519 			    "sd_alloc_rqs: ARQ already enabled\n");
16520 			un->un_f_arq_enabled = TRUE;
16521 			break;
16522 		default:
16523 			/*
16524 			 * ARQ is not supported by this HBA; disable it for this
16525 			 * instance.
16526 			 */
16527 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16528 			    "sd_alloc_rqs: HBA does not support ARQ\n");
16529 			un->un_f_arq_enabled = FALSE;
16530 			break;
16531 		}
16532 	}
16533 
16534 	return (DDI_SUCCESS);
16535 }
16536 
16537 
16538 /*
16539  *    Function: sd_free_rqs
16540  *
16541  * Description: Cleanup for the pre-instance RQS command.
16542  *
16543  *     Context: Kernel thread context
16544  */
16545 
16546 static void
16547 sd_free_rqs(struct sd_lun *un)
16548 {
16549 	ASSERT(un != NULL);
16550 
16551 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
16552 
16553 	/*
16554 	 * If consistent memory is bound to a scsi_pkt, the pkt
16555 	 * has to be destroyed *before* freeing the consistent memory.
16556 	 * Don't change the sequence of this operations.
16557 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
16558 	 * after it was freed in scsi_free_consistent_buf().
16559 	 */
16560 	if (un->un_rqs_pktp != NULL) {
16561 		scsi_destroy_pkt(un->un_rqs_pktp);
16562 		un->un_rqs_pktp = NULL;
16563 	}
16564 
16565 	if (un->un_rqs_bp != NULL) {
16566 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
16567 		if (xp != NULL) {
16568 			kmem_free(xp, sizeof (struct sd_xbuf));
16569 		}
16570 		scsi_free_consistent_buf(un->un_rqs_bp);
16571 		un->un_rqs_bp = NULL;
16572 	}
16573 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
16574 }
16575 
16576 
16577 
16578 /*
16579  *    Function: sd_reduce_throttle
16580  *
16581  * Description: Reduces the maximum # of outstanding commands on a
16582  *		target to the current number of outstanding commands.
16583  *		Queues a tiemout(9F) callback to restore the limit
16584  *		after a specified interval has elapsed.
16585  *		Typically used when we get a TRAN_BUSY return code
16586  *		back from scsi_transport().
16587  *
16588  *   Arguments: un - ptr to the sd_lun softstate struct
16589  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
16590  *
16591  *     Context: May be called from interrupt context
16592  */
16593 
16594 static void
16595 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
16596 {
16597 	ASSERT(un != NULL);
16598 	ASSERT(mutex_owned(SD_MUTEX(un)));
16599 	ASSERT(un->un_ncmds_in_transport >= 0);
16600 
16601 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16602 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
16603 	    un, un->un_throttle, un->un_ncmds_in_transport);
16604 
16605 	if (un->un_throttle > 1) {
16606 		if (un->un_f_use_adaptive_throttle == TRUE) {
16607 			switch (throttle_type) {
16608 			case SD_THROTTLE_TRAN_BUSY:
16609 				if (un->un_busy_throttle == 0) {
16610 					un->un_busy_throttle = un->un_throttle;
16611 				}
16612 				break;
16613 			case SD_THROTTLE_QFULL:
16614 				un->un_busy_throttle = 0;
16615 				break;
16616 			default:
16617 				ASSERT(FALSE);
16618 			}
16619 
16620 			if (un->un_ncmds_in_transport > 0) {
16621 				un->un_throttle = un->un_ncmds_in_transport;
16622 			}
16623 
16624 		} else {
16625 			if (un->un_ncmds_in_transport == 0) {
16626 				un->un_throttle = 1;
16627 			} else {
16628 				un->un_throttle = un->un_ncmds_in_transport;
16629 			}
16630 		}
16631 	}
16632 
16633 	/* Reschedule the timeout if none is currently active */
16634 	if (un->un_reset_throttle_timeid == NULL) {
16635 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
16636 		    un, SD_THROTTLE_RESET_INTERVAL);
16637 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16638 		    "sd_reduce_throttle: timeout scheduled!\n");
16639 	}
16640 
16641 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16642 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16643 }
16644 
16645 
16646 
16647 /*
16648  *    Function: sd_restore_throttle
16649  *
16650  * Description: Callback function for timeout(9F).  Resets the current
16651  *		value of un->un_throttle to its default.
16652  *
16653  *   Arguments: arg - pointer to associated softstate for the device.
16654  *
16655  *     Context: May be called from interrupt context
16656  */
16657 
16658 static void
16659 sd_restore_throttle(void *arg)
16660 {
16661 	struct sd_lun	*un = arg;
16662 
16663 	ASSERT(un != NULL);
16664 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16665 
16666 	mutex_enter(SD_MUTEX(un));
16667 
16668 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16669 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16670 
16671 	un->un_reset_throttle_timeid = NULL;
16672 
16673 	if (un->un_f_use_adaptive_throttle == TRUE) {
16674 		/*
16675 		 * If un_busy_throttle is nonzero, then it contains the
16676 		 * value that un_throttle was when we got a TRAN_BUSY back
16677 		 * from scsi_transport(). We want to revert back to this
16678 		 * value.
16679 		 *
16680 		 * In the QFULL case, the throttle limit will incrementally
16681 		 * increase until it reaches max throttle.
16682 		 */
16683 		if (un->un_busy_throttle > 0) {
16684 			un->un_throttle = un->un_busy_throttle;
16685 			un->un_busy_throttle = 0;
16686 		} else {
16687 			/*
16688 			 * increase throttle by 10% open gate slowly, schedule
16689 			 * another restore if saved throttle has not been
16690 			 * reached
16691 			 */
16692 			short throttle;
16693 			if (sd_qfull_throttle_enable) {
16694 				throttle = un->un_throttle +
16695 				    max((un->un_throttle / 10), 1);
16696 				un->un_throttle =
16697 				    (throttle < un->un_saved_throttle) ?
16698 				    throttle : un->un_saved_throttle;
16699 				if (un->un_throttle < un->un_saved_throttle) {
16700 					un->un_reset_throttle_timeid =
16701 					    timeout(sd_restore_throttle,
16702 					    un,
16703 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
16704 				}
16705 			}
16706 		}
16707 
16708 		/*
16709 		 * If un_throttle has fallen below the low-water mark, we
16710 		 * restore the maximum value here (and allow it to ratchet
16711 		 * down again if necessary).
16712 		 */
16713 		if (un->un_throttle < un->un_min_throttle) {
16714 			un->un_throttle = un->un_saved_throttle;
16715 		}
16716 	} else {
16717 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16718 		    "restoring limit from 0x%x to 0x%x\n",
16719 		    un->un_throttle, un->un_saved_throttle);
16720 		un->un_throttle = un->un_saved_throttle;
16721 	}
16722 
16723 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16724 	    "sd_restore_throttle: calling sd_start_cmds!\n");
16725 
16726 	sd_start_cmds(un, NULL);
16727 
16728 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16729 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
16730 	    un, un->un_throttle);
16731 
16732 	mutex_exit(SD_MUTEX(un));
16733 
16734 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16735 }
16736 
16737 /*
16738  *    Function: sdrunout
16739  *
16740  * Description: Callback routine for scsi_init_pkt when a resource allocation
16741  *		fails.
16742  *
16743  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16744  *		soft state instance.
16745  *
16746  * Return Code: The scsi_init_pkt routine allows for the callback function to
16747  *		return a 0 indicating the callback should be rescheduled or a 1
16748  *		indicating not to reschedule. This routine always returns 1
16749  *		because the driver always provides a callback function to
16750  *		scsi_init_pkt. This results in a callback always being scheduled
16751  *		(via the scsi_init_pkt callback implementation) if a resource
16752  *		failure occurs.
16753  *
16754  *     Context: This callback function may not block or call routines that block
16755  *
16756  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16757  *		request persisting at the head of the list which cannot be
16758  *		satisfied even after multiple retries. In the future the driver
16759  *		may implement some time of maximum runout count before failing
16760  *		an I/O.
16761  */
16762 
16763 static int
16764 sdrunout(caddr_t arg)
16765 {
16766 	struct sd_lun	*un = (struct sd_lun *)arg;
16767 
16768 	ASSERT(un != NULL);
16769 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16770 
16771 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16772 
16773 	mutex_enter(SD_MUTEX(un));
16774 	sd_start_cmds(un, NULL);
16775 	mutex_exit(SD_MUTEX(un));
16776 	/*
16777 	 * This callback routine always returns 1 (i.e. do not reschedule)
16778 	 * because we always specify sdrunout as the callback handler for
16779 	 * scsi_init_pkt inside the call to sd_start_cmds.
16780 	 */
16781 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16782 	return (1);
16783 }
16784 
16785 
16786 /*
16787  *    Function: sdintr
16788  *
16789  * Description: Completion callback routine for scsi_pkt(9S) structs
16790  *		sent to the HBA driver via scsi_transport(9F).
16791  *
16792  *     Context: Interrupt context
16793  */
16794 
16795 static void
16796 sdintr(struct scsi_pkt *pktp)
16797 {
16798 	struct buf	*bp;
16799 	struct sd_xbuf	*xp;
16800 	struct sd_lun	*un;
16801 	size_t		actual_len;
16802 	sd_ssc_t	*sscp;
16803 
16804 	ASSERT(pktp != NULL);
16805 	bp = (struct buf *)pktp->pkt_private;
16806 	ASSERT(bp != NULL);
16807 	xp = SD_GET_XBUF(bp);
16808 	ASSERT(xp != NULL);
16809 	ASSERT(xp->xb_pktp != NULL);
16810 	un = SD_GET_UN(bp);
16811 	ASSERT(un != NULL);
16812 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16813 
16814 #ifdef SD_FAULT_INJECTION
16815 
16816 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16817 	/* SD FaultInjection */
16818 	sd_faultinjection(pktp);
16819 
16820 #endif /* SD_FAULT_INJECTION */
16821 
16822 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16823 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16824 
16825 	mutex_enter(SD_MUTEX(un));
16826 
16827 	ASSERT(un->un_fm_private != NULL);
16828 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16829 	ASSERT(sscp != NULL);
16830 
16831 	/* Reduce the count of the #commands currently in transport */
16832 	un->un_ncmds_in_transport--;
16833 	ASSERT(un->un_ncmds_in_transport >= 0);
16834 
16835 	/* Increment counter to indicate that the callback routine is active */
16836 	un->un_in_callback++;
16837 
16838 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16839 
16840 #ifdef	SDDEBUG
16841 	if (bp == un->un_retry_bp) {
16842 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16843 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16844 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16845 	}
16846 #endif
16847 
16848 	/*
16849 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
16850 	 * state if needed.
16851 	 */
16852 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16853 		/* Prevent multiple console messages for the same failure. */
16854 		if (un->un_last_pkt_reason != CMD_DEV_GONE) {
16855 			un->un_last_pkt_reason = CMD_DEV_GONE;
16856 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16857 			    "Command failed to complete...Device is gone\n");
16858 		}
16859 		if (un->un_mediastate != DKIO_DEV_GONE) {
16860 			un->un_mediastate = DKIO_DEV_GONE;
16861 			cv_broadcast(&un->un_state_cv);
16862 		}
16863 		/*
16864 		 * If the command happens to be the REQUEST SENSE command,
16865 		 * free up the rqs buf and fail the original command.
16866 		 */
16867 		if (bp == un->un_rqs_bp) {
16868 			bp = sd_mark_rqs_idle(un, xp);
16869 		}
16870 		sd_return_failed_command(un, bp, EIO);
16871 		goto exit;
16872 	}
16873 
16874 	if (pktp->pkt_state & STATE_XARQ_DONE) {
16875 		SD_TRACE(SD_LOG_COMMON, un,
16876 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
16877 	}
16878 
16879 	/*
16880 	 * First see if the pkt has auto-request sense data with it....
16881 	 * Look at the packet state first so we don't take a performance
16882 	 * hit looking at the arq enabled flag unless absolutely necessary.
16883 	 */
16884 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16885 	    (un->un_f_arq_enabled == TRUE)) {
16886 		/*
16887 		 * The HBA did an auto request sense for this command so check
16888 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16889 		 * driver command that should not be retried.
16890 		 */
16891 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16892 			/*
16893 			 * Save the relevant sense info into the xp for the
16894 			 * original cmd.
16895 			 */
16896 			struct scsi_arq_status *asp;
16897 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16898 			xp->xb_sense_status =
16899 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16900 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16901 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16902 			if (pktp->pkt_state & STATE_XARQ_DONE) {
16903 				actual_len = MAX_SENSE_LENGTH -
16904 				    xp->xb_sense_resid;
16905 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16906 				    MAX_SENSE_LENGTH);
16907 			} else {
16908 				if (xp->xb_sense_resid > SENSE_LENGTH) {
16909 					actual_len = MAX_SENSE_LENGTH -
16910 					    xp->xb_sense_resid;
16911 				} else {
16912 					actual_len = SENSE_LENGTH -
16913 					    xp->xb_sense_resid;
16914 				}
16915 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16916 					if ((((struct uscsi_cmd *)
16917 					    (xp->xb_pktinfo))->uscsi_rqlen) >
16918 					    actual_len) {
16919 						xp->xb_sense_resid =
16920 						    (((struct uscsi_cmd *)
16921 						    (xp->xb_pktinfo))->
16922 						    uscsi_rqlen) - actual_len;
16923 					} else {
16924 						xp->xb_sense_resid = 0;
16925 					}
16926 				}
16927 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16928 				    SENSE_LENGTH);
16929 			}
16930 
16931 			/* fail the command */
16932 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16933 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
16934 			sd_return_failed_command(un, bp, EIO);
16935 			goto exit;
16936 		}
16937 
16938 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
16939 		/*
16940 		 * We want to either retry or fail this command, so free
16941 		 * the DMA resources here.  If we retry the command then
16942 		 * the DMA resources will be reallocated in sd_start_cmds().
16943 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
16944 		 * causes the *entire* transfer to start over again from the
16945 		 * beginning of the request, even for PARTIAL chunks that
16946 		 * have already transferred successfully.
16947 		 */
16948 		if ((un->un_f_is_fibre == TRUE) &&
16949 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16950 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16951 			scsi_dmafree(pktp);
16952 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16953 		}
16954 #endif
16955 
16956 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16957 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
16958 
16959 		sd_handle_auto_request_sense(un, bp, xp, pktp);
16960 		goto exit;
16961 	}
16962 
16963 	/* Next see if this is the REQUEST SENSE pkt for the instance */
16964 	if (pktp->pkt_flags & FLAG_SENSING)  {
16965 		/* This pktp is from the unit's REQUEST_SENSE command */
16966 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16967 		    "sdintr: sd_handle_request_sense\n");
16968 		sd_handle_request_sense(un, bp, xp, pktp);
16969 		goto exit;
16970 	}
16971 
16972 	/*
16973 	 * Check to see if the command successfully completed as requested;
16974 	 * this is the most common case (and also the hot performance path).
16975 	 *
16976 	 * Requirements for successful completion are:
16977 	 * pkt_reason is CMD_CMPLT and packet status is status good.
16978 	 * In addition:
16979 	 * - A residual of zero indicates successful completion no matter what
16980 	 *   the command is.
16981 	 * - If the residual is not zero and the command is not a read or
16982 	 *   write, then it's still defined as successful completion. In other
16983 	 *   words, if the command is a read or write the residual must be
16984 	 *   zero for successful completion.
16985 	 * - If the residual is not zero and the command is a read or
16986 	 *   write, and it's a USCSICMD, then it's still defined as
16987 	 *   successful completion.
16988 	 */
16989 	if ((pktp->pkt_reason == CMD_CMPLT) &&
16990 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
16991 
16992 		/*
16993 		 * Since this command is returned with a good status, we
16994 		 * can reset the count for Sonoma failover.
16995 		 */
16996 		un->un_sonoma_failure_count = 0;
16997 
16998 		/*
16999 		 * Return all USCSI commands on good status
17000 		 */
17001 		if (pktp->pkt_resid == 0) {
17002 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17003 			    "sdintr: returning command for resid == 0\n");
17004 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
17005 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
17006 			SD_UPDATE_B_RESID(bp, pktp);
17007 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17008 			    "sdintr: returning command for resid != 0\n");
17009 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17010 			SD_UPDATE_B_RESID(bp, pktp);
17011 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17012 			    "sdintr: returning uscsi command\n");
17013 		} else {
17014 			goto not_successful;
17015 		}
17016 		sd_return_command(un, bp);
17017 
17018 		/*
17019 		 * Decrement counter to indicate that the callback routine
17020 		 * is done.
17021 		 */
17022 		un->un_in_callback--;
17023 		ASSERT(un->un_in_callback >= 0);
17024 		mutex_exit(SD_MUTEX(un));
17025 
17026 		return;
17027 	}
17028 
17029 not_successful:
17030 
17031 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
17032 	/*
17033 	 * The following is based upon knowledge of the underlying transport
17034 	 * and its use of DMA resources.  This code should be removed when
17035 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
17036 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
17037 	 * and sd_start_cmds().
17038 	 *
17039 	 * Free any DMA resources associated with this command if there
17040 	 * is a chance it could be retried or enqueued for later retry.
17041 	 * If we keep the DMA binding then mpxio cannot reissue the
17042 	 * command on another path whenever a path failure occurs.
17043 	 *
17044 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
17045 	 * causes the *entire* transfer to start over again from the
17046 	 * beginning of the request, even for PARTIAL chunks that
17047 	 * have already transferred successfully.
17048 	 *
17049 	 * This is only done for non-uscsi commands (and also skipped for the
17050 	 * driver's internal RQS command). Also just do this for Fibre Channel
17051 	 * devices as these are the only ones that support mpxio.
17052 	 */
17053 	if ((un->un_f_is_fibre == TRUE) &&
17054 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
17055 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
17056 		scsi_dmafree(pktp);
17057 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
17058 	}
17059 #endif
17060 
17061 	/*
17062 	 * The command did not successfully complete as requested so check
17063 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
17064 	 * driver command that should not be retried so just return. If
17065 	 * FLAG_DIAGNOSE is not set the error will be processed below.
17066 	 */
17067 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
17068 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17069 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
17070 		/*
17071 		 * Issue a request sense if a check condition caused the error
17072 		 * (we handle the auto request sense case above), otherwise
17073 		 * just fail the command.
17074 		 */
17075 		if ((pktp->pkt_reason == CMD_CMPLT) &&
17076 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
17077 			sd_send_request_sense_command(un, bp, pktp);
17078 		} else {
17079 			sd_return_failed_command(un, bp, EIO);
17080 		}
17081 		goto exit;
17082 	}
17083 
17084 	/*
17085 	 * The command did not successfully complete as requested so process
17086 	 * the error, retry, and/or attempt recovery.
17087 	 */
17088 	switch (pktp->pkt_reason) {
17089 	case CMD_CMPLT:
17090 		switch (SD_GET_PKT_STATUS(pktp)) {
17091 		case STATUS_GOOD:
17092 			/*
17093 			 * The command completed successfully with a non-zero
17094 			 * residual
17095 			 */
17096 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17097 			    "sdintr: STATUS_GOOD \n");
17098 			sd_pkt_status_good(un, bp, xp, pktp);
17099 			break;
17100 
17101 		case STATUS_CHECK:
17102 		case STATUS_TERMINATED:
17103 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17104 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
17105 			sd_pkt_status_check_condition(un, bp, xp, pktp);
17106 			break;
17107 
17108 		case STATUS_BUSY:
17109 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17110 			    "sdintr: STATUS_BUSY\n");
17111 			sd_pkt_status_busy(un, bp, xp, pktp);
17112 			break;
17113 
17114 		case STATUS_RESERVATION_CONFLICT:
17115 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17116 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
17117 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17118 			break;
17119 
17120 		case STATUS_QFULL:
17121 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17122 			    "sdintr: STATUS_QFULL\n");
17123 			sd_pkt_status_qfull(un, bp, xp, pktp);
17124 			break;
17125 
17126 		case STATUS_MET:
17127 		case STATUS_INTERMEDIATE:
17128 		case STATUS_SCSI2:
17129 		case STATUS_INTERMEDIATE_MET:
17130 		case STATUS_ACA_ACTIVE:
17131 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17132 			    "Unexpected SCSI status received: 0x%x\n",
17133 			    SD_GET_PKT_STATUS(pktp));
17134 			/*
17135 			 * Mark the ssc_flags when detected invalid status
17136 			 * code for non-USCSI command.
17137 			 */
17138 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17139 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17140 				    0, "stat-code");
17141 			}
17142 			sd_return_failed_command(un, bp, EIO);
17143 			break;
17144 
17145 		default:
17146 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17147 			    "Invalid SCSI status received: 0x%x\n",
17148 			    SD_GET_PKT_STATUS(pktp));
17149 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17150 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17151 				    0, "stat-code");
17152 			}
17153 			sd_return_failed_command(un, bp, EIO);
17154 			break;
17155 
17156 		}
17157 		break;
17158 
17159 	case CMD_INCOMPLETE:
17160 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17161 		    "sdintr:  CMD_INCOMPLETE\n");
17162 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
17163 		break;
17164 	case CMD_TRAN_ERR:
17165 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17166 		    "sdintr: CMD_TRAN_ERR\n");
17167 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
17168 		break;
17169 	case CMD_RESET:
17170 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17171 		    "sdintr: CMD_RESET \n");
17172 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
17173 		break;
17174 	case CMD_ABORTED:
17175 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17176 		    "sdintr: CMD_ABORTED \n");
17177 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
17178 		break;
17179 	case CMD_TIMEOUT:
17180 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17181 		    "sdintr: CMD_TIMEOUT\n");
17182 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
17183 		break;
17184 	case CMD_UNX_BUS_FREE:
17185 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17186 		    "sdintr: CMD_UNX_BUS_FREE \n");
17187 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
17188 		break;
17189 	case CMD_TAG_REJECT:
17190 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17191 		    "sdintr: CMD_TAG_REJECT\n");
17192 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
17193 		break;
17194 	default:
17195 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17196 		    "sdintr: default\n");
17197 		/*
17198 		 * Mark the ssc_flags for detecting invliad pkt_reason.
17199 		 */
17200 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17201 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_PKT_REASON,
17202 			    0, "pkt-reason");
17203 		}
17204 		sd_pkt_reason_default(un, bp, xp, pktp);
17205 		break;
17206 	}
17207 
17208 exit:
17209 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
17210 
17211 	/* Decrement counter to indicate that the callback routine is done. */
17212 	un->un_in_callback--;
17213 	ASSERT(un->un_in_callback >= 0);
17214 
17215 	/*
17216 	 * At this point, the pkt has been dispatched, ie, it is either
17217 	 * being re-tried or has been returned to its caller and should
17218 	 * not be referenced.
17219 	 */
17220 
17221 	mutex_exit(SD_MUTEX(un));
17222 }
17223 
17224 
17225 /*
17226  *    Function: sd_print_incomplete_msg
17227  *
17228  * Description: Prints the error message for a CMD_INCOMPLETE error.
17229  *
17230  *   Arguments: un - ptr to associated softstate for the device.
17231  *		bp - ptr to the buf(9S) for the command.
17232  *		arg - message string ptr
17233  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
17234  *			or SD_NO_RETRY_ISSUED.
17235  *
17236  *     Context: May be called under interrupt context
17237  */
17238 
17239 static void
17240 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17241 {
17242 	struct scsi_pkt	*pktp;
17243 	char	*msgp;
17244 	char	*cmdp = arg;
17245 
17246 	ASSERT(un != NULL);
17247 	ASSERT(mutex_owned(SD_MUTEX(un)));
17248 	ASSERT(bp != NULL);
17249 	ASSERT(arg != NULL);
17250 	pktp = SD_GET_PKTP(bp);
17251 	ASSERT(pktp != NULL);
17252 
17253 	switch (code) {
17254 	case SD_DELAYED_RETRY_ISSUED:
17255 	case SD_IMMEDIATE_RETRY_ISSUED:
17256 		msgp = "retrying";
17257 		break;
17258 	case SD_NO_RETRY_ISSUED:
17259 	default:
17260 		msgp = "giving up";
17261 		break;
17262 	}
17263 
17264 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17265 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17266 		    "incomplete %s- %s\n", cmdp, msgp);
17267 	}
17268 }
17269 
17270 
17271 
17272 /*
17273  *    Function: sd_pkt_status_good
17274  *
17275  * Description: Processing for a STATUS_GOOD code in pkt_status.
17276  *
17277  *     Context: May be called under interrupt context
17278  */
17279 
17280 static void
17281 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
17282 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17283 {
17284 	char	*cmdp;
17285 
17286 	ASSERT(un != NULL);
17287 	ASSERT(mutex_owned(SD_MUTEX(un)));
17288 	ASSERT(bp != NULL);
17289 	ASSERT(xp != NULL);
17290 	ASSERT(pktp != NULL);
17291 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
17292 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
17293 	ASSERT(pktp->pkt_resid != 0);
17294 
17295 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
17296 
17297 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17298 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
17299 	case SCMD_READ:
17300 		cmdp = "read";
17301 		break;
17302 	case SCMD_WRITE:
17303 		cmdp = "write";
17304 		break;
17305 	default:
17306 		SD_UPDATE_B_RESID(bp, pktp);
17307 		sd_return_command(un, bp);
17308 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17309 		return;
17310 	}
17311 
17312 	/*
17313 	 * See if we can retry the read/write, preferrably immediately.
17314 	 * If retries are exhaused, then sd_retry_command() will update
17315 	 * the b_resid count.
17316 	 */
17317 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
17318 	    cmdp, EIO, (clock_t)0, NULL);
17319 
17320 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17321 }
17322 
17323 
17324 
17325 
17326 
17327 /*
17328  *    Function: sd_handle_request_sense
17329  *
17330  * Description: Processing for non-auto Request Sense command.
17331  *
17332  *   Arguments: un - ptr to associated softstate
17333  *		sense_bp - ptr to buf(9S) for the RQS command
17334  *		sense_xp - ptr to the sd_xbuf for the RQS command
17335  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
17336  *
17337  *     Context: May be called under interrupt context
17338  */
17339 
17340 static void
17341 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
17342 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
17343 {
17344 	struct buf	*cmd_bp;	/* buf for the original command */
17345 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
17346 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
17347 	size_t		actual_len;	/* actual sense data length */
17348 
17349 	ASSERT(un != NULL);
17350 	ASSERT(mutex_owned(SD_MUTEX(un)));
17351 	ASSERT(sense_bp != NULL);
17352 	ASSERT(sense_xp != NULL);
17353 	ASSERT(sense_pktp != NULL);
17354 
17355 	/*
17356 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
17357 	 * RQS command and not the original command.
17358 	 */
17359 	ASSERT(sense_pktp == un->un_rqs_pktp);
17360 	ASSERT(sense_bp   == un->un_rqs_bp);
17361 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
17362 	    (FLAG_SENSING | FLAG_HEAD));
17363 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
17364 	    FLAG_SENSING) == FLAG_SENSING);
17365 
17366 	/* These are the bp, xp, and pktp for the original command */
17367 	cmd_bp = sense_xp->xb_sense_bp;
17368 	cmd_xp = SD_GET_XBUF(cmd_bp);
17369 	cmd_pktp = SD_GET_PKTP(cmd_bp);
17370 
17371 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
17372 		/*
17373 		 * The REQUEST SENSE command failed.  Release the REQUEST
17374 		 * SENSE command for re-use, get back the bp for the original
17375 		 * command, and attempt to re-try the original command if
17376 		 * FLAG_DIAGNOSE is not set in the original packet.
17377 		 */
17378 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17379 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17380 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
17381 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
17382 			    NULL, NULL, EIO, (clock_t)0, NULL);
17383 			return;
17384 		}
17385 	}
17386 
17387 	/*
17388 	 * Save the relevant sense info into the xp for the original cmd.
17389 	 *
17390 	 * Note: if the request sense failed the state info will be zero
17391 	 * as set in sd_mark_rqs_busy()
17392 	 */
17393 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
17394 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
17395 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
17396 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
17397 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
17398 	    SENSE_LENGTH)) {
17399 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17400 		    MAX_SENSE_LENGTH);
17401 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
17402 	} else {
17403 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17404 		    SENSE_LENGTH);
17405 		if (actual_len < SENSE_LENGTH) {
17406 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
17407 		} else {
17408 			cmd_xp->xb_sense_resid = 0;
17409 		}
17410 	}
17411 
17412 	/*
17413 	 *  Free up the RQS command....
17414 	 *  NOTE:
17415 	 *	Must do this BEFORE calling sd_validate_sense_data!
17416 	 *	sd_validate_sense_data may return the original command in
17417 	 *	which case the pkt will be freed and the flags can no
17418 	 *	longer be touched.
17419 	 *	SD_MUTEX is held through this process until the command
17420 	 *	is dispatched based upon the sense data, so there are
17421 	 *	no race conditions.
17422 	 */
17423 	(void) sd_mark_rqs_idle(un, sense_xp);
17424 
17425 	/*
17426 	 * For a retryable command see if we have valid sense data, if so then
17427 	 * turn it over to sd_decode_sense() to figure out the right course of
17428 	 * action. Just fail a non-retryable command.
17429 	 */
17430 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17431 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
17432 		    SD_SENSE_DATA_IS_VALID) {
17433 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
17434 		}
17435 	} else {
17436 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
17437 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17438 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
17439 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
17440 		sd_return_failed_command(un, cmd_bp, EIO);
17441 	}
17442 }
17443 
17444 
17445 
17446 
17447 /*
17448  *    Function: sd_handle_auto_request_sense
17449  *
17450  * Description: Processing for auto-request sense information.
17451  *
17452  *   Arguments: un - ptr to associated softstate
17453  *		bp - ptr to buf(9S) for the command
17454  *		xp - ptr to the sd_xbuf for the command
17455  *		pktp - ptr to the scsi_pkt(9S) for the command
17456  *
17457  *     Context: May be called under interrupt context
17458  */
17459 
17460 static void
17461 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
17462 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17463 {
17464 	struct scsi_arq_status *asp;
17465 	size_t actual_len;
17466 
17467 	ASSERT(un != NULL);
17468 	ASSERT(mutex_owned(SD_MUTEX(un)));
17469 	ASSERT(bp != NULL);
17470 	ASSERT(xp != NULL);
17471 	ASSERT(pktp != NULL);
17472 	ASSERT(pktp != un->un_rqs_pktp);
17473 	ASSERT(bp   != un->un_rqs_bp);
17474 
17475 	/*
17476 	 * For auto-request sense, we get a scsi_arq_status back from
17477 	 * the HBA, with the sense data in the sts_sensedata member.
17478 	 * The pkt_scbp of the packet points to this scsi_arq_status.
17479 	 */
17480 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
17481 
17482 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
17483 		/*
17484 		 * The auto REQUEST SENSE failed; see if we can re-try
17485 		 * the original command.
17486 		 */
17487 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17488 		    "auto request sense failed (reason=%s)\n",
17489 		    scsi_rname(asp->sts_rqpkt_reason));
17490 
17491 		sd_reset_target(un, pktp);
17492 
17493 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17494 		    NULL, NULL, EIO, (clock_t)0, NULL);
17495 		return;
17496 	}
17497 
17498 	/* Save the relevant sense info into the xp for the original cmd. */
17499 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
17500 	xp->xb_sense_state  = asp->sts_rqpkt_state;
17501 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
17502 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
17503 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17504 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
17505 		    MAX_SENSE_LENGTH);
17506 	} else {
17507 		if (xp->xb_sense_resid > SENSE_LENGTH) {
17508 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17509 		} else {
17510 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
17511 		}
17512 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17513 			if ((((struct uscsi_cmd *)
17514 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
17515 				xp->xb_sense_resid = (((struct uscsi_cmd *)
17516 				    (xp->xb_pktinfo))->uscsi_rqlen) -
17517 				    actual_len;
17518 			} else {
17519 				xp->xb_sense_resid = 0;
17520 			}
17521 		}
17522 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
17523 	}
17524 
17525 	/*
17526 	 * See if we have valid sense data, if so then turn it over to
17527 	 * sd_decode_sense() to figure out the right course of action.
17528 	 */
17529 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
17530 	    SD_SENSE_DATA_IS_VALID) {
17531 		sd_decode_sense(un, bp, xp, pktp);
17532 	}
17533 }
17534 
17535 
17536 /*
17537  *    Function: sd_print_sense_failed_msg
17538  *
17539  * Description: Print log message when RQS has failed.
17540  *
17541  *   Arguments: un - ptr to associated softstate
17542  *		bp - ptr to buf(9S) for the command
17543  *		arg - generic message string ptr
17544  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17545  *			or SD_NO_RETRY_ISSUED
17546  *
17547  *     Context: May be called from interrupt context
17548  */
17549 
17550 static void
17551 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
17552 	int code)
17553 {
17554 	char	*msgp = arg;
17555 
17556 	ASSERT(un != NULL);
17557 	ASSERT(mutex_owned(SD_MUTEX(un)));
17558 	ASSERT(bp != NULL);
17559 
17560 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
17561 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
17562 	}
17563 }
17564 
17565 
17566 /*
17567  *    Function: sd_validate_sense_data
17568  *
17569  * Description: Check the given sense data for validity.
17570  *		If the sense data is not valid, the command will
17571  *		be either failed or retried!
17572  *
17573  * Return Code: SD_SENSE_DATA_IS_INVALID
17574  *		SD_SENSE_DATA_IS_VALID
17575  *
17576  *     Context: May be called from interrupt context
17577  */
17578 
17579 static int
17580 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17581 	size_t actual_len)
17582 {
17583 	struct scsi_extended_sense *esp;
17584 	struct	scsi_pkt *pktp;
17585 	char	*msgp = NULL;
17586 	sd_ssc_t *sscp;
17587 
17588 	ASSERT(un != NULL);
17589 	ASSERT(mutex_owned(SD_MUTEX(un)));
17590 	ASSERT(bp != NULL);
17591 	ASSERT(bp != un->un_rqs_bp);
17592 	ASSERT(xp != NULL);
17593 	ASSERT(un->un_fm_private != NULL);
17594 
17595 	pktp = SD_GET_PKTP(bp);
17596 	ASSERT(pktp != NULL);
17597 
17598 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
17599 	ASSERT(sscp != NULL);
17600 
17601 	/*
17602 	 * Check the status of the RQS command (auto or manual).
17603 	 */
17604 	switch (xp->xb_sense_status & STATUS_MASK) {
17605 	case STATUS_GOOD:
17606 		break;
17607 
17608 	case STATUS_RESERVATION_CONFLICT:
17609 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17610 		return (SD_SENSE_DATA_IS_INVALID);
17611 
17612 	case STATUS_BUSY:
17613 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17614 		    "Busy Status on REQUEST SENSE\n");
17615 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
17616 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17617 		return (SD_SENSE_DATA_IS_INVALID);
17618 
17619 	case STATUS_QFULL:
17620 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17621 		    "QFULL Status on REQUEST SENSE\n");
17622 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
17623 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17624 		return (SD_SENSE_DATA_IS_INVALID);
17625 
17626 	case STATUS_CHECK:
17627 	case STATUS_TERMINATED:
17628 		msgp = "Check Condition on REQUEST SENSE\n";
17629 		goto sense_failed;
17630 
17631 	default:
17632 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
17633 		goto sense_failed;
17634 	}
17635 
17636 	/*
17637 	 * See if we got the minimum required amount of sense data.
17638 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
17639 	 * or less.
17640 	 */
17641 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
17642 	    (actual_len == 0)) {
17643 		msgp = "Request Sense couldn't get sense data\n";
17644 		goto sense_failed;
17645 	}
17646 
17647 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
17648 		msgp = "Not enough sense information\n";
17649 		/* Mark the ssc_flags for detecting invalid sense data */
17650 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17651 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17652 			    "sense-data");
17653 		}
17654 		goto sense_failed;
17655 	}
17656 
17657 	/*
17658 	 * We require the extended sense data
17659 	 */
17660 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
17661 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
17662 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17663 			static char tmp[8];
17664 			static char buf[148];
17665 			char *p = (char *)(xp->xb_sense_data);
17666 			int i;
17667 
17668 			mutex_enter(&sd_sense_mutex);
17669 			(void) strcpy(buf, "undecodable sense information:");
17670 			for (i = 0; i < actual_len; i++) {
17671 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
17672 				(void) strcpy(&buf[strlen(buf)], tmp);
17673 			}
17674 			i = strlen(buf);
17675 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
17676 
17677 			if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
17678 				scsi_log(SD_DEVINFO(un), sd_label,
17679 				    CE_WARN, buf);
17680 			}
17681 			mutex_exit(&sd_sense_mutex);
17682 		}
17683 
17684 		/* Mark the ssc_flags for detecting invalid sense data */
17685 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17686 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17687 			    "sense-data");
17688 		}
17689 
17690 		/* Note: Legacy behavior, fail the command with no retry */
17691 		sd_return_failed_command(un, bp, EIO);
17692 		return (SD_SENSE_DATA_IS_INVALID);
17693 	}
17694 
17695 	/*
17696 	 * Check that es_code is valid (es_class concatenated with es_code
17697 	 * make up the "response code" field.  es_class will always be 7, so
17698 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
17699 	 * format.
17700 	 */
17701 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
17702 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
17703 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
17704 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
17705 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
17706 		/* Mark the ssc_flags for detecting invalid sense data */
17707 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17708 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17709 			    "sense-data");
17710 		}
17711 		goto sense_failed;
17712 	}
17713 
17714 	return (SD_SENSE_DATA_IS_VALID);
17715 
17716 sense_failed:
17717 	/*
17718 	 * If the request sense failed (for whatever reason), attempt
17719 	 * to retry the original command.
17720 	 */
17721 #if defined(__i386) || defined(__amd64)
17722 	/*
17723 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
17724 	 * sddef.h for Sparc platform, and x86 uses 1 binary
17725 	 * for both SCSI/FC.
17726 	 * The SD_RETRY_DELAY value need to be adjusted here
17727 	 * when SD_RETRY_DELAY change in sddef.h
17728 	 */
17729 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17730 	    sd_print_sense_failed_msg, msgp, EIO,
17731 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
17732 #else
17733 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17734 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
17735 #endif
17736 
17737 	return (SD_SENSE_DATA_IS_INVALID);
17738 }
17739 
17740 /*
17741  *    Function: sd_decode_sense
17742  *
17743  * Description: Take recovery action(s) when SCSI Sense Data is received.
17744  *
17745  *     Context: Interrupt context.
17746  */
17747 
17748 static void
17749 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17750 	struct scsi_pkt *pktp)
17751 {
17752 	uint8_t sense_key;
17753 
17754 	ASSERT(un != NULL);
17755 	ASSERT(mutex_owned(SD_MUTEX(un)));
17756 	ASSERT(bp != NULL);
17757 	ASSERT(bp != un->un_rqs_bp);
17758 	ASSERT(xp != NULL);
17759 	ASSERT(pktp != NULL);
17760 
17761 	sense_key = scsi_sense_key(xp->xb_sense_data);
17762 
17763 	switch (sense_key) {
17764 	case KEY_NO_SENSE:
17765 		sd_sense_key_no_sense(un, bp, xp, pktp);
17766 		break;
17767 	case KEY_RECOVERABLE_ERROR:
17768 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
17769 		    bp, xp, pktp);
17770 		break;
17771 	case KEY_NOT_READY:
17772 		sd_sense_key_not_ready(un, xp->xb_sense_data,
17773 		    bp, xp, pktp);
17774 		break;
17775 	case KEY_MEDIUM_ERROR:
17776 	case KEY_HARDWARE_ERROR:
17777 		sd_sense_key_medium_or_hardware_error(un,
17778 		    xp->xb_sense_data, bp, xp, pktp);
17779 		break;
17780 	case KEY_ILLEGAL_REQUEST:
17781 		sd_sense_key_illegal_request(un, bp, xp, pktp);
17782 		break;
17783 	case KEY_UNIT_ATTENTION:
17784 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
17785 		    bp, xp, pktp);
17786 		break;
17787 	case KEY_WRITE_PROTECT:
17788 	case KEY_VOLUME_OVERFLOW:
17789 	case KEY_MISCOMPARE:
17790 		sd_sense_key_fail_command(un, bp, xp, pktp);
17791 		break;
17792 	case KEY_BLANK_CHECK:
17793 		sd_sense_key_blank_check(un, bp, xp, pktp);
17794 		break;
17795 	case KEY_ABORTED_COMMAND:
17796 		sd_sense_key_aborted_command(un, bp, xp, pktp);
17797 		break;
17798 	case KEY_VENDOR_UNIQUE:
17799 	case KEY_COPY_ABORTED:
17800 	case KEY_EQUAL:
17801 	case KEY_RESERVED:
17802 	default:
17803 		sd_sense_key_default(un, xp->xb_sense_data,
17804 		    bp, xp, pktp);
17805 		break;
17806 	}
17807 }
17808 
17809 
17810 /*
17811  *    Function: sd_dump_memory
17812  *
17813  * Description: Debug logging routine to print the contents of a user provided
17814  *		buffer. The output of the buffer is broken up into 256 byte
17815  *		segments due to a size constraint of the scsi_log.
17816  *		implementation.
17817  *
17818  *   Arguments: un - ptr to softstate
17819  *		comp - component mask
17820  *		title - "title" string to preceed data when printed
17821  *		data - ptr to data block to be printed
17822  *		len - size of data block to be printed
17823  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
17824  *
17825  *     Context: May be called from interrupt context
17826  */
17827 
17828 #define	SD_DUMP_MEMORY_BUF_SIZE	256
17829 
17830 static char *sd_dump_format_string[] = {
17831 		" 0x%02x",
17832 		" %c"
17833 };
17834 
17835 static void
17836 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
17837     int len, int fmt)
17838 {
17839 	int	i, j;
17840 	int	avail_count;
17841 	int	start_offset;
17842 	int	end_offset;
17843 	size_t	entry_len;
17844 	char	*bufp;
17845 	char	*local_buf;
17846 	char	*format_string;
17847 
17848 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
17849 
17850 	/*
17851 	 * In the debug version of the driver, this function is called from a
17852 	 * number of places which are NOPs in the release driver.
17853 	 * The debug driver therefore has additional methods of filtering
17854 	 * debug output.
17855 	 */
17856 #ifdef SDDEBUG
17857 	/*
17858 	 * In the debug version of the driver we can reduce the amount of debug
17859 	 * messages by setting sd_error_level to something other than
17860 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17861 	 * sd_component_mask.
17862 	 */
17863 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17864 	    (sd_error_level != SCSI_ERR_ALL)) {
17865 		return;
17866 	}
17867 	if (((sd_component_mask & comp) == 0) ||
17868 	    (sd_error_level != SCSI_ERR_ALL)) {
17869 		return;
17870 	}
17871 #else
17872 	if (sd_error_level != SCSI_ERR_ALL) {
17873 		return;
17874 	}
17875 #endif
17876 
17877 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17878 	bufp = local_buf;
17879 	/*
17880 	 * Available length is the length of local_buf[], minus the
17881 	 * length of the title string, minus one for the ":", minus
17882 	 * one for the newline, minus one for the NULL terminator.
17883 	 * This gives the #bytes available for holding the printed
17884 	 * values from the given data buffer.
17885 	 */
17886 	if (fmt == SD_LOG_HEX) {
17887 		format_string = sd_dump_format_string[0];
17888 	} else /* SD_LOG_CHAR */ {
17889 		format_string = sd_dump_format_string[1];
17890 	}
17891 	/*
17892 	 * Available count is the number of elements from the given
17893 	 * data buffer that we can fit into the available length.
17894 	 * This is based upon the size of the format string used.
17895 	 * Make one entry and find it's size.
17896 	 */
17897 	(void) sprintf(bufp, format_string, data[0]);
17898 	entry_len = strlen(bufp);
17899 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17900 
17901 	j = 0;
17902 	while (j < len) {
17903 		bufp = local_buf;
17904 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17905 		start_offset = j;
17906 
17907 		end_offset = start_offset + avail_count;
17908 
17909 		(void) sprintf(bufp, "%s:", title);
17910 		bufp += strlen(bufp);
17911 		for (i = start_offset; ((i < end_offset) && (j < len));
17912 		    i++, j++) {
17913 			(void) sprintf(bufp, format_string, data[i]);
17914 			bufp += entry_len;
17915 		}
17916 		(void) sprintf(bufp, "\n");
17917 
17918 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17919 	}
17920 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
17921 }
17922 
17923 /*
17924  *    Function: sd_print_sense_msg
17925  *
17926  * Description: Log a message based upon the given sense data.
17927  *
17928  *   Arguments: un - ptr to associated softstate
17929  *		bp - ptr to buf(9S) for the command
17930  *		arg - ptr to associate sd_sense_info struct
17931  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17932  *			or SD_NO_RETRY_ISSUED
17933  *
17934  *     Context: May be called from interrupt context
17935  */
17936 
17937 static void
17938 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17939 {
17940 	struct sd_xbuf	*xp;
17941 	struct scsi_pkt	*pktp;
17942 	uint8_t *sensep;
17943 	daddr_t request_blkno;
17944 	diskaddr_t err_blkno;
17945 	int severity;
17946 	int pfa_flag;
17947 	extern struct scsi_key_strings scsi_cmds[];
17948 
17949 	ASSERT(un != NULL);
17950 	ASSERT(mutex_owned(SD_MUTEX(un)));
17951 	ASSERT(bp != NULL);
17952 	xp = SD_GET_XBUF(bp);
17953 	ASSERT(xp != NULL);
17954 	pktp = SD_GET_PKTP(bp);
17955 	ASSERT(pktp != NULL);
17956 	ASSERT(arg != NULL);
17957 
17958 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
17959 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
17960 
17961 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
17962 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
17963 		severity = SCSI_ERR_RETRYABLE;
17964 	}
17965 
17966 	/* Use absolute block number for the request block number */
17967 	request_blkno = xp->xb_blkno;
17968 
17969 	/*
17970 	 * Now try to get the error block number from the sense data
17971 	 */
17972 	sensep = xp->xb_sense_data;
17973 
17974 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
17975 	    (uint64_t *)&err_blkno)) {
17976 		/*
17977 		 * We retrieved the error block number from the information
17978 		 * portion of the sense data.
17979 		 *
17980 		 * For USCSI commands we are better off using the error
17981 		 * block no. as the requested block no. (This is the best
17982 		 * we can estimate.)
17983 		 */
17984 		if ((SD_IS_BUFIO(xp) == FALSE) &&
17985 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
17986 			request_blkno = err_blkno;
17987 		}
17988 	} else {
17989 		/*
17990 		 * Without the es_valid bit set (for fixed format) or an
17991 		 * information descriptor (for descriptor format) we cannot
17992 		 * be certain of the error blkno, so just use the
17993 		 * request_blkno.
17994 		 */
17995 		err_blkno = (diskaddr_t)request_blkno;
17996 	}
17997 
17998 	/*
17999 	 * The following will log the buffer contents for the release driver
18000 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
18001 	 * level is set to verbose.
18002 	 */
18003 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
18004 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
18005 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
18006 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
18007 
18008 	if (pfa_flag == FALSE) {
18009 		/* This is normally only set for USCSI */
18010 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
18011 			return;
18012 		}
18013 
18014 		if ((SD_IS_BUFIO(xp) == TRUE) &&
18015 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
18016 		    (severity < sd_error_level))) {
18017 			return;
18018 		}
18019 	}
18020 	/*
18021 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
18022 	 */
18023 	if ((SD_IS_LSI(un)) &&
18024 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
18025 	    (scsi_sense_asc(sensep) == 0x94) &&
18026 	    (scsi_sense_ascq(sensep) == 0x01)) {
18027 		un->un_sonoma_failure_count++;
18028 		if (un->un_sonoma_failure_count > 1) {
18029 			return;
18030 		}
18031 	}
18032 
18033 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP ||
18034 	    ((scsi_sense_key(sensep) == KEY_RECOVERABLE_ERROR) &&
18035 	    (pktp->pkt_resid == 0))) {
18036 		scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
18037 		    request_blkno, err_blkno, scsi_cmds,
18038 		    (struct scsi_extended_sense *)sensep,
18039 		    un->un_additional_codes, NULL);
18040 	}
18041 }
18042 
18043 /*
18044  *    Function: sd_sense_key_no_sense
18045  *
18046  * Description: Recovery action when sense data was not received.
18047  *
18048  *     Context: May be called from interrupt context
18049  */
18050 
18051 static void
18052 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
18053 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18054 {
18055 	struct sd_sense_info	si;
18056 
18057 	ASSERT(un != NULL);
18058 	ASSERT(mutex_owned(SD_MUTEX(un)));
18059 	ASSERT(bp != NULL);
18060 	ASSERT(xp != NULL);
18061 	ASSERT(pktp != NULL);
18062 
18063 	si.ssi_severity = SCSI_ERR_FATAL;
18064 	si.ssi_pfa_flag = FALSE;
18065 
18066 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
18067 
18068 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18069 	    &si, EIO, (clock_t)0, NULL);
18070 }
18071 
18072 
18073 /*
18074  *    Function: sd_sense_key_recoverable_error
18075  *
18076  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
18077  *
18078  *     Context: May be called from interrupt context
18079  */
18080 
18081 static void
18082 sd_sense_key_recoverable_error(struct sd_lun *un,
18083 	uint8_t *sense_datap,
18084 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18085 {
18086 	struct sd_sense_info	si;
18087 	uint8_t asc = scsi_sense_asc(sense_datap);
18088 
18089 	ASSERT(un != NULL);
18090 	ASSERT(mutex_owned(SD_MUTEX(un)));
18091 	ASSERT(bp != NULL);
18092 	ASSERT(xp != NULL);
18093 	ASSERT(pktp != NULL);
18094 
18095 	/*
18096 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
18097 	 */
18098 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
18099 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18100 		si.ssi_severity = SCSI_ERR_INFO;
18101 		si.ssi_pfa_flag = TRUE;
18102 	} else {
18103 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
18104 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
18105 		si.ssi_severity = SCSI_ERR_RECOVERED;
18106 		si.ssi_pfa_flag = FALSE;
18107 	}
18108 
18109 	if (pktp->pkt_resid == 0) {
18110 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18111 		sd_return_command(un, bp);
18112 		return;
18113 	}
18114 
18115 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18116 	    &si, EIO, (clock_t)0, NULL);
18117 }
18118 
18119 
18120 
18121 
18122 /*
18123  *    Function: sd_sense_key_not_ready
18124  *
18125  * Description: Recovery actions for a SCSI "Not Ready" sense key.
18126  *
18127  *     Context: May be called from interrupt context
18128  */
18129 
18130 static void
18131 sd_sense_key_not_ready(struct sd_lun *un,
18132 	uint8_t *sense_datap,
18133 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18134 {
18135 	struct sd_sense_info	si;
18136 	uint8_t asc = scsi_sense_asc(sense_datap);
18137 	uint8_t ascq = scsi_sense_ascq(sense_datap);
18138 
18139 	ASSERT(un != NULL);
18140 	ASSERT(mutex_owned(SD_MUTEX(un)));
18141 	ASSERT(bp != NULL);
18142 	ASSERT(xp != NULL);
18143 	ASSERT(pktp != NULL);
18144 
18145 	si.ssi_severity = SCSI_ERR_FATAL;
18146 	si.ssi_pfa_flag = FALSE;
18147 
18148 	/*
18149 	 * Update error stats after first NOT READY error. Disks may have
18150 	 * been powered down and may need to be restarted.  For CDROMs,
18151 	 * report NOT READY errors only if media is present.
18152 	 */
18153 	if ((ISCD(un) && (asc == 0x3A)) ||
18154 	    (xp->xb_nr_retry_count > 0)) {
18155 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18156 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
18157 	}
18158 
18159 	/*
18160 	 * Just fail if the "not ready" retry limit has been reached.
18161 	 */
18162 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
18163 		/* Special check for error message printing for removables. */
18164 		if (un->un_f_has_removable_media && (asc == 0x04) &&
18165 		    (ascq >= 0x04)) {
18166 			si.ssi_severity = SCSI_ERR_ALL;
18167 		}
18168 		goto fail_command;
18169 	}
18170 
18171 	/*
18172 	 * Check the ASC and ASCQ in the sense data as needed, to determine
18173 	 * what to do.
18174 	 */
18175 	switch (asc) {
18176 	case 0x04:	/* LOGICAL UNIT NOT READY */
18177 		/*
18178 		 * disk drives that don't spin up result in a very long delay
18179 		 * in format without warning messages. We will log a message
18180 		 * if the error level is set to verbose.
18181 		 */
18182 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18183 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18184 			    "logical unit not ready, resetting disk\n");
18185 		}
18186 
18187 		/*
18188 		 * There are different requirements for CDROMs and disks for
18189 		 * the number of retries.  If a CD-ROM is giving this, it is
18190 		 * probably reading TOC and is in the process of getting
18191 		 * ready, so we should keep on trying for a long time to make
18192 		 * sure that all types of media are taken in account (for
18193 		 * some media the drive takes a long time to read TOC).  For
18194 		 * disks we do not want to retry this too many times as this
18195 		 * can cause a long hang in format when the drive refuses to
18196 		 * spin up (a very common failure).
18197 		 */
18198 		switch (ascq) {
18199 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
18200 			/*
18201 			 * Disk drives frequently refuse to spin up which
18202 			 * results in a very long hang in format without
18203 			 * warning messages.
18204 			 *
18205 			 * Note: This code preserves the legacy behavior of
18206 			 * comparing xb_nr_retry_count against zero for fibre
18207 			 * channel targets instead of comparing against the
18208 			 * un_reset_retry_count value.  The reason for this
18209 			 * discrepancy has been so utterly lost beneath the
18210 			 * Sands of Time that even Indiana Jones could not
18211 			 * find it.
18212 			 */
18213 			if (un->un_f_is_fibre == TRUE) {
18214 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18215 				    (xp->xb_nr_retry_count > 0)) &&
18216 				    (un->un_startstop_timeid == NULL)) {
18217 					scsi_log(SD_DEVINFO(un), sd_label,
18218 					    CE_WARN, "logical unit not ready, "
18219 					    "resetting disk\n");
18220 					sd_reset_target(un, pktp);
18221 				}
18222 			} else {
18223 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18224 				    (xp->xb_nr_retry_count >
18225 				    un->un_reset_retry_count)) &&
18226 				    (un->un_startstop_timeid == NULL)) {
18227 					scsi_log(SD_DEVINFO(un), sd_label,
18228 					    CE_WARN, "logical unit not ready, "
18229 					    "resetting disk\n");
18230 					sd_reset_target(un, pktp);
18231 				}
18232 			}
18233 			break;
18234 
18235 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
18236 			/*
18237 			 * If the target is in the process of becoming
18238 			 * ready, just proceed with the retry. This can
18239 			 * happen with CD-ROMs that take a long time to
18240 			 * read TOC after a power cycle or reset.
18241 			 */
18242 			goto do_retry;
18243 
18244 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
18245 			break;
18246 
18247 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
18248 			/*
18249 			 * Retries cannot help here so just fail right away.
18250 			 */
18251 			goto fail_command;
18252 
18253 		case 0x88:
18254 			/*
18255 			 * Vendor-unique code for T3/T4: it indicates a
18256 			 * path problem in a mutipathed config, but as far as
18257 			 * the target driver is concerned it equates to a fatal
18258 			 * error, so we should just fail the command right away
18259 			 * (without printing anything to the console). If this
18260 			 * is not a T3/T4, fall thru to the default recovery
18261 			 * action.
18262 			 * T3/T4 is FC only, don't need to check is_fibre
18263 			 */
18264 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
18265 				sd_return_failed_command(un, bp, EIO);
18266 				return;
18267 			}
18268 			/* FALLTHRU */
18269 
18270 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
18271 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
18272 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
18273 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
18274 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
18275 		default:    /* Possible future codes in SCSI spec? */
18276 			/*
18277 			 * For removable-media devices, do not retry if
18278 			 * ASCQ > 2 as these result mostly from USCSI commands
18279 			 * on MMC devices issued to check status of an
18280 			 * operation initiated in immediate mode.  Also for
18281 			 * ASCQ >= 4 do not print console messages as these
18282 			 * mainly represent a user-initiated operation
18283 			 * instead of a system failure.
18284 			 */
18285 			if (un->un_f_has_removable_media) {
18286 				si.ssi_severity = SCSI_ERR_ALL;
18287 				goto fail_command;
18288 			}
18289 			break;
18290 		}
18291 
18292 		/*
18293 		 * As part of our recovery attempt for the NOT READY
18294 		 * condition, we issue a START STOP UNIT command. However
18295 		 * we want to wait for a short delay before attempting this
18296 		 * as there may still be more commands coming back from the
18297 		 * target with the check condition. To do this we use
18298 		 * timeout(9F) to call sd_start_stop_unit_callback() after
18299 		 * the delay interval expires. (sd_start_stop_unit_callback()
18300 		 * dispatches sd_start_stop_unit_task(), which will issue
18301 		 * the actual START STOP UNIT command. The delay interval
18302 		 * is one-half of the delay that we will use to retry the
18303 		 * command that generated the NOT READY condition.
18304 		 *
18305 		 * Note that we could just dispatch sd_start_stop_unit_task()
18306 		 * from here and allow it to sleep for the delay interval,
18307 		 * but then we would be tying up the taskq thread
18308 		 * uncesessarily for the duration of the delay.
18309 		 *
18310 		 * Do not issue the START STOP UNIT if the current command
18311 		 * is already a START STOP UNIT.
18312 		 */
18313 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
18314 			break;
18315 		}
18316 
18317 		/*
18318 		 * Do not schedule the timeout if one is already pending.
18319 		 */
18320 		if (un->un_startstop_timeid != NULL) {
18321 			SD_INFO(SD_LOG_ERROR, un,
18322 			    "sd_sense_key_not_ready: restart already issued to"
18323 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
18324 			    ddi_get_instance(SD_DEVINFO(un)));
18325 			break;
18326 		}
18327 
18328 		/*
18329 		 * Schedule the START STOP UNIT command, then queue the command
18330 		 * for a retry.
18331 		 *
18332 		 * Note: A timeout is not scheduled for this retry because we
18333 		 * want the retry to be serial with the START_STOP_UNIT. The
18334 		 * retry will be started when the START_STOP_UNIT is completed
18335 		 * in sd_start_stop_unit_task.
18336 		 */
18337 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
18338 		    un, un->un_busy_timeout / 2);
18339 		xp->xb_nr_retry_count++;
18340 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
18341 		return;
18342 
18343 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
18344 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18345 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18346 			    "unit does not respond to selection\n");
18347 		}
18348 		break;
18349 
18350 	case 0x3A:	/* MEDIUM NOT PRESENT */
18351 		if (sd_error_level >= SCSI_ERR_FATAL) {
18352 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18353 			    "Caddy not inserted in drive\n");
18354 		}
18355 
18356 		sr_ejected(un);
18357 		un->un_mediastate = DKIO_EJECTED;
18358 		/* The state has changed, inform the media watch routines */
18359 		cv_broadcast(&un->un_state_cv);
18360 		/* Just fail if no media is present in the drive. */
18361 		goto fail_command;
18362 
18363 	default:
18364 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18365 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
18366 			    "Unit not Ready. Additional sense code 0x%x\n",
18367 			    asc);
18368 		}
18369 		break;
18370 	}
18371 
18372 do_retry:
18373 
18374 	/*
18375 	 * Retry the command, as some targets may report NOT READY for
18376 	 * several seconds after being reset.
18377 	 */
18378 	xp->xb_nr_retry_count++;
18379 	si.ssi_severity = SCSI_ERR_RETRYABLE;
18380 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
18381 	    &si, EIO, un->un_busy_timeout, NULL);
18382 
18383 	return;
18384 
18385 fail_command:
18386 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18387 	sd_return_failed_command(un, bp, EIO);
18388 }
18389 
18390 
18391 
18392 /*
18393  *    Function: sd_sense_key_medium_or_hardware_error
18394  *
18395  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
18396  *		sense key.
18397  *
18398  *     Context: May be called from interrupt context
18399  */
18400 
18401 static void
18402 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
18403 	uint8_t *sense_datap,
18404 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18405 {
18406 	struct sd_sense_info	si;
18407 	uint8_t sense_key = scsi_sense_key(sense_datap);
18408 	uint8_t asc = scsi_sense_asc(sense_datap);
18409 
18410 	ASSERT(un != NULL);
18411 	ASSERT(mutex_owned(SD_MUTEX(un)));
18412 	ASSERT(bp != NULL);
18413 	ASSERT(xp != NULL);
18414 	ASSERT(pktp != NULL);
18415 
18416 	si.ssi_severity = SCSI_ERR_FATAL;
18417 	si.ssi_pfa_flag = FALSE;
18418 
18419 	if (sense_key == KEY_MEDIUM_ERROR) {
18420 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
18421 	}
18422 
18423 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18424 
18425 	if ((un->un_reset_retry_count != 0) &&
18426 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
18427 		mutex_exit(SD_MUTEX(un));
18428 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
18429 		if (un->un_f_allow_bus_device_reset == TRUE) {
18430 
18431 			boolean_t try_resetting_target = B_TRUE;
18432 
18433 			/*
18434 			 * We need to be able to handle specific ASC when we are
18435 			 * handling a KEY_HARDWARE_ERROR. In particular
18436 			 * taking the default action of resetting the target may
18437 			 * not be the appropriate way to attempt recovery.
18438 			 * Resetting a target because of a single LUN failure
18439 			 * victimizes all LUNs on that target.
18440 			 *
18441 			 * This is true for the LSI arrays, if an LSI
18442 			 * array controller returns an ASC of 0x84 (LUN Dead) we
18443 			 * should trust it.
18444 			 */
18445 
18446 			if (sense_key == KEY_HARDWARE_ERROR) {
18447 				switch (asc) {
18448 				case 0x84:
18449 					if (SD_IS_LSI(un)) {
18450 						try_resetting_target = B_FALSE;
18451 					}
18452 					break;
18453 				default:
18454 					break;
18455 				}
18456 			}
18457 
18458 			if (try_resetting_target == B_TRUE) {
18459 				int reset_retval = 0;
18460 				if (un->un_f_lun_reset_enabled == TRUE) {
18461 					SD_TRACE(SD_LOG_IO_CORE, un,
18462 					    "sd_sense_key_medium_or_hardware_"
18463 					    "error: issuing RESET_LUN\n");
18464 					reset_retval =
18465 					    scsi_reset(SD_ADDRESS(un),
18466 					    RESET_LUN);
18467 				}
18468 				if (reset_retval == 0) {
18469 					SD_TRACE(SD_LOG_IO_CORE, un,
18470 					    "sd_sense_key_medium_or_hardware_"
18471 					    "error: issuing RESET_TARGET\n");
18472 					(void) scsi_reset(SD_ADDRESS(un),
18473 					    RESET_TARGET);
18474 				}
18475 			}
18476 		}
18477 		mutex_enter(SD_MUTEX(un));
18478 	}
18479 
18480 	/*
18481 	 * This really ought to be a fatal error, but we will retry anyway
18482 	 * as some drives report this as a spurious error.
18483 	 */
18484 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18485 	    &si, EIO, (clock_t)0, NULL);
18486 }
18487 
18488 
18489 
18490 /*
18491  *    Function: sd_sense_key_illegal_request
18492  *
18493  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
18494  *
18495  *     Context: May be called from interrupt context
18496  */
18497 
18498 static void
18499 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
18500 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18501 {
18502 	struct sd_sense_info	si;
18503 
18504 	ASSERT(un != NULL);
18505 	ASSERT(mutex_owned(SD_MUTEX(un)));
18506 	ASSERT(bp != NULL);
18507 	ASSERT(xp != NULL);
18508 	ASSERT(pktp != NULL);
18509 
18510 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
18511 
18512 	si.ssi_severity = SCSI_ERR_INFO;
18513 	si.ssi_pfa_flag = FALSE;
18514 
18515 	/* Pointless to retry if the target thinks it's an illegal request */
18516 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18517 	sd_return_failed_command(un, bp, EIO);
18518 }
18519 
18520 
18521 
18522 
18523 /*
18524  *    Function: sd_sense_key_unit_attention
18525  *
18526  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
18527  *
18528  *     Context: May be called from interrupt context
18529  */
18530 
18531 static void
18532 sd_sense_key_unit_attention(struct sd_lun *un,
18533 	uint8_t *sense_datap,
18534 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18535 {
18536 	/*
18537 	 * For UNIT ATTENTION we allow retries for one minute. Devices
18538 	 * like Sonoma can return UNIT ATTENTION close to a minute
18539 	 * under certain conditions.
18540 	 */
18541 	int	retry_check_flag = SD_RETRIES_UA;
18542 	boolean_t	kstat_updated = B_FALSE;
18543 	struct	sd_sense_info		si;
18544 	uint8_t asc = scsi_sense_asc(sense_datap);
18545 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
18546 
18547 	ASSERT(un != NULL);
18548 	ASSERT(mutex_owned(SD_MUTEX(un)));
18549 	ASSERT(bp != NULL);
18550 	ASSERT(xp != NULL);
18551 	ASSERT(pktp != NULL);
18552 
18553 	si.ssi_severity = SCSI_ERR_INFO;
18554 	si.ssi_pfa_flag = FALSE;
18555 
18556 
18557 	switch (asc) {
18558 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
18559 		if (sd_report_pfa != 0) {
18560 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18561 			si.ssi_pfa_flag = TRUE;
18562 			retry_check_flag = SD_RETRIES_STANDARD;
18563 			goto do_retry;
18564 		}
18565 
18566 		break;
18567 
18568 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
18569 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
18570 			un->un_resvd_status |=
18571 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
18572 		}
18573 #ifdef _LP64
18574 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
18575 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
18576 			    un, KM_NOSLEEP) == 0) {
18577 				/*
18578 				 * If we can't dispatch the task we'll just
18579 				 * live without descriptor sense.  We can
18580 				 * try again on the next "unit attention"
18581 				 */
18582 				SD_ERROR(SD_LOG_ERROR, un,
18583 				    "sd_sense_key_unit_attention: "
18584 				    "Could not dispatch "
18585 				    "sd_reenable_dsense_task\n");
18586 			}
18587 		}
18588 #endif /* _LP64 */
18589 		/* FALLTHRU */
18590 
18591 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
18592 		if (!un->un_f_has_removable_media) {
18593 			break;
18594 		}
18595 
18596 		/*
18597 		 * When we get a unit attention from a removable-media device,
18598 		 * it may be in a state that will take a long time to recover
18599 		 * (e.g., from a reset).  Since we are executing in interrupt
18600 		 * context here, we cannot wait around for the device to come
18601 		 * back. So hand this command off to sd_media_change_task()
18602 		 * for deferred processing under taskq thread context. (Note
18603 		 * that the command still may be failed if a problem is
18604 		 * encountered at a later time.)
18605 		 */
18606 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
18607 		    KM_NOSLEEP) == 0) {
18608 			/*
18609 			 * Cannot dispatch the request so fail the command.
18610 			 */
18611 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
18612 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18613 			si.ssi_severity = SCSI_ERR_FATAL;
18614 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18615 			sd_return_failed_command(un, bp, EIO);
18616 		}
18617 
18618 		/*
18619 		 * If failed to dispatch sd_media_change_task(), we already
18620 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
18621 		 * we should update kstat later if it encounters an error. So,
18622 		 * we update kstat_updated flag here.
18623 		 */
18624 		kstat_updated = B_TRUE;
18625 
18626 		/*
18627 		 * Either the command has been successfully dispatched to a
18628 		 * task Q for retrying, or the dispatch failed. In either case
18629 		 * do NOT retry again by calling sd_retry_command. This sets up
18630 		 * two retries of the same command and when one completes and
18631 		 * frees the resources the other will access freed memory,
18632 		 * a bad thing.
18633 		 */
18634 		return;
18635 
18636 	default:
18637 		break;
18638 	}
18639 
18640 	/*
18641 	 * ASC  ASCQ
18642 	 *  2A   09	Capacity data has changed
18643 	 *  2A   01	Mode parameters changed
18644 	 *  3F   0E	Reported luns data has changed
18645 	 * Arrays that support logical unit expansion should report
18646 	 * capacity changes(2Ah/09). Mode parameters changed and
18647 	 * reported luns data has changed are the approximation.
18648 	 */
18649 	if (((asc == 0x2a) && (ascq == 0x09)) ||
18650 	    ((asc == 0x2a) && (ascq == 0x01)) ||
18651 	    ((asc == 0x3f) && (ascq == 0x0e))) {
18652 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
18653 		    KM_NOSLEEP) == 0) {
18654 			SD_ERROR(SD_LOG_ERROR, un,
18655 			    "sd_sense_key_unit_attention: "
18656 			    "Could not dispatch sd_target_change_task\n");
18657 		}
18658 	}
18659 
18660 	/*
18661 	 * Update kstat if we haven't done that.
18662 	 */
18663 	if (!kstat_updated) {
18664 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18665 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18666 	}
18667 
18668 do_retry:
18669 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
18670 	    EIO, SD_UA_RETRY_DELAY, NULL);
18671 }
18672 
18673 
18674 
18675 /*
18676  *    Function: sd_sense_key_fail_command
18677  *
18678  * Description: Use to fail a command when we don't like the sense key that
18679  *		was returned.
18680  *
18681  *     Context: May be called from interrupt context
18682  */
18683 
18684 static void
18685 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
18686 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18687 {
18688 	struct sd_sense_info	si;
18689 
18690 	ASSERT(un != NULL);
18691 	ASSERT(mutex_owned(SD_MUTEX(un)));
18692 	ASSERT(bp != NULL);
18693 	ASSERT(xp != NULL);
18694 	ASSERT(pktp != NULL);
18695 
18696 	si.ssi_severity = SCSI_ERR_FATAL;
18697 	si.ssi_pfa_flag = FALSE;
18698 
18699 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18700 	sd_return_failed_command(un, bp, EIO);
18701 }
18702 
18703 
18704 
18705 /*
18706  *    Function: sd_sense_key_blank_check
18707  *
18708  * Description: Recovery actions for a SCSI "Blank Check" sense key.
18709  *		Has no monetary connotation.
18710  *
18711  *     Context: May be called from interrupt context
18712  */
18713 
18714 static void
18715 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
18716 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18717 {
18718 	struct sd_sense_info	si;
18719 
18720 	ASSERT(un != NULL);
18721 	ASSERT(mutex_owned(SD_MUTEX(un)));
18722 	ASSERT(bp != NULL);
18723 	ASSERT(xp != NULL);
18724 	ASSERT(pktp != NULL);
18725 
18726 	/*
18727 	 * Blank check is not fatal for removable devices, therefore
18728 	 * it does not require a console message.
18729 	 */
18730 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
18731 	    SCSI_ERR_FATAL;
18732 	si.ssi_pfa_flag = FALSE;
18733 
18734 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18735 	sd_return_failed_command(un, bp, EIO);
18736 }
18737 
18738 
18739 
18740 
18741 /*
18742  *    Function: sd_sense_key_aborted_command
18743  *
18744  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
18745  *
18746  *     Context: May be called from interrupt context
18747  */
18748 
18749 static void
18750 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
18751 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18752 {
18753 	struct sd_sense_info	si;
18754 
18755 	ASSERT(un != NULL);
18756 	ASSERT(mutex_owned(SD_MUTEX(un)));
18757 	ASSERT(bp != NULL);
18758 	ASSERT(xp != NULL);
18759 	ASSERT(pktp != NULL);
18760 
18761 	si.ssi_severity = SCSI_ERR_FATAL;
18762 	si.ssi_pfa_flag = FALSE;
18763 
18764 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18765 
18766 	/*
18767 	 * This really ought to be a fatal error, but we will retry anyway
18768 	 * as some drives report this as a spurious error.
18769 	 */
18770 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18771 	    &si, EIO, drv_usectohz(100000), NULL);
18772 }
18773 
18774 
18775 
18776 /*
18777  *    Function: sd_sense_key_default
18778  *
18779  * Description: Default recovery action for several SCSI sense keys (basically
18780  *		attempts a retry).
18781  *
18782  *     Context: May be called from interrupt context
18783  */
18784 
18785 static void
18786 sd_sense_key_default(struct sd_lun *un,
18787 	uint8_t *sense_datap,
18788 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18789 {
18790 	struct sd_sense_info	si;
18791 	uint8_t sense_key = scsi_sense_key(sense_datap);
18792 
18793 	ASSERT(un != NULL);
18794 	ASSERT(mutex_owned(SD_MUTEX(un)));
18795 	ASSERT(bp != NULL);
18796 	ASSERT(xp != NULL);
18797 	ASSERT(pktp != NULL);
18798 
18799 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18800 
18801 	/*
18802 	 * Undecoded sense key.	Attempt retries and hope that will fix
18803 	 * the problem.  Otherwise, we're dead.
18804 	 */
18805 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18806 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18807 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18808 	}
18809 
18810 	si.ssi_severity = SCSI_ERR_FATAL;
18811 	si.ssi_pfa_flag = FALSE;
18812 
18813 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18814 	    &si, EIO, (clock_t)0, NULL);
18815 }
18816 
18817 
18818 
18819 /*
18820  *    Function: sd_print_retry_msg
18821  *
18822  * Description: Print a message indicating the retry action being taken.
18823  *
18824  *   Arguments: un - ptr to associated softstate
18825  *		bp - ptr to buf(9S) for the command
18826  *		arg - not used.
18827  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18828  *			or SD_NO_RETRY_ISSUED
18829  *
18830  *     Context: May be called from interrupt context
18831  */
18832 /* ARGSUSED */
18833 static void
18834 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18835 {
18836 	struct sd_xbuf	*xp;
18837 	struct scsi_pkt *pktp;
18838 	char *reasonp;
18839 	char *msgp;
18840 
18841 	ASSERT(un != NULL);
18842 	ASSERT(mutex_owned(SD_MUTEX(un)));
18843 	ASSERT(bp != NULL);
18844 	pktp = SD_GET_PKTP(bp);
18845 	ASSERT(pktp != NULL);
18846 	xp = SD_GET_XBUF(bp);
18847 	ASSERT(xp != NULL);
18848 
18849 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18850 	mutex_enter(&un->un_pm_mutex);
18851 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18852 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18853 	    (pktp->pkt_flags & FLAG_SILENT)) {
18854 		mutex_exit(&un->un_pm_mutex);
18855 		goto update_pkt_reason;
18856 	}
18857 	mutex_exit(&un->un_pm_mutex);
18858 
18859 	/*
18860 	 * Suppress messages if they are all the same pkt_reason; with
18861 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18862 	 * If we are in panic, then suppress the retry messages.
18863 	 */
18864 	switch (flag) {
18865 	case SD_NO_RETRY_ISSUED:
18866 		msgp = "giving up";
18867 		break;
18868 	case SD_IMMEDIATE_RETRY_ISSUED:
18869 	case SD_DELAYED_RETRY_ISSUED:
18870 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18871 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18872 		    (sd_error_level != SCSI_ERR_ALL))) {
18873 			return;
18874 		}
18875 		msgp = "retrying command";
18876 		break;
18877 	default:
18878 		goto update_pkt_reason;
18879 	}
18880 
18881 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18882 	    scsi_rname(pktp->pkt_reason));
18883 
18884 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
18885 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18886 		    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18887 	}
18888 
18889 update_pkt_reason:
18890 	/*
18891 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18892 	 * This is to prevent multiple console messages for the same failure
18893 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18894 	 * when the command is retried successfully because there still may be
18895 	 * more commands coming back with the same value of pktp->pkt_reason.
18896 	 */
18897 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18898 		un->un_last_pkt_reason = pktp->pkt_reason;
18899 	}
18900 }
18901 
18902 
18903 /*
18904  *    Function: sd_print_cmd_incomplete_msg
18905  *
18906  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18907  *
18908  *   Arguments: un - ptr to associated softstate
18909  *		bp - ptr to buf(9S) for the command
18910  *		arg - passed to sd_print_retry_msg()
18911  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18912  *			or SD_NO_RETRY_ISSUED
18913  *
18914  *     Context: May be called from interrupt context
18915  */
18916 
18917 static void
18918 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18919 	int code)
18920 {
18921 	dev_info_t	*dip;
18922 
18923 	ASSERT(un != NULL);
18924 	ASSERT(mutex_owned(SD_MUTEX(un)));
18925 	ASSERT(bp != NULL);
18926 
18927 	switch (code) {
18928 	case SD_NO_RETRY_ISSUED:
18929 		/* Command was failed. Someone turned off this target? */
18930 		if (un->un_state != SD_STATE_OFFLINE) {
18931 			/*
18932 			 * Suppress message if we are detaching and
18933 			 * device has been disconnected
18934 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
18935 			 * private interface and not part of the DDI
18936 			 */
18937 			dip = un->un_sd->sd_dev;
18938 			if (!(DEVI_IS_DETACHING(dip) &&
18939 			    DEVI_IS_DEVICE_REMOVED(dip))) {
18940 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18941 				"disk not responding to selection\n");
18942 			}
18943 			New_state(un, SD_STATE_OFFLINE);
18944 		}
18945 		break;
18946 
18947 	case SD_DELAYED_RETRY_ISSUED:
18948 	case SD_IMMEDIATE_RETRY_ISSUED:
18949 	default:
18950 		/* Command was successfully queued for retry */
18951 		sd_print_retry_msg(un, bp, arg, code);
18952 		break;
18953 	}
18954 }
18955 
18956 
18957 /*
18958  *    Function: sd_pkt_reason_cmd_incomplete
18959  *
18960  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
18961  *
18962  *     Context: May be called from interrupt context
18963  */
18964 
18965 static void
18966 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
18967 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
18968 {
18969 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
18970 
18971 	ASSERT(un != NULL);
18972 	ASSERT(mutex_owned(SD_MUTEX(un)));
18973 	ASSERT(bp != NULL);
18974 	ASSERT(xp != NULL);
18975 	ASSERT(pktp != NULL);
18976 
18977 	/* Do not do a reset if selection did not complete */
18978 	/* Note: Should this not just check the bit? */
18979 	if (pktp->pkt_state != STATE_GOT_BUS) {
18980 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18981 		sd_reset_target(un, pktp);
18982 	}
18983 
18984 	/*
18985 	 * If the target was not successfully selected, then set
18986 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
18987 	 * with the target, and further retries and/or commands are
18988 	 * likely to take a long time.
18989 	 */
18990 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
18991 		flag |= SD_RETRIES_FAILFAST;
18992 	}
18993 
18994 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18995 
18996 	sd_retry_command(un, bp, flag,
18997 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18998 }
18999 
19000 
19001 
19002 /*
19003  *    Function: sd_pkt_reason_cmd_tran_err
19004  *
19005  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
19006  *
19007  *     Context: May be called from interrupt context
19008  */
19009 
19010 static void
19011 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
19012 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19013 {
19014 	ASSERT(un != NULL);
19015 	ASSERT(mutex_owned(SD_MUTEX(un)));
19016 	ASSERT(bp != NULL);
19017 	ASSERT(xp != NULL);
19018 	ASSERT(pktp != NULL);
19019 
19020 	/*
19021 	 * Do not reset if we got a parity error, or if
19022 	 * selection did not complete.
19023 	 */
19024 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19025 	/* Note: Should this not just check the bit for pkt_state? */
19026 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
19027 	    (pktp->pkt_state != STATE_GOT_BUS)) {
19028 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
19029 		sd_reset_target(un, pktp);
19030 	}
19031 
19032 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19033 
19034 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19035 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19036 }
19037 
19038 
19039 
19040 /*
19041  *    Function: sd_pkt_reason_cmd_reset
19042  *
19043  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
19044  *
19045  *     Context: May be called from interrupt context
19046  */
19047 
19048 static void
19049 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
19050 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19051 {
19052 	ASSERT(un != NULL);
19053 	ASSERT(mutex_owned(SD_MUTEX(un)));
19054 	ASSERT(bp != NULL);
19055 	ASSERT(xp != NULL);
19056 	ASSERT(pktp != NULL);
19057 
19058 	/* The target may still be running the command, so try to reset. */
19059 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19060 	sd_reset_target(un, pktp);
19061 
19062 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19063 
19064 	/*
19065 	 * If pkt_reason is CMD_RESET chances are that this pkt got
19066 	 * reset because another target on this bus caused it. The target
19067 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
19068 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
19069 	 */
19070 
19071 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
19072 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19073 }
19074 
19075 
19076 
19077 
19078 /*
19079  *    Function: sd_pkt_reason_cmd_aborted
19080  *
19081  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
19082  *
19083  *     Context: May be called from interrupt context
19084  */
19085 
19086 static void
19087 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
19088 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19089 {
19090 	ASSERT(un != NULL);
19091 	ASSERT(mutex_owned(SD_MUTEX(un)));
19092 	ASSERT(bp != NULL);
19093 	ASSERT(xp != NULL);
19094 	ASSERT(pktp != NULL);
19095 
19096 	/* The target may still be running the command, so try to reset. */
19097 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19098 	sd_reset_target(un, pktp);
19099 
19100 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19101 
19102 	/*
19103 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
19104 	 * aborted because another target on this bus caused it. The target
19105 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
19106 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
19107 	 */
19108 
19109 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
19110 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19111 }
19112 
19113 
19114 
19115 /*
19116  *    Function: sd_pkt_reason_cmd_timeout
19117  *
19118  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
19119  *
19120  *     Context: May be called from interrupt context
19121  */
19122 
19123 static void
19124 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
19125 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19126 {
19127 	ASSERT(un != NULL);
19128 	ASSERT(mutex_owned(SD_MUTEX(un)));
19129 	ASSERT(bp != NULL);
19130 	ASSERT(xp != NULL);
19131 	ASSERT(pktp != NULL);
19132 
19133 
19134 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19135 	sd_reset_target(un, pktp);
19136 
19137 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19138 
19139 	/*
19140 	 * A command timeout indicates that we could not establish
19141 	 * communication with the target, so set SD_RETRIES_FAILFAST
19142 	 * as further retries/commands are likely to take a long time.
19143 	 */
19144 	sd_retry_command(un, bp,
19145 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
19146 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19147 }
19148 
19149 
19150 
19151 /*
19152  *    Function: sd_pkt_reason_cmd_unx_bus_free
19153  *
19154  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
19155  *
19156  *     Context: May be called from interrupt context
19157  */
19158 
19159 static void
19160 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
19161 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19162 {
19163 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
19164 
19165 	ASSERT(un != NULL);
19166 	ASSERT(mutex_owned(SD_MUTEX(un)));
19167 	ASSERT(bp != NULL);
19168 	ASSERT(xp != NULL);
19169 	ASSERT(pktp != NULL);
19170 
19171 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19172 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19173 
19174 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
19175 	    sd_print_retry_msg : NULL;
19176 
19177 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19178 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19179 }
19180 
19181 
19182 /*
19183  *    Function: sd_pkt_reason_cmd_tag_reject
19184  *
19185  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
19186  *
19187  *     Context: May be called from interrupt context
19188  */
19189 
19190 static void
19191 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
19192 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19193 {
19194 	ASSERT(un != NULL);
19195 	ASSERT(mutex_owned(SD_MUTEX(un)));
19196 	ASSERT(bp != NULL);
19197 	ASSERT(xp != NULL);
19198 	ASSERT(pktp != NULL);
19199 
19200 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19201 	pktp->pkt_flags = 0;
19202 	un->un_tagflags = 0;
19203 	if (un->un_f_opt_queueing == TRUE) {
19204 		un->un_throttle = min(un->un_throttle, 3);
19205 	} else {
19206 		un->un_throttle = 1;
19207 	}
19208 	mutex_exit(SD_MUTEX(un));
19209 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
19210 	mutex_enter(SD_MUTEX(un));
19211 
19212 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19213 
19214 	/* Legacy behavior not to check retry counts here. */
19215 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
19216 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19217 }
19218 
19219 
19220 /*
19221  *    Function: sd_pkt_reason_default
19222  *
19223  * Description: Default recovery actions for SCSA pkt_reason values that
19224  *		do not have more explicit recovery actions.
19225  *
19226  *     Context: May be called from interrupt context
19227  */
19228 
19229 static void
19230 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
19231 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19232 {
19233 	ASSERT(un != NULL);
19234 	ASSERT(mutex_owned(SD_MUTEX(un)));
19235 	ASSERT(bp != NULL);
19236 	ASSERT(xp != NULL);
19237 	ASSERT(pktp != NULL);
19238 
19239 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19240 	sd_reset_target(un, pktp);
19241 
19242 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19243 
19244 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19245 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19246 }
19247 
19248 
19249 
19250 /*
19251  *    Function: sd_pkt_status_check_condition
19252  *
19253  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
19254  *
19255  *     Context: May be called from interrupt context
19256  */
19257 
19258 static void
19259 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
19260 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19261 {
19262 	ASSERT(un != NULL);
19263 	ASSERT(mutex_owned(SD_MUTEX(un)));
19264 	ASSERT(bp != NULL);
19265 	ASSERT(xp != NULL);
19266 	ASSERT(pktp != NULL);
19267 
19268 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
19269 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
19270 
19271 	/*
19272 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
19273 	 * command will be retried after the request sense). Otherwise, retry
19274 	 * the command. Note: we are issuing the request sense even though the
19275 	 * retry limit may have been reached for the failed command.
19276 	 */
19277 	if (un->un_f_arq_enabled == FALSE) {
19278 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19279 		    "no ARQ, sending request sense command\n");
19280 		sd_send_request_sense_command(un, bp, pktp);
19281 	} else {
19282 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19283 		    "ARQ,retrying request sense command\n");
19284 #if defined(__i386) || defined(__amd64)
19285 		/*
19286 		 * The SD_RETRY_DELAY value need to be adjusted here
19287 		 * when SD_RETRY_DELAY change in sddef.h
19288 		 */
19289 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19290 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
19291 		    NULL);
19292 #else
19293 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
19294 		    EIO, SD_RETRY_DELAY, NULL);
19295 #endif
19296 	}
19297 
19298 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
19299 }
19300 
19301 
19302 /*
19303  *    Function: sd_pkt_status_busy
19304  *
19305  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
19306  *
19307  *     Context: May be called from interrupt context
19308  */
19309 
19310 static void
19311 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19312 	struct scsi_pkt *pktp)
19313 {
19314 	ASSERT(un != NULL);
19315 	ASSERT(mutex_owned(SD_MUTEX(un)));
19316 	ASSERT(bp != NULL);
19317 	ASSERT(xp != NULL);
19318 	ASSERT(pktp != NULL);
19319 
19320 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19321 	    "sd_pkt_status_busy: entry\n");
19322 
19323 	/* If retries are exhausted, just fail the command. */
19324 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
19325 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19326 		    "device busy too long\n");
19327 		sd_return_failed_command(un, bp, EIO);
19328 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19329 		    "sd_pkt_status_busy: exit\n");
19330 		return;
19331 	}
19332 	xp->xb_retry_count++;
19333 
19334 	/*
19335 	 * Try to reset the target. However, we do not want to perform
19336 	 * more than one reset if the device continues to fail. The reset
19337 	 * will be performed when the retry count reaches the reset
19338 	 * threshold.  This threshold should be set such that at least
19339 	 * one retry is issued before the reset is performed.
19340 	 */
19341 	if (xp->xb_retry_count ==
19342 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
19343 		int rval = 0;
19344 		mutex_exit(SD_MUTEX(un));
19345 		if (un->un_f_allow_bus_device_reset == TRUE) {
19346 			/*
19347 			 * First try to reset the LUN; if we cannot then
19348 			 * try to reset the target.
19349 			 */
19350 			if (un->un_f_lun_reset_enabled == TRUE) {
19351 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19352 				    "sd_pkt_status_busy: RESET_LUN\n");
19353 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19354 			}
19355 			if (rval == 0) {
19356 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19357 				    "sd_pkt_status_busy: RESET_TARGET\n");
19358 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19359 			}
19360 		}
19361 		if (rval == 0) {
19362 			/*
19363 			 * If the RESET_LUN and/or RESET_TARGET failed,
19364 			 * try RESET_ALL
19365 			 */
19366 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19367 			    "sd_pkt_status_busy: RESET_ALL\n");
19368 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
19369 		}
19370 		mutex_enter(SD_MUTEX(un));
19371 		if (rval == 0) {
19372 			/*
19373 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
19374 			 * At this point we give up & fail the command.
19375 			 */
19376 			sd_return_failed_command(un, bp, EIO);
19377 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19378 			    "sd_pkt_status_busy: exit (failed cmd)\n");
19379 			return;
19380 		}
19381 	}
19382 
19383 	/*
19384 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
19385 	 * we have already checked the retry counts above.
19386 	 */
19387 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
19388 	    EIO, un->un_busy_timeout, NULL);
19389 
19390 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19391 	    "sd_pkt_status_busy: exit\n");
19392 }
19393 
19394 
19395 /*
19396  *    Function: sd_pkt_status_reservation_conflict
19397  *
19398  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
19399  *		command status.
19400  *
19401  *     Context: May be called from interrupt context
19402  */
19403 
19404 static void
19405 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
19406 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19407 {
19408 	ASSERT(un != NULL);
19409 	ASSERT(mutex_owned(SD_MUTEX(un)));
19410 	ASSERT(bp != NULL);
19411 	ASSERT(xp != NULL);
19412 	ASSERT(pktp != NULL);
19413 
19414 	/*
19415 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
19416 	 * conflict could be due to various reasons like incorrect keys, not
19417 	 * registered or not reserved etc. So, we return EACCES to the caller.
19418 	 */
19419 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
19420 		int cmd = SD_GET_PKT_OPCODE(pktp);
19421 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
19422 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
19423 			sd_return_failed_command(un, bp, EACCES);
19424 			return;
19425 		}
19426 	}
19427 
19428 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
19429 
19430 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
19431 		if (sd_failfast_enable != 0) {
19432 			/* By definition, we must panic here.... */
19433 			sd_panic_for_res_conflict(un);
19434 			/*NOTREACHED*/
19435 		}
19436 		SD_ERROR(SD_LOG_IO, un,
19437 		    "sd_handle_resv_conflict: Disk Reserved\n");
19438 		sd_return_failed_command(un, bp, EACCES);
19439 		return;
19440 	}
19441 
19442 	/*
19443 	 * 1147670: retry only if sd_retry_on_reservation_conflict
19444 	 * property is set (default is 1). Retries will not succeed
19445 	 * on a disk reserved by another initiator. HA systems
19446 	 * may reset this via sd.conf to avoid these retries.
19447 	 *
19448 	 * Note: The legacy return code for this failure is EIO, however EACCES
19449 	 * seems more appropriate for a reservation conflict.
19450 	 */
19451 	if (sd_retry_on_reservation_conflict == 0) {
19452 		SD_ERROR(SD_LOG_IO, un,
19453 		    "sd_handle_resv_conflict: Device Reserved\n");
19454 		sd_return_failed_command(un, bp, EIO);
19455 		return;
19456 	}
19457 
19458 	/*
19459 	 * Retry the command if we can.
19460 	 *
19461 	 * Note: The legacy return code for this failure is EIO, however EACCES
19462 	 * seems more appropriate for a reservation conflict.
19463 	 */
19464 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19465 	    (clock_t)2, NULL);
19466 }
19467 
19468 
19469 
19470 /*
19471  *    Function: sd_pkt_status_qfull
19472  *
19473  * Description: Handle a QUEUE FULL condition from the target.  This can
19474  *		occur if the HBA does not handle the queue full condition.
19475  *		(Basically this means third-party HBAs as Sun HBAs will
19476  *		handle the queue full condition.)  Note that if there are
19477  *		some commands already in the transport, then the queue full
19478  *		has occurred because the queue for this nexus is actually
19479  *		full. If there are no commands in the transport, then the
19480  *		queue full is resulting from some other initiator or lun
19481  *		consuming all the resources at the target.
19482  *
19483  *     Context: May be called from interrupt context
19484  */
19485 
19486 static void
19487 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
19488 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
19489 {
19490 	ASSERT(un != NULL);
19491 	ASSERT(mutex_owned(SD_MUTEX(un)));
19492 	ASSERT(bp != NULL);
19493 	ASSERT(xp != NULL);
19494 	ASSERT(pktp != NULL);
19495 
19496 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19497 	    "sd_pkt_status_qfull: entry\n");
19498 
19499 	/*
19500 	 * Just lower the QFULL throttle and retry the command.  Note that
19501 	 * we do not limit the number of retries here.
19502 	 */
19503 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
19504 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
19505 	    SD_RESTART_TIMEOUT, NULL);
19506 
19507 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19508 	    "sd_pkt_status_qfull: exit\n");
19509 }
19510 
19511 
19512 /*
19513  *    Function: sd_reset_target
19514  *
19515  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
19516  *		RESET_TARGET, or RESET_ALL.
19517  *
19518  *     Context: May be called under interrupt context.
19519  */
19520 
19521 static void
19522 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
19523 {
19524 	int rval = 0;
19525 
19526 	ASSERT(un != NULL);
19527 	ASSERT(mutex_owned(SD_MUTEX(un)));
19528 	ASSERT(pktp != NULL);
19529 
19530 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
19531 
19532 	/*
19533 	 * No need to reset if the transport layer has already done so.
19534 	 */
19535 	if ((pktp->pkt_statistics &
19536 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
19537 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19538 		    "sd_reset_target: no reset\n");
19539 		return;
19540 	}
19541 
19542 	mutex_exit(SD_MUTEX(un));
19543 
19544 	if (un->un_f_allow_bus_device_reset == TRUE) {
19545 		if (un->un_f_lun_reset_enabled == TRUE) {
19546 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19547 			    "sd_reset_target: RESET_LUN\n");
19548 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19549 		}
19550 		if (rval == 0) {
19551 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19552 			    "sd_reset_target: RESET_TARGET\n");
19553 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19554 		}
19555 	}
19556 
19557 	if (rval == 0) {
19558 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19559 		    "sd_reset_target: RESET_ALL\n");
19560 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
19561 	}
19562 
19563 	mutex_enter(SD_MUTEX(un));
19564 
19565 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
19566 }
19567 
19568 /*
19569  *    Function: sd_target_change_task
19570  *
19571  * Description: Handle dynamic target change
19572  *
19573  *     Context: Executes in a taskq() thread context
19574  */
19575 static void
19576 sd_target_change_task(void *arg)
19577 {
19578 	struct sd_lun		*un = arg;
19579 	uint64_t		capacity;
19580 	diskaddr_t		label_cap;
19581 	uint_t			lbasize;
19582 	sd_ssc_t		*ssc;
19583 
19584 	ASSERT(un != NULL);
19585 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19586 
19587 	if ((un->un_f_blockcount_is_valid == FALSE) ||
19588 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
19589 		return;
19590 	}
19591 
19592 	ssc = sd_ssc_init(un);
19593 
19594 	if (sd_send_scsi_READ_CAPACITY(ssc, &capacity,
19595 	    &lbasize, SD_PATH_DIRECT) != 0) {
19596 		SD_ERROR(SD_LOG_ERROR, un,
19597 		    "sd_target_change_task: fail to read capacity\n");
19598 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19599 		goto task_exit;
19600 	}
19601 
19602 	mutex_enter(SD_MUTEX(un));
19603 	if (capacity <= un->un_blockcount) {
19604 		mutex_exit(SD_MUTEX(un));
19605 		goto task_exit;
19606 	}
19607 
19608 	sd_update_block_info(un, lbasize, capacity);
19609 	mutex_exit(SD_MUTEX(un));
19610 
19611 	/*
19612 	 * If lun is EFI labeled and lun capacity is greater than the
19613 	 * capacity contained in the label, log a sys event.
19614 	 */
19615 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
19616 	    (void*)SD_PATH_DIRECT) == 0) {
19617 		mutex_enter(SD_MUTEX(un));
19618 		if (un->un_f_blockcount_is_valid &&
19619 		    un->un_blockcount > label_cap) {
19620 			mutex_exit(SD_MUTEX(un));
19621 			sd_log_lun_expansion_event(un, KM_SLEEP);
19622 		} else {
19623 			mutex_exit(SD_MUTEX(un));
19624 		}
19625 	}
19626 
19627 task_exit:
19628 	sd_ssc_fini(ssc);
19629 }
19630 
19631 
19632 /*
19633  *    Function: sd_log_dev_status_event
19634  *
19635  * Description: Log EC_dev_status sysevent
19636  *
19637  *     Context: Never called from interrupt context
19638  */
19639 static void
19640 sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag)
19641 {
19642 	int err;
19643 	char			*path;
19644 	nvlist_t		*attr_list;
19645 
19646 	/* Allocate and build sysevent attribute list */
19647 	err = nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
19648 	if (err != 0) {
19649 		SD_ERROR(SD_LOG_ERROR, un,
19650 		    "sd_log_dev_status_event: fail to allocate space\n");
19651 		return;
19652 	}
19653 
19654 	path = kmem_alloc(MAXPATHLEN, km_flag);
19655 	if (path == NULL) {
19656 		nvlist_free(attr_list);
19657 		SD_ERROR(SD_LOG_ERROR, un,
19658 		    "sd_log_dev_status_event: fail to allocate space\n");
19659 		return;
19660 	}
19661 	/*
19662 	 * Add path attribute to identify the lun.
19663 	 * We are using minor node 'a' as the sysevent attribute.
19664 	 */
19665 	(void) snprintf(path, MAXPATHLEN, "/devices");
19666 	(void) ddi_pathname(SD_DEVINFO(un), path + strlen(path));
19667 	(void) snprintf(path + strlen(path), MAXPATHLEN - strlen(path),
19668 	    ":a");
19669 
19670 	err = nvlist_add_string(attr_list, DEV_PHYS_PATH, path);
19671 	if (err != 0) {
19672 		nvlist_free(attr_list);
19673 		kmem_free(path, MAXPATHLEN);
19674 		SD_ERROR(SD_LOG_ERROR, un,
19675 		    "sd_log_dev_status_event: fail to add attribute\n");
19676 		return;
19677 	}
19678 
19679 	/* Log dynamic lun expansion sysevent */
19680 	err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR, EC_DEV_STATUS,
19681 	    esc, attr_list, NULL, km_flag);
19682 	if (err != DDI_SUCCESS) {
19683 		SD_ERROR(SD_LOG_ERROR, un,
19684 		    "sd_log_dev_status_event: fail to log sysevent\n");
19685 	}
19686 
19687 	nvlist_free(attr_list);
19688 	kmem_free(path, MAXPATHLEN);
19689 }
19690 
19691 
19692 /*
19693  *    Function: sd_log_lun_expansion_event
19694  *
19695  * Description: Log lun expansion sys event
19696  *
19697  *     Context: Never called from interrupt context
19698  */
19699 static void
19700 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
19701 {
19702 	sd_log_dev_status_event(un, ESC_DEV_DLE, km_flag);
19703 }
19704 
19705 
19706 /*
19707  *    Function: sd_log_eject_request_event
19708  *
19709  * Description: Log eject request sysevent
19710  *
19711  *     Context: Never called from interrupt context
19712  */
19713 static void
19714 sd_log_eject_request_event(struct sd_lun *un, int km_flag)
19715 {
19716 	sd_log_dev_status_event(un, ESC_DEV_EJECT_REQUEST, km_flag);
19717 }
19718 
19719 
19720 /*
19721  *    Function: sd_media_change_task
19722  *
19723  * Description: Recovery action for CDROM to become available.
19724  *
19725  *     Context: Executes in a taskq() thread context
19726  */
19727 
19728 static void
19729 sd_media_change_task(void *arg)
19730 {
19731 	struct	scsi_pkt	*pktp = arg;
19732 	struct	sd_lun		*un;
19733 	struct	buf		*bp;
19734 	struct	sd_xbuf		*xp;
19735 	int	err		= 0;
19736 	int	retry_count	= 0;
19737 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
19738 	struct	sd_sense_info	si;
19739 
19740 	ASSERT(pktp != NULL);
19741 	bp = (struct buf *)pktp->pkt_private;
19742 	ASSERT(bp != NULL);
19743 	xp = SD_GET_XBUF(bp);
19744 	ASSERT(xp != NULL);
19745 	un = SD_GET_UN(bp);
19746 	ASSERT(un != NULL);
19747 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19748 	ASSERT(un->un_f_monitor_media_state);
19749 
19750 	si.ssi_severity = SCSI_ERR_INFO;
19751 	si.ssi_pfa_flag = FALSE;
19752 
19753 	/*
19754 	 * When a reset is issued on a CDROM, it takes a long time to
19755 	 * recover. First few attempts to read capacity and other things
19756 	 * related to handling unit attention fail (with a ASC 0x4 and
19757 	 * ASCQ 0x1). In that case we want to do enough retries and we want
19758 	 * to limit the retries in other cases of genuine failures like
19759 	 * no media in drive.
19760 	 */
19761 	while (retry_count++ < retry_limit) {
19762 		if ((err = sd_handle_mchange(un)) == 0) {
19763 			break;
19764 		}
19765 		if (err == EAGAIN) {
19766 			retry_limit = SD_UNIT_ATTENTION_RETRY;
19767 		}
19768 		/* Sleep for 0.5 sec. & try again */
19769 		delay(drv_usectohz(500000));
19770 	}
19771 
19772 	/*
19773 	 * Dispatch (retry or fail) the original command here,
19774 	 * along with appropriate console messages....
19775 	 *
19776 	 * Must grab the mutex before calling sd_retry_command,
19777 	 * sd_print_sense_msg and sd_return_failed_command.
19778 	 */
19779 	mutex_enter(SD_MUTEX(un));
19780 	if (err != SD_CMD_SUCCESS) {
19781 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
19782 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
19783 		si.ssi_severity = SCSI_ERR_FATAL;
19784 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
19785 		sd_return_failed_command(un, bp, EIO);
19786 	} else {
19787 		sd_retry_command(un, bp, SD_RETRIES_UA, sd_print_sense_msg,
19788 		    &si, EIO, (clock_t)0, NULL);
19789 	}
19790 	mutex_exit(SD_MUTEX(un));
19791 }
19792 
19793 
19794 
19795 /*
19796  *    Function: sd_handle_mchange
19797  *
19798  * Description: Perform geometry validation & other recovery when CDROM
19799  *		has been removed from drive.
19800  *
19801  * Return Code: 0 for success
19802  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
19803  *		sd_send_scsi_READ_CAPACITY()
19804  *
19805  *     Context: Executes in a taskq() thread context
19806  */
19807 
19808 static int
19809 sd_handle_mchange(struct sd_lun *un)
19810 {
19811 	uint64_t	capacity;
19812 	uint32_t	lbasize;
19813 	int		rval;
19814 	sd_ssc_t	*ssc;
19815 
19816 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19817 	ASSERT(un->un_f_monitor_media_state);
19818 
19819 	ssc = sd_ssc_init(un);
19820 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
19821 	    SD_PATH_DIRECT_PRIORITY);
19822 
19823 	if (rval != 0)
19824 		goto failed;
19825 
19826 	mutex_enter(SD_MUTEX(un));
19827 	sd_update_block_info(un, lbasize, capacity);
19828 
19829 	if (un->un_errstats != NULL) {
19830 		struct	sd_errstats *stp =
19831 		    (struct sd_errstats *)un->un_errstats->ks_data;
19832 		stp->sd_capacity.value.ui64 = (uint64_t)
19833 		    ((uint64_t)un->un_blockcount *
19834 		    (uint64_t)un->un_tgt_blocksize);
19835 	}
19836 
19837 	/*
19838 	 * Check if the media in the device is writable or not
19839 	 */
19840 	if (ISCD(un)) {
19841 		sd_check_for_writable_cd(ssc, SD_PATH_DIRECT_PRIORITY);
19842 	}
19843 
19844 	/*
19845 	 * Note: Maybe let the strategy/partitioning chain worry about getting
19846 	 * valid geometry.
19847 	 */
19848 	mutex_exit(SD_MUTEX(un));
19849 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
19850 
19851 
19852 	if (cmlb_validate(un->un_cmlbhandle, 0,
19853 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
19854 		sd_ssc_fini(ssc);
19855 		return (EIO);
19856 	} else {
19857 		if (un->un_f_pkstats_enabled) {
19858 			sd_set_pstats(un);
19859 			SD_TRACE(SD_LOG_IO_PARTITION, un,
19860 			    "sd_handle_mchange: un:0x%p pstats created and "
19861 			    "set\n", un);
19862 		}
19863 	}
19864 
19865 	/*
19866 	 * Try to lock the door
19867 	 */
19868 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
19869 	    SD_PATH_DIRECT_PRIORITY);
19870 failed:
19871 	if (rval != 0)
19872 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19873 	sd_ssc_fini(ssc);
19874 	return (rval);
19875 }
19876 
19877 
19878 /*
19879  *    Function: sd_send_scsi_DOORLOCK
19880  *
19881  * Description: Issue the scsi DOOR LOCK command
19882  *
19883  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19884  *                      structure for this target.
19885  *		flag  - SD_REMOVAL_ALLOW
19886  *			SD_REMOVAL_PREVENT
19887  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19888  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19889  *			to use the USCSI "direct" chain and bypass the normal
19890  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19891  *			command is issued as part of an error recovery action.
19892  *
19893  * Return Code: 0   - Success
19894  *		errno return code from sd_ssc_send()
19895  *
19896  *     Context: Can sleep.
19897  */
19898 
19899 static int
19900 sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag)
19901 {
19902 	struct scsi_extended_sense	sense_buf;
19903 	union scsi_cdb		cdb;
19904 	struct uscsi_cmd	ucmd_buf;
19905 	int			status;
19906 	struct sd_lun		*un;
19907 
19908 	ASSERT(ssc != NULL);
19909 	un = ssc->ssc_un;
19910 	ASSERT(un != NULL);
19911 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19912 
19913 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
19914 
19915 	/* already determined doorlock is not supported, fake success */
19916 	if (un->un_f_doorlock_supported == FALSE) {
19917 		return (0);
19918 	}
19919 
19920 	/*
19921 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
19922 	 * ignore the command so we can complete the eject
19923 	 * operation.
19924 	 */
19925 	if (flag == SD_REMOVAL_PREVENT) {
19926 		mutex_enter(SD_MUTEX(un));
19927 		if (un->un_f_ejecting == TRUE) {
19928 			mutex_exit(SD_MUTEX(un));
19929 			return (EAGAIN);
19930 		}
19931 		mutex_exit(SD_MUTEX(un));
19932 	}
19933 
19934 	bzero(&cdb, sizeof (cdb));
19935 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19936 
19937 	cdb.scc_cmd = SCMD_DOORLOCK;
19938 	cdb.cdb_opaque[4] = (uchar_t)flag;
19939 
19940 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19941 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19942 	ucmd_buf.uscsi_bufaddr	= NULL;
19943 	ucmd_buf.uscsi_buflen	= 0;
19944 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19945 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19946 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19947 	ucmd_buf.uscsi_timeout	= 15;
19948 
19949 	SD_TRACE(SD_LOG_IO, un,
19950 	    "sd_send_scsi_DOORLOCK: returning sd_ssc_send\n");
19951 
19952 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19953 	    UIO_SYSSPACE, path_flag);
19954 
19955 	if (status == 0)
19956 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19957 
19958 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
19959 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19960 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
19961 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19962 
19963 		/* fake success and skip subsequent doorlock commands */
19964 		un->un_f_doorlock_supported = FALSE;
19965 		return (0);
19966 	}
19967 
19968 	return (status);
19969 }
19970 
19971 /*
19972  *    Function: sd_send_scsi_READ_CAPACITY
19973  *
19974  * Description: This routine uses the scsi READ CAPACITY command to determine
19975  *		the device capacity in number of blocks and the device native
19976  *		block size. If this function returns a failure, then the
19977  *		values in *capp and *lbap are undefined.  If the capacity
19978  *		returned is 0xffffffff then the lun is too large for a
19979  *		normal READ CAPACITY command and the results of a
19980  *		READ CAPACITY 16 will be used instead.
19981  *
19982  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
19983  *		capp - ptr to unsigned 64-bit variable to receive the
19984  *			capacity value from the command.
19985  *		lbap - ptr to unsigned 32-bit varaible to receive the
19986  *			block size value from the command
19987  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19988  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19989  *			to use the USCSI "direct" chain and bypass the normal
19990  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19991  *			command is issued as part of an error recovery action.
19992  *
19993  * Return Code: 0   - Success
19994  *		EIO - IO error
19995  *		EACCES - Reservation conflict detected
19996  *		EAGAIN - Device is becoming ready
19997  *		errno return code from sd_ssc_send()
19998  *
19999  *     Context: Can sleep.  Blocks until command completes.
20000  */
20001 
20002 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
20003 
20004 static int
20005 sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
20006 	int path_flag)
20007 {
20008 	struct	scsi_extended_sense	sense_buf;
20009 	struct	uscsi_cmd	ucmd_buf;
20010 	union	scsi_cdb	cdb;
20011 	uint32_t		*capacity_buf;
20012 	uint64_t		capacity;
20013 	uint32_t		lbasize;
20014 	uint32_t		pbsize;
20015 	int			status;
20016 	struct sd_lun		*un;
20017 
20018 	ASSERT(ssc != NULL);
20019 
20020 	un = ssc->ssc_un;
20021 	ASSERT(un != NULL);
20022 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20023 	ASSERT(capp != NULL);
20024 	ASSERT(lbap != NULL);
20025 
20026 	SD_TRACE(SD_LOG_IO, un,
20027 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20028 
20029 	/*
20030 	 * First send a READ_CAPACITY command to the target.
20031 	 * (This command is mandatory under SCSI-2.)
20032 	 *
20033 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
20034 	 * Medium Indicator bit is cleared.  The address field must be
20035 	 * zero if the PMI bit is zero.
20036 	 */
20037 	bzero(&cdb, sizeof (cdb));
20038 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20039 
20040 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
20041 
20042 	cdb.scc_cmd = SCMD_READ_CAPACITY;
20043 
20044 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20045 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20046 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
20047 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
20048 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20049 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20050 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20051 	ucmd_buf.uscsi_timeout	= 60;
20052 
20053 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20054 	    UIO_SYSSPACE, path_flag);
20055 
20056 	switch (status) {
20057 	case 0:
20058 		/* Return failure if we did not get valid capacity data. */
20059 		if (ucmd_buf.uscsi_resid != 0) {
20060 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20061 			    "sd_send_scsi_READ_CAPACITY received invalid "
20062 			    "capacity data");
20063 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20064 			return (EIO);
20065 		}
20066 		/*
20067 		 * Read capacity and block size from the READ CAPACITY 10 data.
20068 		 * This data may be adjusted later due to device specific
20069 		 * issues.
20070 		 *
20071 		 * According to the SCSI spec, the READ CAPACITY 10
20072 		 * command returns the following:
20073 		 *
20074 		 *  bytes 0-3: Maximum logical block address available.
20075 		 *		(MSB in byte:0 & LSB in byte:3)
20076 		 *
20077 		 *  bytes 4-7: Block length in bytes
20078 		 *		(MSB in byte:4 & LSB in byte:7)
20079 		 *
20080 		 */
20081 		capacity = BE_32(capacity_buf[0]);
20082 		lbasize = BE_32(capacity_buf[1]);
20083 
20084 		/*
20085 		 * Done with capacity_buf
20086 		 */
20087 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20088 
20089 		/*
20090 		 * if the reported capacity is set to all 0xf's, then
20091 		 * this disk is too large and requires SBC-2 commands.
20092 		 * Reissue the request using READ CAPACITY 16.
20093 		 */
20094 		if (capacity == 0xffffffff) {
20095 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20096 			status = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity,
20097 			    &lbasize, &pbsize, path_flag);
20098 			if (status != 0) {
20099 				return (status);
20100 			} else {
20101 				goto rc16_done;
20102 			}
20103 		}
20104 		break;	/* Success! */
20105 	case EIO:
20106 		switch (ucmd_buf.uscsi_status) {
20107 		case STATUS_RESERVATION_CONFLICT:
20108 			status = EACCES;
20109 			break;
20110 		case STATUS_CHECK:
20111 			/*
20112 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20113 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20114 			 */
20115 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20116 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20117 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20118 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20119 				return (EAGAIN);
20120 			}
20121 			break;
20122 		default:
20123 			break;
20124 		}
20125 		/* FALLTHRU */
20126 	default:
20127 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20128 		return (status);
20129 	}
20130 
20131 	/*
20132 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20133 	 * (2352 and 0 are common) so for these devices always force the value
20134 	 * to 2048 as required by the ATAPI specs.
20135 	 */
20136 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20137 		lbasize = 2048;
20138 	}
20139 
20140 	/*
20141 	 * Get the maximum LBA value from the READ CAPACITY data.
20142 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20143 	 * was cleared when issuing the command. This means that the LBA
20144 	 * returned from the device is the LBA of the last logical block
20145 	 * on the logical unit.  The actual logical block count will be
20146 	 * this value plus one.
20147 	 */
20148 	capacity += 1;
20149 
20150 	/*
20151 	 * Currently, for removable media, the capacity is saved in terms
20152 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20153 	 */
20154 	if (un->un_f_has_removable_media)
20155 		capacity *= (lbasize / un->un_sys_blocksize);
20156 
20157 rc16_done:
20158 
20159 	/*
20160 	 * Copy the values from the READ CAPACITY command into the space
20161 	 * provided by the caller.
20162 	 */
20163 	*capp = capacity;
20164 	*lbap = lbasize;
20165 
20166 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
20167 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
20168 
20169 	/*
20170 	 * Both the lbasize and capacity from the device must be nonzero,
20171 	 * otherwise we assume that the values are not valid and return
20172 	 * failure to the caller. (4203735)
20173 	 */
20174 	if ((capacity == 0) || (lbasize == 0)) {
20175 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20176 		    "sd_send_scsi_READ_CAPACITY received invalid value "
20177 		    "capacity %llu lbasize %d", capacity, lbasize);
20178 		return (EIO);
20179 	}
20180 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20181 	return (0);
20182 }
20183 
20184 /*
20185  *    Function: sd_send_scsi_READ_CAPACITY_16
20186  *
20187  * Description: This routine uses the scsi READ CAPACITY 16 command to
20188  *		determine the device capacity in number of blocks and the
20189  *		device native block size.  If this function returns a failure,
20190  *		then the values in *capp and *lbap are undefined.
20191  *		This routine should be called by sd_send_scsi_READ_CAPACITY
20192  *              which will apply any device specific adjustments to capacity
20193  *              and lbasize. One exception is it is also called by
20194  *              sd_get_media_info_ext. In that function, there is no need to
20195  *              adjust the capacity and lbasize.
20196  *
20197  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
20198  *		capp - ptr to unsigned 64-bit variable to receive the
20199  *			capacity value from the command.
20200  *		lbap - ptr to unsigned 32-bit varaible to receive the
20201  *			block size value from the command
20202  *              psp  - ptr to unsigned 32-bit variable to receive the
20203  *                      physical block size value from the command
20204  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20205  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20206  *			to use the USCSI "direct" chain and bypass the normal
20207  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
20208  *			this command is issued as part of an error recovery
20209  *			action.
20210  *
20211  * Return Code: 0   - Success
20212  *		EIO - IO error
20213  *		EACCES - Reservation conflict detected
20214  *		EAGAIN - Device is becoming ready
20215  *		errno return code from sd_ssc_send()
20216  *
20217  *     Context: Can sleep.  Blocks until command completes.
20218  */
20219 
20220 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
20221 
20222 static int
20223 sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
20224 	uint32_t *lbap, uint32_t *psp, int path_flag)
20225 {
20226 	struct	scsi_extended_sense	sense_buf;
20227 	struct	uscsi_cmd	ucmd_buf;
20228 	union	scsi_cdb	cdb;
20229 	uint64_t		*capacity16_buf;
20230 	uint64_t		capacity;
20231 	uint32_t		lbasize;
20232 	uint32_t		pbsize;
20233 	uint32_t		lbpb_exp;
20234 	int			status;
20235 	struct sd_lun		*un;
20236 
20237 	ASSERT(ssc != NULL);
20238 
20239 	un = ssc->ssc_un;
20240 	ASSERT(un != NULL);
20241 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20242 	ASSERT(capp != NULL);
20243 	ASSERT(lbap != NULL);
20244 
20245 	SD_TRACE(SD_LOG_IO, un,
20246 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20247 
20248 	/*
20249 	 * First send a READ_CAPACITY_16 command to the target.
20250 	 *
20251 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
20252 	 * Medium Indicator bit is cleared.  The address field must be
20253 	 * zero if the PMI bit is zero.
20254 	 */
20255 	bzero(&cdb, sizeof (cdb));
20256 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20257 
20258 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
20259 
20260 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20261 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
20262 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
20263 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
20264 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20265 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20266 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20267 	ucmd_buf.uscsi_timeout	= 60;
20268 
20269 	/*
20270 	 * Read Capacity (16) is a Service Action In command.  One
20271 	 * command byte (0x9E) is overloaded for multiple operations,
20272 	 * with the second CDB byte specifying the desired operation
20273 	 */
20274 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
20275 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
20276 
20277 	/*
20278 	 * Fill in allocation length field
20279 	 */
20280 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
20281 
20282 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20283 	    UIO_SYSSPACE, path_flag);
20284 
20285 	switch (status) {
20286 	case 0:
20287 		/* Return failure if we did not get valid capacity data. */
20288 		if (ucmd_buf.uscsi_resid > 20) {
20289 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20290 			    "sd_send_scsi_READ_CAPACITY_16 received invalid "
20291 			    "capacity data");
20292 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20293 			return (EIO);
20294 		}
20295 
20296 		/*
20297 		 * Read capacity and block size from the READ CAPACITY 16 data.
20298 		 * This data may be adjusted later due to device specific
20299 		 * issues.
20300 		 *
20301 		 * According to the SCSI spec, the READ CAPACITY 16
20302 		 * command returns the following:
20303 		 *
20304 		 *  bytes 0-7: Maximum logical block address available.
20305 		 *		(MSB in byte:0 & LSB in byte:7)
20306 		 *
20307 		 *  bytes 8-11: Block length in bytes
20308 		 *		(MSB in byte:8 & LSB in byte:11)
20309 		 *
20310 		 *  byte 13: LOGICAL BLOCKS PER PHYSICAL BLOCK EXPONENT
20311 		 */
20312 		capacity = BE_64(capacity16_buf[0]);
20313 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
20314 		lbpb_exp = (BE_64(capacity16_buf[1]) >> 16) & 0x0f;
20315 
20316 		pbsize = lbasize << lbpb_exp;
20317 
20318 		/*
20319 		 * Done with capacity16_buf
20320 		 */
20321 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20322 
20323 		/*
20324 		 * if the reported capacity is set to all 0xf's, then
20325 		 * this disk is too large.  This could only happen with
20326 		 * a device that supports LBAs larger than 64 bits which
20327 		 * are not defined by any current T10 standards.
20328 		 */
20329 		if (capacity == 0xffffffffffffffff) {
20330 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20331 			    "disk is too large");
20332 			return (EIO);
20333 		}
20334 		break;	/* Success! */
20335 	case EIO:
20336 		switch (ucmd_buf.uscsi_status) {
20337 		case STATUS_RESERVATION_CONFLICT:
20338 			status = EACCES;
20339 			break;
20340 		case STATUS_CHECK:
20341 			/*
20342 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20343 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20344 			 */
20345 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20346 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20347 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20348 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20349 				return (EAGAIN);
20350 			}
20351 			break;
20352 		default:
20353 			break;
20354 		}
20355 		/* FALLTHRU */
20356 	default:
20357 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20358 		return (status);
20359 	}
20360 
20361 	/*
20362 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20363 	 * (2352 and 0 are common) so for these devices always force the value
20364 	 * to 2048 as required by the ATAPI specs.
20365 	 */
20366 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20367 		lbasize = 2048;
20368 	}
20369 
20370 	/*
20371 	 * Get the maximum LBA value from the READ CAPACITY 16 data.
20372 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20373 	 * was cleared when issuing the command. This means that the LBA
20374 	 * returned from the device is the LBA of the last logical block
20375 	 * on the logical unit.  The actual logical block count will be
20376 	 * this value plus one.
20377 	 */
20378 	capacity += 1;
20379 
20380 	/*
20381 	 * Currently, for removable media, the capacity is saved in terms
20382 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20383 	 */
20384 	if (un->un_f_has_removable_media)
20385 		capacity *= (lbasize / un->un_sys_blocksize);
20386 
20387 	*capp = capacity;
20388 	*lbap = lbasize;
20389 	*psp = pbsize;
20390 
20391 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
20392 	    "capacity:0x%llx  lbasize:0x%x, pbsize: 0x%x\n",
20393 	    capacity, lbasize, pbsize);
20394 
20395 	if ((capacity == 0) || (lbasize == 0) || (pbsize == 0)) {
20396 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20397 		    "sd_send_scsi_READ_CAPACITY_16 received invalid value "
20398 		    "capacity %llu lbasize %d pbsize %d", capacity, lbasize);
20399 		return (EIO);
20400 	}
20401 
20402 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20403 	return (0);
20404 }
20405 
20406 
20407 /*
20408  *    Function: sd_send_scsi_START_STOP_UNIT
20409  *
20410  * Description: Issue a scsi START STOP UNIT command to the target.
20411  *
20412  *   Arguments: ssc    - ssc contatins pointer to driver soft state (unit)
20413  *                       structure for this target.
20414  *      pc_flag - SD_POWER_CONDITION
20415  *                SD_START_STOP
20416  *		flag  - SD_TARGET_START
20417  *			SD_TARGET_STOP
20418  *			SD_TARGET_EJECT
20419  *			SD_TARGET_CLOSE
20420  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20421  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20422  *			to use the USCSI "direct" chain and bypass the normal
20423  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
20424  *			command is issued as part of an error recovery action.
20425  *
20426  * Return Code: 0   - Success
20427  *		EIO - IO error
20428  *		EACCES - Reservation conflict detected
20429  *		ENXIO  - Not Ready, medium not present
20430  *		errno return code from sd_ssc_send()
20431  *
20432  *     Context: Can sleep.
20433  */
20434 
20435 static int
20436 sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag, int flag,
20437     int path_flag)
20438 {
20439 	struct	scsi_extended_sense	sense_buf;
20440 	union scsi_cdb		cdb;
20441 	struct uscsi_cmd	ucmd_buf;
20442 	int			status;
20443 	struct sd_lun		*un;
20444 
20445 	ASSERT(ssc != NULL);
20446 	un = ssc->ssc_un;
20447 	ASSERT(un != NULL);
20448 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20449 
20450 	SD_TRACE(SD_LOG_IO, un,
20451 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
20452 
20453 	if (un->un_f_check_start_stop &&
20454 	    (pc_flag == SD_START_STOP) &&
20455 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
20456 	    (un->un_f_start_stop_supported != TRUE)) {
20457 		return (0);
20458 	}
20459 
20460 	/*
20461 	 * If we are performing an eject operation and
20462 	 * we receive any command other than SD_TARGET_EJECT
20463 	 * we should immediately return.
20464 	 */
20465 	if (flag != SD_TARGET_EJECT) {
20466 		mutex_enter(SD_MUTEX(un));
20467 		if (un->un_f_ejecting == TRUE) {
20468 			mutex_exit(SD_MUTEX(un));
20469 			return (EAGAIN);
20470 		}
20471 		mutex_exit(SD_MUTEX(un));
20472 	}
20473 
20474 	bzero(&cdb, sizeof (cdb));
20475 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20476 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20477 
20478 	cdb.scc_cmd = SCMD_START_STOP;
20479 	cdb.cdb_opaque[4] = (pc_flag == SD_POWER_CONDITION) ?
20480 	    (uchar_t)(flag << 4) : (uchar_t)flag;
20481 
20482 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20483 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20484 	ucmd_buf.uscsi_bufaddr	= NULL;
20485 	ucmd_buf.uscsi_buflen	= 0;
20486 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20487 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20488 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20489 	ucmd_buf.uscsi_timeout	= 200;
20490 
20491 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20492 	    UIO_SYSSPACE, path_flag);
20493 
20494 	switch (status) {
20495 	case 0:
20496 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20497 		break;	/* Success! */
20498 	case EIO:
20499 		switch (ucmd_buf.uscsi_status) {
20500 		case STATUS_RESERVATION_CONFLICT:
20501 			status = EACCES;
20502 			break;
20503 		case STATUS_CHECK:
20504 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
20505 				switch (scsi_sense_key(
20506 				    (uint8_t *)&sense_buf)) {
20507 				case KEY_ILLEGAL_REQUEST:
20508 					status = ENOTSUP;
20509 					break;
20510 				case KEY_NOT_READY:
20511 					if (scsi_sense_asc(
20512 					    (uint8_t *)&sense_buf)
20513 					    == 0x3A) {
20514 						status = ENXIO;
20515 					}
20516 					break;
20517 				default:
20518 					break;
20519 				}
20520 			}
20521 			break;
20522 		default:
20523 			break;
20524 		}
20525 		break;
20526 	default:
20527 		break;
20528 	}
20529 
20530 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
20531 
20532 	return (status);
20533 }
20534 
20535 
20536 /*
20537  *    Function: sd_start_stop_unit_callback
20538  *
20539  * Description: timeout(9F) callback to begin recovery process for a
20540  *		device that has spun down.
20541  *
20542  *   Arguments: arg - pointer to associated softstate struct.
20543  *
20544  *     Context: Executes in a timeout(9F) thread context
20545  */
20546 
20547 static void
20548 sd_start_stop_unit_callback(void *arg)
20549 {
20550 	struct sd_lun	*un = arg;
20551 	ASSERT(un != NULL);
20552 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20553 
20554 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
20555 
20556 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
20557 }
20558 
20559 
20560 /*
20561  *    Function: sd_start_stop_unit_task
20562  *
20563  * Description: Recovery procedure when a drive is spun down.
20564  *
20565  *   Arguments: arg - pointer to associated softstate struct.
20566  *
20567  *     Context: Executes in a taskq() thread context
20568  */
20569 
20570 static void
20571 sd_start_stop_unit_task(void *arg)
20572 {
20573 	struct sd_lun	*un = arg;
20574 	sd_ssc_t	*ssc;
20575 	int		power_level;
20576 	int		rval;
20577 
20578 	ASSERT(un != NULL);
20579 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20580 
20581 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
20582 
20583 	/*
20584 	 * Some unformatted drives report not ready error, no need to
20585 	 * restart if format has been initiated.
20586 	 */
20587 	mutex_enter(SD_MUTEX(un));
20588 	if (un->un_f_format_in_progress == TRUE) {
20589 		mutex_exit(SD_MUTEX(un));
20590 		return;
20591 	}
20592 	mutex_exit(SD_MUTEX(un));
20593 
20594 	ssc = sd_ssc_init(un);
20595 	/*
20596 	 * When a START STOP command is issued from here, it is part of a
20597 	 * failure recovery operation and must be issued before any other
20598 	 * commands, including any pending retries. Thus it must be sent
20599 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
20600 	 * succeeds or not, we will start I/O after the attempt.
20601 	 * If power condition is supported and the current power level
20602 	 * is capable of performing I/O, we should set the power condition
20603 	 * to that level. Otherwise, set the power condition to ACTIVE.
20604 	 */
20605 	if (un->un_f_power_condition_supported) {
20606 		mutex_enter(SD_MUTEX(un));
20607 		ASSERT(SD_PM_IS_LEVEL_VALID(un, un->un_power_level));
20608 		power_level = sd_pwr_pc.ran_perf[un->un_power_level]
20609 		    > 0 ? un->un_power_level : SD_SPINDLE_ACTIVE;
20610 		mutex_exit(SD_MUTEX(un));
20611 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
20612 		    sd_pl2pc[power_level], SD_PATH_DIRECT_PRIORITY);
20613 	} else {
20614 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
20615 		    SD_TARGET_START, SD_PATH_DIRECT_PRIORITY);
20616 	}
20617 
20618 	if (rval != 0)
20619 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20620 	sd_ssc_fini(ssc);
20621 	/*
20622 	 * The above call blocks until the START_STOP_UNIT command completes.
20623 	 * Now that it has completed, we must re-try the original IO that
20624 	 * received the NOT READY condition in the first place. There are
20625 	 * three possible conditions here:
20626 	 *
20627 	 *  (1) The original IO is on un_retry_bp.
20628 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
20629 	 *	is NULL.
20630 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
20631 	 *	points to some other, unrelated bp.
20632 	 *
20633 	 * For each case, we must call sd_start_cmds() with un_retry_bp
20634 	 * as the argument. If un_retry_bp is NULL, this will initiate
20635 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
20636 	 * then this will process the bp on un_retry_bp. That may or may not
20637 	 * be the original IO, but that does not matter: the important thing
20638 	 * is to keep the IO processing going at this point.
20639 	 *
20640 	 * Note: This is a very specific error recovery sequence associated
20641 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
20642 	 * serialize the I/O with completion of the spin-up.
20643 	 */
20644 	mutex_enter(SD_MUTEX(un));
20645 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
20646 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
20647 	    un, un->un_retry_bp);
20648 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
20649 	sd_start_cmds(un, un->un_retry_bp);
20650 	mutex_exit(SD_MUTEX(un));
20651 
20652 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
20653 }
20654 
20655 
20656 /*
20657  *    Function: sd_send_scsi_INQUIRY
20658  *
20659  * Description: Issue the scsi INQUIRY command.
20660  *
20661  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20662  *                      structure for this target.
20663  *		bufaddr
20664  *		buflen
20665  *		evpd
20666  *		page_code
20667  *		page_length
20668  *
20669  * Return Code: 0   - Success
20670  *		errno return code from sd_ssc_send()
20671  *
20672  *     Context: Can sleep. Does not return until command is completed.
20673  */
20674 
20675 static int
20676 sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr, size_t buflen,
20677 	uchar_t evpd, uchar_t page_code, size_t *residp)
20678 {
20679 	union scsi_cdb		cdb;
20680 	struct uscsi_cmd	ucmd_buf;
20681 	int			status;
20682 	struct sd_lun		*un;
20683 
20684 	ASSERT(ssc != NULL);
20685 	un = ssc->ssc_un;
20686 	ASSERT(un != NULL);
20687 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20688 	ASSERT(bufaddr != NULL);
20689 
20690 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
20691 
20692 	bzero(&cdb, sizeof (cdb));
20693 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20694 	bzero(bufaddr, buflen);
20695 
20696 	cdb.scc_cmd = SCMD_INQUIRY;
20697 	cdb.cdb_opaque[1] = evpd;
20698 	cdb.cdb_opaque[2] = page_code;
20699 	FORMG0COUNT(&cdb, buflen);
20700 
20701 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20702 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20703 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20704 	ucmd_buf.uscsi_buflen	= buflen;
20705 	ucmd_buf.uscsi_rqbuf	= NULL;
20706 	ucmd_buf.uscsi_rqlen	= 0;
20707 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
20708 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
20709 
20710 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20711 	    UIO_SYSSPACE, SD_PATH_DIRECT);
20712 
20713 	/*
20714 	 * Only handle status == 0, the upper-level caller
20715 	 * will put different assessment based on the context.
20716 	 */
20717 	if (status == 0)
20718 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20719 
20720 	if ((status == 0) && (residp != NULL)) {
20721 		*residp = ucmd_buf.uscsi_resid;
20722 	}
20723 
20724 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
20725 
20726 	return (status);
20727 }
20728 
20729 
20730 /*
20731  *    Function: sd_send_scsi_TEST_UNIT_READY
20732  *
20733  * Description: Issue the scsi TEST UNIT READY command.
20734  *		This routine can be told to set the flag USCSI_DIAGNOSE to
20735  *		prevent retrying failed commands. Use this when the intent
20736  *		is either to check for device readiness, to clear a Unit
20737  *		Attention, or to clear any outstanding sense data.
20738  *		However under specific conditions the expected behavior
20739  *		is for retries to bring a device ready, so use the flag
20740  *		with caution.
20741  *
20742  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20743  *                      structure for this target.
20744  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
20745  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
20746  *			0: dont check for media present, do retries on cmd.
20747  *
20748  * Return Code: 0   - Success
20749  *		EIO - IO error
20750  *		EACCES - Reservation conflict detected
20751  *		ENXIO  - Not Ready, medium not present
20752  *		errno return code from sd_ssc_send()
20753  *
20754  *     Context: Can sleep. Does not return until command is completed.
20755  */
20756 
20757 static int
20758 sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag)
20759 {
20760 	struct	scsi_extended_sense	sense_buf;
20761 	union scsi_cdb		cdb;
20762 	struct uscsi_cmd	ucmd_buf;
20763 	int			status;
20764 	struct sd_lun		*un;
20765 
20766 	ASSERT(ssc != NULL);
20767 	un = ssc->ssc_un;
20768 	ASSERT(un != NULL);
20769 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20770 
20771 	SD_TRACE(SD_LOG_IO, un,
20772 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
20773 
20774 	/*
20775 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
20776 	 * timeouts when they receive a TUR and the queue is not empty. Check
20777 	 * the configuration flag set during attach (indicating the drive has
20778 	 * this firmware bug) and un_ncmds_in_transport before issuing the
20779 	 * TUR. If there are
20780 	 * pending commands return success, this is a bit arbitrary but is ok
20781 	 * for non-removables (i.e. the eliteI disks) and non-clustering
20782 	 * configurations.
20783 	 */
20784 	if (un->un_f_cfg_tur_check == TRUE) {
20785 		mutex_enter(SD_MUTEX(un));
20786 		if (un->un_ncmds_in_transport != 0) {
20787 			mutex_exit(SD_MUTEX(un));
20788 			return (0);
20789 		}
20790 		mutex_exit(SD_MUTEX(un));
20791 	}
20792 
20793 	bzero(&cdb, sizeof (cdb));
20794 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20795 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20796 
20797 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
20798 
20799 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20800 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20801 	ucmd_buf.uscsi_bufaddr	= NULL;
20802 	ucmd_buf.uscsi_buflen	= 0;
20803 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20804 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20805 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20806 
20807 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
20808 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
20809 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
20810 	}
20811 	ucmd_buf.uscsi_timeout	= 60;
20812 
20813 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20814 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
20815 	    SD_PATH_STANDARD));
20816 
20817 	switch (status) {
20818 	case 0:
20819 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20820 		break;	/* Success! */
20821 	case EIO:
20822 		switch (ucmd_buf.uscsi_status) {
20823 		case STATUS_RESERVATION_CONFLICT:
20824 			status = EACCES;
20825 			break;
20826 		case STATUS_CHECK:
20827 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
20828 				break;
20829 			}
20830 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20831 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20832 			    KEY_NOT_READY) &&
20833 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
20834 				status = ENXIO;
20835 			}
20836 			break;
20837 		default:
20838 			break;
20839 		}
20840 		break;
20841 	default:
20842 		break;
20843 	}
20844 
20845 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
20846 
20847 	return (status);
20848 }
20849 
20850 /*
20851  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
20852  *
20853  * Description: Issue the scsi PERSISTENT RESERVE IN command.
20854  *
20855  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20856  *                      structure for this target.
20857  *
20858  * Return Code: 0   - Success
20859  *		EACCES
20860  *		ENOTSUP
20861  *		errno return code from sd_ssc_send()
20862  *
20863  *     Context: Can sleep. Does not return until command is completed.
20864  */
20865 
20866 static int
20867 sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc, uchar_t  usr_cmd,
20868 	uint16_t data_len, uchar_t *data_bufp)
20869 {
20870 	struct scsi_extended_sense	sense_buf;
20871 	union scsi_cdb		cdb;
20872 	struct uscsi_cmd	ucmd_buf;
20873 	int			status;
20874 	int			no_caller_buf = FALSE;
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((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
20882 
20883 	SD_TRACE(SD_LOG_IO, un,
20884 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
20885 
20886 	bzero(&cdb, sizeof (cdb));
20887 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20888 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20889 	if (data_bufp == NULL) {
20890 		/* Allocate a default buf if the caller did not give one */
20891 		ASSERT(data_len == 0);
20892 		data_len  = MHIOC_RESV_KEY_SIZE;
20893 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
20894 		no_caller_buf = TRUE;
20895 	}
20896 
20897 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
20898 	cdb.cdb_opaque[1] = usr_cmd;
20899 	FORMG1COUNT(&cdb, data_len);
20900 
20901 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20902 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20903 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
20904 	ucmd_buf.uscsi_buflen	= data_len;
20905 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20906 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20907 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20908 	ucmd_buf.uscsi_timeout	= 60;
20909 
20910 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20911 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20912 
20913 	switch (status) {
20914 	case 0:
20915 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20916 
20917 		break;	/* Success! */
20918 	case EIO:
20919 		switch (ucmd_buf.uscsi_status) {
20920 		case STATUS_RESERVATION_CONFLICT:
20921 			status = EACCES;
20922 			break;
20923 		case STATUS_CHECK:
20924 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20925 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20926 			    KEY_ILLEGAL_REQUEST)) {
20927 				status = ENOTSUP;
20928 			}
20929 			break;
20930 		default:
20931 			break;
20932 		}
20933 		break;
20934 	default:
20935 		break;
20936 	}
20937 
20938 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
20939 
20940 	if (no_caller_buf == TRUE) {
20941 		kmem_free(data_bufp, data_len);
20942 	}
20943 
20944 	return (status);
20945 }
20946 
20947 
20948 /*
20949  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
20950  *
20951  * Description: This routine is the driver entry point for handling CD-ROM
20952  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
20953  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
20954  *		device.
20955  *
20956  *   Arguments: ssc  -  ssc contains un - pointer to soft state struct
20957  *                      for the target.
20958  *		usr_cmd SCSI-3 reservation facility command (one of
20959  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
20960  *			SD_SCSI3_PREEMPTANDABORT, SD_SCSI3_CLEAR)
20961  *		usr_bufp - user provided pointer register, reserve descriptor or
20962  *			preempt and abort structure (mhioc_register_t,
20963  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
20964  *
20965  * Return Code: 0   - Success
20966  *		EACCES
20967  *		ENOTSUP
20968  *		errno return code from sd_ssc_send()
20969  *
20970  *     Context: Can sleep. Does not return until command is completed.
20971  */
20972 
20973 static int
20974 sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc, uchar_t usr_cmd,
20975 	uchar_t	*usr_bufp)
20976 {
20977 	struct scsi_extended_sense	sense_buf;
20978 	union scsi_cdb		cdb;
20979 	struct uscsi_cmd	ucmd_buf;
20980 	int			status;
20981 	uchar_t			data_len = sizeof (sd_prout_t);
20982 	sd_prout_t		*prp;
20983 	struct sd_lun		*un;
20984 
20985 	ASSERT(ssc != NULL);
20986 	un = ssc->ssc_un;
20987 	ASSERT(un != NULL);
20988 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20989 	ASSERT(data_len == 24);	/* required by scsi spec */
20990 
20991 	SD_TRACE(SD_LOG_IO, un,
20992 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
20993 
20994 	if (usr_bufp == NULL) {
20995 		return (EINVAL);
20996 	}
20997 
20998 	bzero(&cdb, sizeof (cdb));
20999 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21000 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21001 	prp = kmem_zalloc(data_len, KM_SLEEP);
21002 
21003 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
21004 	cdb.cdb_opaque[1] = usr_cmd;
21005 	FORMG1COUNT(&cdb, data_len);
21006 
21007 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21008 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
21009 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
21010 	ucmd_buf.uscsi_buflen	= data_len;
21011 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21012 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21013 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
21014 	ucmd_buf.uscsi_timeout	= 60;
21015 
21016 	switch (usr_cmd) {
21017 	case SD_SCSI3_REGISTER: {
21018 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
21019 
21020 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21021 		bcopy(ptr->newkey.key, prp->service_key,
21022 		    MHIOC_RESV_KEY_SIZE);
21023 		prp->aptpl = ptr->aptpl;
21024 		break;
21025 	}
21026 	case SD_SCSI3_CLEAR: {
21027 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
21028 
21029 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21030 		break;
21031 	}
21032 	case SD_SCSI3_RESERVE:
21033 	case SD_SCSI3_RELEASE: {
21034 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
21035 
21036 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21037 		prp->scope_address = BE_32(ptr->scope_specific_addr);
21038 		cdb.cdb_opaque[2] = ptr->type;
21039 		break;
21040 	}
21041 	case SD_SCSI3_PREEMPTANDABORT: {
21042 		mhioc_preemptandabort_t *ptr =
21043 		    (mhioc_preemptandabort_t *)usr_bufp;
21044 
21045 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21046 		bcopy(ptr->victim_key.key, prp->service_key,
21047 		    MHIOC_RESV_KEY_SIZE);
21048 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
21049 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
21050 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
21051 		break;
21052 	}
21053 	case SD_SCSI3_REGISTERANDIGNOREKEY:
21054 	{
21055 		mhioc_registerandignorekey_t *ptr;
21056 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
21057 		bcopy(ptr->newkey.key,
21058 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
21059 		prp->aptpl = ptr->aptpl;
21060 		break;
21061 	}
21062 	default:
21063 		ASSERT(FALSE);
21064 		break;
21065 	}
21066 
21067 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21068 	    UIO_SYSSPACE, SD_PATH_STANDARD);
21069 
21070 	switch (status) {
21071 	case 0:
21072 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21073 		break;	/* Success! */
21074 	case EIO:
21075 		switch (ucmd_buf.uscsi_status) {
21076 		case STATUS_RESERVATION_CONFLICT:
21077 			status = EACCES;
21078 			break;
21079 		case STATUS_CHECK:
21080 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21081 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21082 			    KEY_ILLEGAL_REQUEST)) {
21083 				status = ENOTSUP;
21084 			}
21085 			break;
21086 		default:
21087 			break;
21088 		}
21089 		break;
21090 	default:
21091 		break;
21092 	}
21093 
21094 	kmem_free(prp, data_len);
21095 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
21096 	return (status);
21097 }
21098 
21099 
21100 /*
21101  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
21102  *
21103  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
21104  *
21105  *   Arguments: un - pointer to the target's soft state struct
21106  *              dkc - pointer to the callback structure
21107  *
21108  * Return Code: 0 - success
21109  *		errno-type error code
21110  *
21111  *     Context: kernel thread context only.
21112  *
21113  *  _______________________________________________________________
21114  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
21115  * |FLUSH_VOLATILE|              | operation                       |
21116  * |______________|______________|_________________________________|
21117  * | 0            | NULL         | Synchronous flush on both       |
21118  * |              |              | volatile and non-volatile cache |
21119  * |______________|______________|_________________________________|
21120  * | 1            | NULL         | Synchronous flush on volatile   |
21121  * |              |              | cache; disk drivers may suppress|
21122  * |              |              | flush if disk table indicates   |
21123  * |              |              | non-volatile cache              |
21124  * |______________|______________|_________________________________|
21125  * | 0            | !NULL        | Asynchronous flush on both      |
21126  * |              |              | volatile and non-volatile cache;|
21127  * |______________|______________|_________________________________|
21128  * | 1            | !NULL        | Asynchronous flush on volatile  |
21129  * |              |              | cache; disk drivers may suppress|
21130  * |              |              | flush if disk table indicates   |
21131  * |              |              | non-volatile cache              |
21132  * |______________|______________|_________________________________|
21133  *
21134  */
21135 
21136 static int
21137 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
21138 {
21139 	struct sd_uscsi_info	*uip;
21140 	struct uscsi_cmd	*uscmd;
21141 	union scsi_cdb		*cdb;
21142 	struct buf		*bp;
21143 	int			rval = 0;
21144 	int			is_async;
21145 
21146 	SD_TRACE(SD_LOG_IO, un,
21147 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
21148 
21149 	ASSERT(un != NULL);
21150 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21151 
21152 	if (dkc == NULL || dkc->dkc_callback == NULL) {
21153 		is_async = FALSE;
21154 	} else {
21155 		is_async = TRUE;
21156 	}
21157 
21158 	mutex_enter(SD_MUTEX(un));
21159 	/* check whether cache flush should be suppressed */
21160 	if (un->un_f_suppress_cache_flush == TRUE) {
21161 		mutex_exit(SD_MUTEX(un));
21162 		/*
21163 		 * suppress the cache flush if the device is told to do
21164 		 * so by sd.conf or disk table
21165 		 */
21166 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
21167 		    skip the cache flush since suppress_cache_flush is %d!\n",
21168 		    un->un_f_suppress_cache_flush);
21169 
21170 		if (is_async == TRUE) {
21171 			/* invoke callback for asynchronous flush */
21172 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
21173 		}
21174 		return (rval);
21175 	}
21176 	mutex_exit(SD_MUTEX(un));
21177 
21178 	/*
21179 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
21180 	 * set properly
21181 	 */
21182 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
21183 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
21184 
21185 	mutex_enter(SD_MUTEX(un));
21186 	if (dkc != NULL && un->un_f_sync_nv_supported &&
21187 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
21188 		/*
21189 		 * if the device supports SYNC_NV bit, turn on
21190 		 * the SYNC_NV bit to only flush volatile cache
21191 		 */
21192 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
21193 	}
21194 	mutex_exit(SD_MUTEX(un));
21195 
21196 	/*
21197 	 * First get some memory for the uscsi_cmd struct and cdb
21198 	 * and initialize for SYNCHRONIZE_CACHE cmd.
21199 	 */
21200 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
21201 	uscmd->uscsi_cdblen = CDB_GROUP1;
21202 	uscmd->uscsi_cdb = (caddr_t)cdb;
21203 	uscmd->uscsi_bufaddr = NULL;
21204 	uscmd->uscsi_buflen = 0;
21205 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
21206 	uscmd->uscsi_rqlen = SENSE_LENGTH;
21207 	uscmd->uscsi_rqresid = SENSE_LENGTH;
21208 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
21209 	uscmd->uscsi_timeout = sd_io_time;
21210 
21211 	/*
21212 	 * Allocate an sd_uscsi_info struct and fill it with the info
21213 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
21214 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
21215 	 * since we allocate the buf here in this function, we do not
21216 	 * need to preserve the prior contents of b_private.
21217 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
21218 	 */
21219 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
21220 	uip->ui_flags = SD_PATH_DIRECT;
21221 	uip->ui_cmdp  = uscmd;
21222 
21223 	bp = getrbuf(KM_SLEEP);
21224 	bp->b_private = uip;
21225 
21226 	/*
21227 	 * Setup buffer to carry uscsi request.
21228 	 */
21229 	bp->b_flags  = B_BUSY;
21230 	bp->b_bcount = 0;
21231 	bp->b_blkno  = 0;
21232 
21233 	if (is_async == TRUE) {
21234 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
21235 		uip->ui_dkc = *dkc;
21236 	}
21237 
21238 	bp->b_edev = SD_GET_DEV(un);
21239 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
21240 
21241 	/*
21242 	 * Unset un_f_sync_cache_required flag
21243 	 */
21244 	mutex_enter(SD_MUTEX(un));
21245 	un->un_f_sync_cache_required = FALSE;
21246 	mutex_exit(SD_MUTEX(un));
21247 
21248 	(void) sd_uscsi_strategy(bp);
21249 
21250 	/*
21251 	 * If synchronous request, wait for completion
21252 	 * If async just return and let b_iodone callback
21253 	 * cleanup.
21254 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
21255 	 * but it was also incremented in sd_uscsi_strategy(), so
21256 	 * we should be ok.
21257 	 */
21258 	if (is_async == FALSE) {
21259 		(void) biowait(bp);
21260 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
21261 	}
21262 
21263 	return (rval);
21264 }
21265 
21266 
21267 static int
21268 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
21269 {
21270 	struct sd_uscsi_info *uip;
21271 	struct uscsi_cmd *uscmd;
21272 	uint8_t *sense_buf;
21273 	struct sd_lun *un;
21274 	int status;
21275 	union scsi_cdb *cdb;
21276 
21277 	uip = (struct sd_uscsi_info *)(bp->b_private);
21278 	ASSERT(uip != NULL);
21279 
21280 	uscmd = uip->ui_cmdp;
21281 	ASSERT(uscmd != NULL);
21282 
21283 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
21284 	ASSERT(sense_buf != NULL);
21285 
21286 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
21287 	ASSERT(un != NULL);
21288 
21289 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
21290 
21291 	status = geterror(bp);
21292 	switch (status) {
21293 	case 0:
21294 		break;	/* Success! */
21295 	case EIO:
21296 		switch (uscmd->uscsi_status) {
21297 		case STATUS_RESERVATION_CONFLICT:
21298 			/* Ignore reservation conflict */
21299 			status = 0;
21300 			goto done;
21301 
21302 		case STATUS_CHECK:
21303 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
21304 			    (scsi_sense_key(sense_buf) ==
21305 			    KEY_ILLEGAL_REQUEST)) {
21306 				/* Ignore Illegal Request error */
21307 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
21308 					mutex_enter(SD_MUTEX(un));
21309 					un->un_f_sync_nv_supported = FALSE;
21310 					mutex_exit(SD_MUTEX(un));
21311 					status = 0;
21312 					SD_TRACE(SD_LOG_IO, un,
21313 					    "un_f_sync_nv_supported \
21314 					    is set to false.\n");
21315 					goto done;
21316 				}
21317 
21318 				mutex_enter(SD_MUTEX(un));
21319 				un->un_f_sync_cache_supported = FALSE;
21320 				mutex_exit(SD_MUTEX(un));
21321 				SD_TRACE(SD_LOG_IO, un,
21322 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
21323 				    un_f_sync_cache_supported set to false \
21324 				    with asc = %x, ascq = %x\n",
21325 				    scsi_sense_asc(sense_buf),
21326 				    scsi_sense_ascq(sense_buf));
21327 				status = ENOTSUP;
21328 				goto done;
21329 			}
21330 			break;
21331 		default:
21332 			break;
21333 		}
21334 		/* FALLTHRU */
21335 	default:
21336 		/*
21337 		 * Turn on the un_f_sync_cache_required flag
21338 		 * since the SYNC CACHE command failed
21339 		 */
21340 		mutex_enter(SD_MUTEX(un));
21341 		un->un_f_sync_cache_required = TRUE;
21342 		mutex_exit(SD_MUTEX(un));
21343 
21344 		/*
21345 		 * Don't log an error message if this device
21346 		 * has removable media.
21347 		 */
21348 		if (!un->un_f_has_removable_media) {
21349 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
21350 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
21351 		}
21352 		break;
21353 	}
21354 
21355 done:
21356 	if (uip->ui_dkc.dkc_callback != NULL) {
21357 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
21358 	}
21359 
21360 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
21361 	freerbuf(bp);
21362 	kmem_free(uip, sizeof (struct sd_uscsi_info));
21363 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
21364 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
21365 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
21366 
21367 	return (status);
21368 }
21369 
21370 
21371 /*
21372  *    Function: sd_send_scsi_GET_CONFIGURATION
21373  *
21374  * Description: Issues the get configuration command to the device.
21375  *		Called from sd_check_for_writable_cd & sd_get_media_info
21376  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
21377  *   Arguments: ssc
21378  *		ucmdbuf
21379  *		rqbuf
21380  *		rqbuflen
21381  *		bufaddr
21382  *		buflen
21383  *		path_flag
21384  *
21385  * Return Code: 0   - Success
21386  *		errno return code from sd_ssc_send()
21387  *
21388  *     Context: Can sleep. Does not return until command is completed.
21389  *
21390  */
21391 
21392 static int
21393 sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21394 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21395 	int path_flag)
21396 {
21397 	char	cdb[CDB_GROUP1];
21398 	int	status;
21399 	struct sd_lun	*un;
21400 
21401 	ASSERT(ssc != NULL);
21402 	un = ssc->ssc_un;
21403 	ASSERT(un != NULL);
21404 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21405 	ASSERT(bufaddr != NULL);
21406 	ASSERT(ucmdbuf != NULL);
21407 	ASSERT(rqbuf != NULL);
21408 
21409 	SD_TRACE(SD_LOG_IO, un,
21410 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
21411 
21412 	bzero(cdb, sizeof (cdb));
21413 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21414 	bzero(rqbuf, rqbuflen);
21415 	bzero(bufaddr, buflen);
21416 
21417 	/*
21418 	 * Set up cdb field for the get configuration command.
21419 	 */
21420 	cdb[0] = SCMD_GET_CONFIGURATION;
21421 	cdb[1] = 0x02;  /* Requested Type */
21422 	cdb[8] = SD_PROFILE_HEADER_LEN;
21423 	ucmdbuf->uscsi_cdb = cdb;
21424 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21425 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21426 	ucmdbuf->uscsi_buflen = buflen;
21427 	ucmdbuf->uscsi_timeout = sd_io_time;
21428 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21429 	ucmdbuf->uscsi_rqlen = rqbuflen;
21430 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
21431 
21432 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21433 	    UIO_SYSSPACE, path_flag);
21434 
21435 	switch (status) {
21436 	case 0:
21437 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21438 		break;  /* Success! */
21439 	case EIO:
21440 		switch (ucmdbuf->uscsi_status) {
21441 		case STATUS_RESERVATION_CONFLICT:
21442 			status = EACCES;
21443 			break;
21444 		default:
21445 			break;
21446 		}
21447 		break;
21448 	default:
21449 		break;
21450 	}
21451 
21452 	if (status == 0) {
21453 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21454 		    "sd_send_scsi_GET_CONFIGURATION: data",
21455 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21456 	}
21457 
21458 	SD_TRACE(SD_LOG_IO, un,
21459 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
21460 
21461 	return (status);
21462 }
21463 
21464 /*
21465  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
21466  *
21467  * Description: Issues the get configuration command to the device to
21468  *              retrieve a specific feature. Called from
21469  *		sd_check_for_writable_cd & sd_set_mmc_caps.
21470  *   Arguments: ssc
21471  *              ucmdbuf
21472  *              rqbuf
21473  *              rqbuflen
21474  *              bufaddr
21475  *              buflen
21476  *		feature
21477  *
21478  * Return Code: 0   - Success
21479  *              errno return code from sd_ssc_send()
21480  *
21481  *     Context: Can sleep. Does not return until command is completed.
21482  *
21483  */
21484 static int
21485 sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
21486 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
21487 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
21488 {
21489 	char    cdb[CDB_GROUP1];
21490 	int	status;
21491 	struct sd_lun	*un;
21492 
21493 	ASSERT(ssc != NULL);
21494 	un = ssc->ssc_un;
21495 	ASSERT(un != NULL);
21496 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21497 	ASSERT(bufaddr != NULL);
21498 	ASSERT(ucmdbuf != NULL);
21499 	ASSERT(rqbuf != NULL);
21500 
21501 	SD_TRACE(SD_LOG_IO, un,
21502 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
21503 
21504 	bzero(cdb, sizeof (cdb));
21505 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21506 	bzero(rqbuf, rqbuflen);
21507 	bzero(bufaddr, buflen);
21508 
21509 	/*
21510 	 * Set up cdb field for the get configuration command.
21511 	 */
21512 	cdb[0] = SCMD_GET_CONFIGURATION;
21513 	cdb[1] = 0x02;  /* Requested Type */
21514 	cdb[3] = feature;
21515 	cdb[8] = buflen;
21516 	ucmdbuf->uscsi_cdb = cdb;
21517 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21518 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21519 	ucmdbuf->uscsi_buflen = buflen;
21520 	ucmdbuf->uscsi_timeout = sd_io_time;
21521 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21522 	ucmdbuf->uscsi_rqlen = rqbuflen;
21523 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
21524 
21525 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21526 	    UIO_SYSSPACE, path_flag);
21527 
21528 	switch (status) {
21529 	case 0:
21530 
21531 		break;  /* Success! */
21532 	case EIO:
21533 		switch (ucmdbuf->uscsi_status) {
21534 		case STATUS_RESERVATION_CONFLICT:
21535 			status = EACCES;
21536 			break;
21537 		default:
21538 			break;
21539 		}
21540 		break;
21541 	default:
21542 		break;
21543 	}
21544 
21545 	if (status == 0) {
21546 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21547 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
21548 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21549 	}
21550 
21551 	SD_TRACE(SD_LOG_IO, un,
21552 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
21553 
21554 	return (status);
21555 }
21556 
21557 
21558 /*
21559  *    Function: sd_send_scsi_MODE_SENSE
21560  *
21561  * Description: Utility function for issuing a scsi MODE SENSE command.
21562  *		Note: This routine uses a consistent implementation for Group0,
21563  *		Group1, and Group2 commands across all platforms. ATAPI devices
21564  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21565  *
21566  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21567  *                      structure for this target.
21568  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21569  *			  CDB_GROUP[1|2] (10 byte).
21570  *		bufaddr - buffer for page data retrieved from the target.
21571  *		buflen - size of page to be retrieved.
21572  *		page_code - page code of data to be retrieved from the target.
21573  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21574  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21575  *			to use the USCSI "direct" chain and bypass the normal
21576  *			command waitq.
21577  *
21578  * Return Code: 0   - Success
21579  *		errno return code from sd_ssc_send()
21580  *
21581  *     Context: Can sleep. Does not return until command is completed.
21582  */
21583 
21584 static int
21585 sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21586 	size_t buflen,  uchar_t page_code, int path_flag)
21587 {
21588 	struct	scsi_extended_sense	sense_buf;
21589 	union scsi_cdb		cdb;
21590 	struct uscsi_cmd	ucmd_buf;
21591 	int			status;
21592 	int			headlen;
21593 	struct sd_lun		*un;
21594 
21595 	ASSERT(ssc != NULL);
21596 	un = ssc->ssc_un;
21597 	ASSERT(un != NULL);
21598 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21599 	ASSERT(bufaddr != NULL);
21600 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21601 	    (cdbsize == CDB_GROUP2));
21602 
21603 	SD_TRACE(SD_LOG_IO, un,
21604 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
21605 
21606 	bzero(&cdb, sizeof (cdb));
21607 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21608 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21609 	bzero(bufaddr, buflen);
21610 
21611 	if (cdbsize == CDB_GROUP0) {
21612 		cdb.scc_cmd = SCMD_MODE_SENSE;
21613 		cdb.cdb_opaque[2] = page_code;
21614 		FORMG0COUNT(&cdb, buflen);
21615 		headlen = MODE_HEADER_LENGTH;
21616 	} else {
21617 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
21618 		cdb.cdb_opaque[2] = page_code;
21619 		FORMG1COUNT(&cdb, buflen);
21620 		headlen = MODE_HEADER_LENGTH_GRP2;
21621 	}
21622 
21623 	ASSERT(headlen <= buflen);
21624 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21625 
21626 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21627 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21628 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21629 	ucmd_buf.uscsi_buflen	= buflen;
21630 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21631 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21632 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21633 	ucmd_buf.uscsi_timeout	= 60;
21634 
21635 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21636 	    UIO_SYSSPACE, path_flag);
21637 
21638 	switch (status) {
21639 	case 0:
21640 		/*
21641 		 * sr_check_wp() uses 0x3f page code and check the header of
21642 		 * mode page to determine if target device is write-protected.
21643 		 * But some USB devices return 0 bytes for 0x3f page code. For
21644 		 * this case, make sure that mode page header is returned at
21645 		 * least.
21646 		 */
21647 		if (buflen - ucmd_buf.uscsi_resid <  headlen) {
21648 			status = EIO;
21649 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
21650 			    "mode page header is not returned");
21651 		}
21652 		break;	/* Success! */
21653 	case EIO:
21654 		switch (ucmd_buf.uscsi_status) {
21655 		case STATUS_RESERVATION_CONFLICT:
21656 			status = EACCES;
21657 			break;
21658 		default:
21659 			break;
21660 		}
21661 		break;
21662 	default:
21663 		break;
21664 	}
21665 
21666 	if (status == 0) {
21667 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
21668 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21669 	}
21670 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
21671 
21672 	return (status);
21673 }
21674 
21675 
21676 /*
21677  *    Function: sd_send_scsi_MODE_SELECT
21678  *
21679  * Description: Utility function for issuing a scsi MODE SELECT command.
21680  *		Note: This routine uses a consistent implementation for Group0,
21681  *		Group1, and Group2 commands across all platforms. ATAPI devices
21682  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21683  *
21684  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21685  *                      structure for this target.
21686  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21687  *			  CDB_GROUP[1|2] (10 byte).
21688  *		bufaddr - buffer for page data retrieved from the target.
21689  *		buflen - size of page to be retrieved.
21690  *		save_page - boolean to determin if SP bit should be set.
21691  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21692  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21693  *			to use the USCSI "direct" chain and bypass the normal
21694  *			command waitq.
21695  *
21696  * Return Code: 0   - Success
21697  *		errno return code from sd_ssc_send()
21698  *
21699  *     Context: Can sleep. Does not return until command is completed.
21700  */
21701 
21702 static int
21703 sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21704 	size_t buflen,  uchar_t save_page, int path_flag)
21705 {
21706 	struct	scsi_extended_sense	sense_buf;
21707 	union scsi_cdb		cdb;
21708 	struct uscsi_cmd	ucmd_buf;
21709 	int			status;
21710 	struct sd_lun		*un;
21711 
21712 	ASSERT(ssc != NULL);
21713 	un = ssc->ssc_un;
21714 	ASSERT(un != NULL);
21715 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21716 	ASSERT(bufaddr != NULL);
21717 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21718 	    (cdbsize == CDB_GROUP2));
21719 
21720 	SD_TRACE(SD_LOG_IO, un,
21721 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
21722 
21723 	bzero(&cdb, sizeof (cdb));
21724 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21725 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21726 
21727 	/* Set the PF bit for many third party drives */
21728 	cdb.cdb_opaque[1] = 0x10;
21729 
21730 	/* Set the savepage(SP) bit if given */
21731 	if (save_page == SD_SAVE_PAGE) {
21732 		cdb.cdb_opaque[1] |= 0x01;
21733 	}
21734 
21735 	if (cdbsize == CDB_GROUP0) {
21736 		cdb.scc_cmd = SCMD_MODE_SELECT;
21737 		FORMG0COUNT(&cdb, buflen);
21738 	} else {
21739 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
21740 		FORMG1COUNT(&cdb, buflen);
21741 	}
21742 
21743 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21744 
21745 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21746 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21747 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21748 	ucmd_buf.uscsi_buflen	= buflen;
21749 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21750 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21751 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
21752 	ucmd_buf.uscsi_timeout	= 60;
21753 
21754 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21755 	    UIO_SYSSPACE, path_flag);
21756 
21757 	switch (status) {
21758 	case 0:
21759 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21760 		break;	/* Success! */
21761 	case EIO:
21762 		switch (ucmd_buf.uscsi_status) {
21763 		case STATUS_RESERVATION_CONFLICT:
21764 			status = EACCES;
21765 			break;
21766 		default:
21767 			break;
21768 		}
21769 		break;
21770 	default:
21771 		break;
21772 	}
21773 
21774 	if (status == 0) {
21775 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
21776 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21777 	}
21778 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
21779 
21780 	return (status);
21781 }
21782 
21783 
21784 /*
21785  *    Function: sd_send_scsi_RDWR
21786  *
21787  * Description: Issue a scsi READ or WRITE command with the given parameters.
21788  *
21789  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21790  *                      structure for this target.
21791  *		cmd:	 SCMD_READ or SCMD_WRITE
21792  *		bufaddr: Address of caller's buffer to receive the RDWR data
21793  *		buflen:  Length of caller's buffer receive the RDWR data.
21794  *		start_block: Block number for the start of the RDWR operation.
21795  *			 (Assumes target-native block size.)
21796  *		residp:  Pointer to variable to receive the redisual of the
21797  *			 RDWR operation (may be NULL of no residual requested).
21798  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21799  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21800  *			to use the USCSI "direct" chain and bypass the normal
21801  *			command waitq.
21802  *
21803  * Return Code: 0   - Success
21804  *		errno return code from sd_ssc_send()
21805  *
21806  *     Context: Can sleep. Does not return until command is completed.
21807  */
21808 
21809 static int
21810 sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
21811 	size_t buflen, daddr_t start_block, int path_flag)
21812 {
21813 	struct	scsi_extended_sense	sense_buf;
21814 	union scsi_cdb		cdb;
21815 	struct uscsi_cmd	ucmd_buf;
21816 	uint32_t		block_count;
21817 	int			status;
21818 	int			cdbsize;
21819 	uchar_t			flag;
21820 	struct sd_lun		*un;
21821 
21822 	ASSERT(ssc != NULL);
21823 	un = ssc->ssc_un;
21824 	ASSERT(un != NULL);
21825 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21826 	ASSERT(bufaddr != NULL);
21827 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
21828 
21829 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
21830 
21831 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
21832 		return (EINVAL);
21833 	}
21834 
21835 	mutex_enter(SD_MUTEX(un));
21836 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
21837 	mutex_exit(SD_MUTEX(un));
21838 
21839 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
21840 
21841 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
21842 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
21843 	    bufaddr, buflen, start_block, block_count);
21844 
21845 	bzero(&cdb, sizeof (cdb));
21846 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21847 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21848 
21849 	/* Compute CDB size to use */
21850 	if (start_block > 0xffffffff)
21851 		cdbsize = CDB_GROUP4;
21852 	else if ((start_block & 0xFFE00000) ||
21853 	    (un->un_f_cfg_is_atapi == TRUE))
21854 		cdbsize = CDB_GROUP1;
21855 	else
21856 		cdbsize = CDB_GROUP0;
21857 
21858 	switch (cdbsize) {
21859 	case CDB_GROUP0:	/* 6-byte CDBs */
21860 		cdb.scc_cmd = cmd;
21861 		FORMG0ADDR(&cdb, start_block);
21862 		FORMG0COUNT(&cdb, block_count);
21863 		break;
21864 	case CDB_GROUP1:	/* 10-byte CDBs */
21865 		cdb.scc_cmd = cmd | SCMD_GROUP1;
21866 		FORMG1ADDR(&cdb, start_block);
21867 		FORMG1COUNT(&cdb, block_count);
21868 		break;
21869 	case CDB_GROUP4:	/* 16-byte CDBs */
21870 		cdb.scc_cmd = cmd | SCMD_GROUP4;
21871 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
21872 		FORMG4COUNT(&cdb, block_count);
21873 		break;
21874 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
21875 	default:
21876 		/* All others reserved */
21877 		return (EINVAL);
21878 	}
21879 
21880 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
21881 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21882 
21883 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21884 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21885 	ucmd_buf.uscsi_bufaddr	= bufaddr;
21886 	ucmd_buf.uscsi_buflen	= buflen;
21887 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21888 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21889 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
21890 	ucmd_buf.uscsi_timeout	= 60;
21891 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21892 	    UIO_SYSSPACE, path_flag);
21893 
21894 	switch (status) {
21895 	case 0:
21896 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21897 		break;	/* Success! */
21898 	case EIO:
21899 		switch (ucmd_buf.uscsi_status) {
21900 		case STATUS_RESERVATION_CONFLICT:
21901 			status = EACCES;
21902 			break;
21903 		default:
21904 			break;
21905 		}
21906 		break;
21907 	default:
21908 		break;
21909 	}
21910 
21911 	if (status == 0) {
21912 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
21913 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21914 	}
21915 
21916 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
21917 
21918 	return (status);
21919 }
21920 
21921 
21922 /*
21923  *    Function: sd_send_scsi_LOG_SENSE
21924  *
21925  * Description: Issue a scsi LOG_SENSE command with the given parameters.
21926  *
21927  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21928  *                      structure for this target.
21929  *
21930  * Return Code: 0   - Success
21931  *		errno return code from sd_ssc_send()
21932  *
21933  *     Context: Can sleep. Does not return until command is completed.
21934  */
21935 
21936 static int
21937 sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr, uint16_t buflen,
21938 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
21939 	int path_flag)
21940 
21941 {
21942 	struct scsi_extended_sense	sense_buf;
21943 	union scsi_cdb		cdb;
21944 	struct uscsi_cmd	ucmd_buf;
21945 	int			status;
21946 	struct sd_lun		*un;
21947 
21948 	ASSERT(ssc != NULL);
21949 	un = ssc->ssc_un;
21950 	ASSERT(un != NULL);
21951 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21952 
21953 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
21954 
21955 	bzero(&cdb, sizeof (cdb));
21956 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21957 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21958 
21959 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
21960 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
21961 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
21962 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
21963 	FORMG1COUNT(&cdb, buflen);
21964 
21965 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21966 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
21967 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21968 	ucmd_buf.uscsi_buflen	= buflen;
21969 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21970 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21971 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21972 	ucmd_buf.uscsi_timeout	= 60;
21973 
21974 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21975 	    UIO_SYSSPACE, path_flag);
21976 
21977 	switch (status) {
21978 	case 0:
21979 		break;
21980 	case EIO:
21981 		switch (ucmd_buf.uscsi_status) {
21982 		case STATUS_RESERVATION_CONFLICT:
21983 			status = EACCES;
21984 			break;
21985 		case STATUS_CHECK:
21986 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21987 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21988 				KEY_ILLEGAL_REQUEST) &&
21989 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
21990 				/*
21991 				 * ASC 0x24: INVALID FIELD IN CDB
21992 				 */
21993 				switch (page_code) {
21994 				case START_STOP_CYCLE_PAGE:
21995 					/*
21996 					 * The start stop cycle counter is
21997 					 * implemented as page 0x31 in earlier
21998 					 * generation disks. In new generation
21999 					 * disks the start stop cycle counter is
22000 					 * implemented as page 0xE. To properly
22001 					 * handle this case if an attempt for
22002 					 * log page 0xE is made and fails we
22003 					 * will try again using page 0x31.
22004 					 *
22005 					 * Network storage BU committed to
22006 					 * maintain the page 0x31 for this
22007 					 * purpose and will not have any other
22008 					 * page implemented with page code 0x31
22009 					 * until all disks transition to the
22010 					 * standard page.
22011 					 */
22012 					mutex_enter(SD_MUTEX(un));
22013 					un->un_start_stop_cycle_page =
22014 					    START_STOP_CYCLE_VU_PAGE;
22015 					cdb.cdb_opaque[2] =
22016 					    (char)(page_control << 6) |
22017 					    un->un_start_stop_cycle_page;
22018 					mutex_exit(SD_MUTEX(un));
22019 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22020 					status = sd_ssc_send(
22021 					    ssc, &ucmd_buf, FKIOCTL,
22022 					    UIO_SYSSPACE, path_flag);
22023 
22024 					break;
22025 				case TEMPERATURE_PAGE:
22026 					status = ENOTTY;
22027 					break;
22028 				default:
22029 					break;
22030 				}
22031 			}
22032 			break;
22033 		default:
22034 			break;
22035 		}
22036 		break;
22037 	default:
22038 		break;
22039 	}
22040 
22041 	if (status == 0) {
22042 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22043 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
22044 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22045 	}
22046 
22047 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
22048 
22049 	return (status);
22050 }
22051 
22052 
22053 /*
22054  *    Function: sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
22055  *
22056  * Description: Issue the scsi GET EVENT STATUS NOTIFICATION command.
22057  *
22058  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22059  *                      structure for this target.
22060  *		bufaddr
22061  *		buflen
22062  *		class_req
22063  *
22064  * Return Code: 0   - Success
22065  *		errno return code from sd_ssc_send()
22066  *
22067  *     Context: Can sleep. Does not return until command is completed.
22068  */
22069 
22070 static int
22071 sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc, uchar_t *bufaddr,
22072 	size_t buflen, uchar_t class_req)
22073 {
22074 	union scsi_cdb		cdb;
22075 	struct uscsi_cmd	ucmd_buf;
22076 	int			status;
22077 	struct sd_lun		*un;
22078 
22079 	ASSERT(ssc != NULL);
22080 	un = ssc->ssc_un;
22081 	ASSERT(un != NULL);
22082 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22083 	ASSERT(bufaddr != NULL);
22084 
22085 	SD_TRACE(SD_LOG_IO, un,
22086 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: entry: un:0x%p\n", un);
22087 
22088 	bzero(&cdb, sizeof (cdb));
22089 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22090 	bzero(bufaddr, buflen);
22091 
22092 	cdb.scc_cmd = SCMD_GET_EVENT_STATUS_NOTIFICATION;
22093 	cdb.cdb_opaque[1] = 1; /* polled */
22094 	cdb.cdb_opaque[4] = class_req;
22095 	FORMG1COUNT(&cdb, buflen);
22096 
22097 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22098 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22099 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22100 	ucmd_buf.uscsi_buflen	= buflen;
22101 	ucmd_buf.uscsi_rqbuf	= NULL;
22102 	ucmd_buf.uscsi_rqlen	= 0;
22103 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
22104 	ucmd_buf.uscsi_timeout	= 60;
22105 
22106 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22107 	    UIO_SYSSPACE, SD_PATH_DIRECT);
22108 
22109 	/*
22110 	 * Only handle status == 0, the upper-level caller
22111 	 * will put different assessment based on the context.
22112 	 */
22113 	if (status == 0) {
22114 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22115 
22116 		if (ucmd_buf.uscsi_resid != 0) {
22117 			status = EIO;
22118 		}
22119 	}
22120 
22121 	SD_TRACE(SD_LOG_IO, un,
22122 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: exit\n");
22123 
22124 	return (status);
22125 }
22126 
22127 
22128 static boolean_t
22129 sd_gesn_media_data_valid(uchar_t *data)
22130 {
22131 	uint16_t			len;
22132 
22133 	len = (data[1] << 8) | data[0];
22134 	return ((len >= 6) &&
22135 	    ((data[2] & SD_GESN_HEADER_NEA) == 0) &&
22136 	    ((data[2] & SD_GESN_HEADER_CLASS) == SD_GESN_MEDIA_CLASS) &&
22137 	    ((data[3] & (1 << SD_GESN_MEDIA_CLASS)) != 0));
22138 }
22139 
22140 
22141 /*
22142  *    Function: sdioctl
22143  *
22144  * Description: Driver's ioctl(9e) entry point function.
22145  *
22146  *   Arguments: dev     - device number
22147  *		cmd     - ioctl operation to be performed
22148  *		arg     - user argument, contains data to be set or reference
22149  *			  parameter for get
22150  *		flag    - bit flag, indicating open settings, 32/64 bit type
22151  *		cred_p  - user credential pointer
22152  *		rval_p  - calling process return value (OPT)
22153  *
22154  * Return Code: EINVAL
22155  *		ENOTTY
22156  *		ENXIO
22157  *		EIO
22158  *		EFAULT
22159  *		ENOTSUP
22160  *		EPERM
22161  *
22162  *     Context: Called from the device switch at normal priority.
22163  */
22164 
22165 static int
22166 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
22167 {
22168 	struct sd_lun	*un = NULL;
22169 	int		err = 0;
22170 	int		i = 0;
22171 	cred_t		*cr;
22172 	int		tmprval = EINVAL;
22173 	boolean_t	is_valid;
22174 	sd_ssc_t	*ssc;
22175 
22176 	/*
22177 	 * All device accesses go thru sdstrategy where we check on suspend
22178 	 * status
22179 	 */
22180 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22181 		return (ENXIO);
22182 	}
22183 
22184 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22185 
22186 	/* Initialize sd_ssc_t for internal uscsi commands */
22187 	ssc = sd_ssc_init(un);
22188 
22189 	is_valid = SD_IS_VALID_LABEL(un);
22190 
22191 	/*
22192 	 * Moved this wait from sd_uscsi_strategy to here for
22193 	 * reasons of deadlock prevention. Internal driver commands,
22194 	 * specifically those to change a devices power level, result
22195 	 * in a call to sd_uscsi_strategy.
22196 	 */
22197 	mutex_enter(SD_MUTEX(un));
22198 	while ((un->un_state == SD_STATE_SUSPENDED) ||
22199 	    (un->un_state == SD_STATE_PM_CHANGING)) {
22200 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
22201 	}
22202 	/*
22203 	 * Twiddling the counter here protects commands from now
22204 	 * through to the top of sd_uscsi_strategy. Without the
22205 	 * counter inc. a power down, for example, could get in
22206 	 * after the above check for state is made and before
22207 	 * execution gets to the top of sd_uscsi_strategy.
22208 	 * That would cause problems.
22209 	 */
22210 	un->un_ncmds_in_driver++;
22211 
22212 	if (!is_valid &&
22213 	    (flag & (FNDELAY | FNONBLOCK))) {
22214 		switch (cmd) {
22215 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
22216 		case DKIOCGVTOC:
22217 		case DKIOCGEXTVTOC:
22218 		case DKIOCGAPART:
22219 		case DKIOCPARTINFO:
22220 		case DKIOCEXTPARTINFO:
22221 		case DKIOCSGEOM:
22222 		case DKIOCSAPART:
22223 		case DKIOCGETEFI:
22224 		case DKIOCPARTITION:
22225 		case DKIOCSVTOC:
22226 		case DKIOCSEXTVTOC:
22227 		case DKIOCSETEFI:
22228 		case DKIOCGMBOOT:
22229 		case DKIOCSMBOOT:
22230 		case DKIOCG_PHYGEOM:
22231 		case DKIOCG_VIRTGEOM:
22232 #if defined(__i386) || defined(__amd64)
22233 		case DKIOCSETEXTPART:
22234 #endif
22235 			/* let cmlb handle it */
22236 			goto skip_ready_valid;
22237 
22238 		case CDROMPAUSE:
22239 		case CDROMRESUME:
22240 		case CDROMPLAYMSF:
22241 		case CDROMPLAYTRKIND:
22242 		case CDROMREADTOCHDR:
22243 		case CDROMREADTOCENTRY:
22244 		case CDROMSTOP:
22245 		case CDROMSTART:
22246 		case CDROMVOLCTRL:
22247 		case CDROMSUBCHNL:
22248 		case CDROMREADMODE2:
22249 		case CDROMREADMODE1:
22250 		case CDROMREADOFFSET:
22251 		case CDROMSBLKMODE:
22252 		case CDROMGBLKMODE:
22253 		case CDROMGDRVSPEED:
22254 		case CDROMSDRVSPEED:
22255 		case CDROMCDDA:
22256 		case CDROMCDXA:
22257 		case CDROMSUBCODE:
22258 			if (!ISCD(un)) {
22259 				un->un_ncmds_in_driver--;
22260 				ASSERT(un->un_ncmds_in_driver >= 0);
22261 				mutex_exit(SD_MUTEX(un));
22262 				err = ENOTTY;
22263 				goto done_without_assess;
22264 			}
22265 			break;
22266 		case FDEJECT:
22267 		case DKIOCEJECT:
22268 		case CDROMEJECT:
22269 			if (!un->un_f_eject_media_supported) {
22270 				un->un_ncmds_in_driver--;
22271 				ASSERT(un->un_ncmds_in_driver >= 0);
22272 				mutex_exit(SD_MUTEX(un));
22273 				err = ENOTTY;
22274 				goto done_without_assess;
22275 			}
22276 			break;
22277 		case DKIOCFLUSHWRITECACHE:
22278 			mutex_exit(SD_MUTEX(un));
22279 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22280 			if (err != 0) {
22281 				mutex_enter(SD_MUTEX(un));
22282 				un->un_ncmds_in_driver--;
22283 				ASSERT(un->un_ncmds_in_driver >= 0);
22284 				mutex_exit(SD_MUTEX(un));
22285 				err = EIO;
22286 				goto done_quick_assess;
22287 			}
22288 			mutex_enter(SD_MUTEX(un));
22289 			/* FALLTHROUGH */
22290 		case DKIOCREMOVABLE:
22291 		case DKIOCHOTPLUGGABLE:
22292 		case DKIOCINFO:
22293 		case DKIOCGMEDIAINFO:
22294 		case DKIOCGMEDIAINFOEXT:
22295 		case MHIOCENFAILFAST:
22296 		case MHIOCSTATUS:
22297 		case MHIOCTKOWN:
22298 		case MHIOCRELEASE:
22299 		case MHIOCGRP_INKEYS:
22300 		case MHIOCGRP_INRESV:
22301 		case MHIOCGRP_REGISTER:
22302 		case MHIOCGRP_CLEAR:
22303 		case MHIOCGRP_RESERVE:
22304 		case MHIOCGRP_PREEMPTANDABORT:
22305 		case MHIOCGRP_REGISTERANDIGNOREKEY:
22306 		case CDROMCLOSETRAY:
22307 		case USCSICMD:
22308 			goto skip_ready_valid;
22309 		default:
22310 			break;
22311 		}
22312 
22313 		mutex_exit(SD_MUTEX(un));
22314 		err = sd_ready_and_valid(ssc, SDPART(dev));
22315 		mutex_enter(SD_MUTEX(un));
22316 
22317 		if (err != SD_READY_VALID) {
22318 			switch (cmd) {
22319 			case DKIOCSTATE:
22320 			case CDROMGDRVSPEED:
22321 			case CDROMSDRVSPEED:
22322 			case FDEJECT:	/* for eject command */
22323 			case DKIOCEJECT:
22324 			case CDROMEJECT:
22325 			case DKIOCREMOVABLE:
22326 			case DKIOCHOTPLUGGABLE:
22327 				break;
22328 			default:
22329 				if (un->un_f_has_removable_media) {
22330 					err = ENXIO;
22331 				} else {
22332 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
22333 					if (err == SD_RESERVED_BY_OTHERS) {
22334 						err = EACCES;
22335 					} else {
22336 						err = EIO;
22337 					}
22338 				}
22339 				un->un_ncmds_in_driver--;
22340 				ASSERT(un->un_ncmds_in_driver >= 0);
22341 				mutex_exit(SD_MUTEX(un));
22342 
22343 				goto done_without_assess;
22344 			}
22345 		}
22346 	}
22347 
22348 skip_ready_valid:
22349 	mutex_exit(SD_MUTEX(un));
22350 
22351 	switch (cmd) {
22352 	case DKIOCINFO:
22353 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
22354 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
22355 		break;
22356 
22357 	case DKIOCGMEDIAINFO:
22358 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
22359 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
22360 		break;
22361 
22362 	case DKIOCGMEDIAINFOEXT:
22363 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFOEXT\n");
22364 		err = sd_get_media_info_ext(dev, (caddr_t)arg, flag);
22365 		break;
22366 
22367 	case DKIOCGGEOM:
22368 	case DKIOCGVTOC:
22369 	case DKIOCGEXTVTOC:
22370 	case DKIOCGAPART:
22371 	case DKIOCPARTINFO:
22372 	case DKIOCEXTPARTINFO:
22373 	case DKIOCSGEOM:
22374 	case DKIOCSAPART:
22375 	case DKIOCGETEFI:
22376 	case DKIOCPARTITION:
22377 	case DKIOCSVTOC:
22378 	case DKIOCSEXTVTOC:
22379 	case DKIOCSETEFI:
22380 	case DKIOCGMBOOT:
22381 	case DKIOCSMBOOT:
22382 	case DKIOCG_PHYGEOM:
22383 	case DKIOCG_VIRTGEOM:
22384 #if defined(__i386) || defined(__amd64)
22385 	case DKIOCSETEXTPART:
22386 #endif
22387 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
22388 
22389 		/* TUR should spin up */
22390 
22391 		if (un->un_f_has_removable_media)
22392 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
22393 			    SD_CHECK_FOR_MEDIA);
22394 
22395 		else
22396 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22397 
22398 		if (err != 0)
22399 			goto done_with_assess;
22400 
22401 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
22402 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
22403 
22404 		if ((err == 0) &&
22405 		    ((cmd == DKIOCSETEFI) ||
22406 		    (un->un_f_pkstats_enabled) &&
22407 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
22408 		    cmd == DKIOCSEXTVTOC))) {
22409 
22410 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
22411 			    (void *)SD_PATH_DIRECT);
22412 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
22413 				sd_set_pstats(un);
22414 				SD_TRACE(SD_LOG_IO_PARTITION, un,
22415 				    "sd_ioctl: un:0x%p pstats created and "
22416 				    "set\n", un);
22417 			}
22418 		}
22419 
22420 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
22421 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
22422 
22423 			mutex_enter(SD_MUTEX(un));
22424 			if (un->un_f_devid_supported &&
22425 			    (un->un_f_opt_fab_devid == TRUE)) {
22426 				if (un->un_devid == NULL) {
22427 					sd_register_devid(ssc, SD_DEVINFO(un),
22428 					    SD_TARGET_IS_UNRESERVED);
22429 				} else {
22430 					/*
22431 					 * The device id for this disk
22432 					 * has been fabricated. The
22433 					 * device id must be preserved
22434 					 * by writing it back out to
22435 					 * disk.
22436 					 */
22437 					if (sd_write_deviceid(ssc) != 0) {
22438 						ddi_devid_free(un->un_devid);
22439 						un->un_devid = NULL;
22440 					}
22441 				}
22442 			}
22443 			mutex_exit(SD_MUTEX(un));
22444 		}
22445 
22446 		break;
22447 
22448 	case DKIOCLOCK:
22449 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
22450 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22451 		    SD_PATH_STANDARD);
22452 		goto done_with_assess;
22453 
22454 	case DKIOCUNLOCK:
22455 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
22456 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
22457 		    SD_PATH_STANDARD);
22458 		goto done_with_assess;
22459 
22460 	case DKIOCSTATE: {
22461 		enum dkio_state		state;
22462 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
22463 
22464 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
22465 			err = EFAULT;
22466 		} else {
22467 			err = sd_check_media(dev, state);
22468 			if (err == 0) {
22469 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
22470 				    sizeof (int), flag) != 0)
22471 					err = EFAULT;
22472 			}
22473 		}
22474 		break;
22475 	}
22476 
22477 	case DKIOCREMOVABLE:
22478 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
22479 		i = un->un_f_has_removable_media ? 1 : 0;
22480 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22481 			err = EFAULT;
22482 		} else {
22483 			err = 0;
22484 		}
22485 		break;
22486 
22487 	case DKIOCHOTPLUGGABLE:
22488 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
22489 		i = un->un_f_is_hotpluggable ? 1 : 0;
22490 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22491 			err = EFAULT;
22492 		} else {
22493 			err = 0;
22494 		}
22495 		break;
22496 
22497 	case DKIOCREADONLY:
22498 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREADONLY\n");
22499 		i = 0;
22500 		if ((ISCD(un) && !un->un_f_mmc_writable_media) ||
22501 		    (sr_check_wp(dev) != 0)) {
22502 			i = 1;
22503 		}
22504 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22505 			err = EFAULT;
22506 		} else {
22507 			err = 0;
22508 		}
22509 		break;
22510 
22511 	case DKIOCGTEMPERATURE:
22512 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
22513 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
22514 		break;
22515 
22516 	case MHIOCENFAILFAST:
22517 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
22518 		if ((err = drv_priv(cred_p)) == 0) {
22519 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
22520 		}
22521 		break;
22522 
22523 	case MHIOCTKOWN:
22524 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
22525 		if ((err = drv_priv(cred_p)) == 0) {
22526 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
22527 		}
22528 		break;
22529 
22530 	case MHIOCRELEASE:
22531 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
22532 		if ((err = drv_priv(cred_p)) == 0) {
22533 			err = sd_mhdioc_release(dev);
22534 		}
22535 		break;
22536 
22537 	case MHIOCSTATUS:
22538 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
22539 		if ((err = drv_priv(cred_p)) == 0) {
22540 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
22541 			case 0:
22542 				err = 0;
22543 				break;
22544 			case EACCES:
22545 				*rval_p = 1;
22546 				err = 0;
22547 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22548 				break;
22549 			default:
22550 				err = EIO;
22551 				goto done_with_assess;
22552 			}
22553 		}
22554 		break;
22555 
22556 	case MHIOCQRESERVE:
22557 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
22558 		if ((err = drv_priv(cred_p)) == 0) {
22559 			err = sd_reserve_release(dev, SD_RESERVE);
22560 		}
22561 		break;
22562 
22563 	case MHIOCREREGISTERDEVID:
22564 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
22565 		if (drv_priv(cred_p) == EPERM) {
22566 			err = EPERM;
22567 		} else if (!un->un_f_devid_supported) {
22568 			err = ENOTTY;
22569 		} else {
22570 			err = sd_mhdioc_register_devid(dev);
22571 		}
22572 		break;
22573 
22574 	case MHIOCGRP_INKEYS:
22575 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
22576 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
22577 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22578 				err = ENOTSUP;
22579 			} else {
22580 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
22581 				    flag);
22582 			}
22583 		}
22584 		break;
22585 
22586 	case MHIOCGRP_INRESV:
22587 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
22588 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
22589 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22590 				err = ENOTSUP;
22591 			} else {
22592 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
22593 			}
22594 		}
22595 		break;
22596 
22597 	case MHIOCGRP_REGISTER:
22598 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
22599 		if ((err = drv_priv(cred_p)) != EPERM) {
22600 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22601 				err = ENOTSUP;
22602 			} else if (arg != NULL) {
22603 				mhioc_register_t reg;
22604 				if (ddi_copyin((void *)arg, &reg,
22605 				    sizeof (mhioc_register_t), flag) != 0) {
22606 					err = EFAULT;
22607 				} else {
22608 					err =
22609 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22610 					    ssc, SD_SCSI3_REGISTER,
22611 					    (uchar_t *)&reg);
22612 					if (err != 0)
22613 						goto done_with_assess;
22614 				}
22615 			}
22616 		}
22617 		break;
22618 
22619 	case MHIOCGRP_CLEAR:
22620 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_CLEAR\n");
22621 		if ((err = drv_priv(cred_p)) != EPERM) {
22622 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22623 				err = ENOTSUP;
22624 			} else if (arg != NULL) {
22625 				mhioc_register_t reg;
22626 				if (ddi_copyin((void *)arg, &reg,
22627 				    sizeof (mhioc_register_t), flag) != 0) {
22628 					err = EFAULT;
22629 				} else {
22630 					err =
22631 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22632 					    ssc, SD_SCSI3_CLEAR,
22633 					    (uchar_t *)&reg);
22634 					if (err != 0)
22635 						goto done_with_assess;
22636 				}
22637 			}
22638 		}
22639 		break;
22640 
22641 	case MHIOCGRP_RESERVE:
22642 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
22643 		if ((err = drv_priv(cred_p)) != EPERM) {
22644 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22645 				err = ENOTSUP;
22646 			} else if (arg != NULL) {
22647 				mhioc_resv_desc_t resv_desc;
22648 				if (ddi_copyin((void *)arg, &resv_desc,
22649 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
22650 					err = EFAULT;
22651 				} else {
22652 					err =
22653 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22654 					    ssc, SD_SCSI3_RESERVE,
22655 					    (uchar_t *)&resv_desc);
22656 					if (err != 0)
22657 						goto done_with_assess;
22658 				}
22659 			}
22660 		}
22661 		break;
22662 
22663 	case MHIOCGRP_PREEMPTANDABORT:
22664 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
22665 		if ((err = drv_priv(cred_p)) != EPERM) {
22666 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22667 				err = ENOTSUP;
22668 			} else if (arg != NULL) {
22669 				mhioc_preemptandabort_t preempt_abort;
22670 				if (ddi_copyin((void *)arg, &preempt_abort,
22671 				    sizeof (mhioc_preemptandabort_t),
22672 				    flag) != 0) {
22673 					err = EFAULT;
22674 				} else {
22675 					err =
22676 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22677 					    ssc, SD_SCSI3_PREEMPTANDABORT,
22678 					    (uchar_t *)&preempt_abort);
22679 					if (err != 0)
22680 						goto done_with_assess;
22681 				}
22682 			}
22683 		}
22684 		break;
22685 
22686 	case MHIOCGRP_REGISTERANDIGNOREKEY:
22687 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
22688 		if ((err = drv_priv(cred_p)) != EPERM) {
22689 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22690 				err = ENOTSUP;
22691 			} else if (arg != NULL) {
22692 				mhioc_registerandignorekey_t r_and_i;
22693 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
22694 				    sizeof (mhioc_registerandignorekey_t),
22695 				    flag) != 0) {
22696 					err = EFAULT;
22697 				} else {
22698 					err =
22699 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22700 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
22701 					    (uchar_t *)&r_and_i);
22702 					if (err != 0)
22703 						goto done_with_assess;
22704 				}
22705 			}
22706 		}
22707 		break;
22708 
22709 	case USCSICMD:
22710 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
22711 		cr = ddi_get_cred();
22712 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
22713 			err = EPERM;
22714 		} else {
22715 			enum uio_seg	uioseg;
22716 
22717 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
22718 			    UIO_USERSPACE;
22719 			if (un->un_f_format_in_progress == TRUE) {
22720 				err = EAGAIN;
22721 				break;
22722 			}
22723 
22724 			err = sd_ssc_send(ssc,
22725 			    (struct uscsi_cmd *)arg,
22726 			    flag, uioseg, SD_PATH_STANDARD);
22727 			if (err != 0)
22728 				goto done_with_assess;
22729 			else
22730 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22731 		}
22732 		break;
22733 
22734 	case CDROMPAUSE:
22735 	case CDROMRESUME:
22736 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
22737 		if (!ISCD(un)) {
22738 			err = ENOTTY;
22739 		} else {
22740 			err = sr_pause_resume(dev, cmd);
22741 		}
22742 		break;
22743 
22744 	case CDROMPLAYMSF:
22745 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
22746 		if (!ISCD(un)) {
22747 			err = ENOTTY;
22748 		} else {
22749 			err = sr_play_msf(dev, (caddr_t)arg, flag);
22750 		}
22751 		break;
22752 
22753 	case CDROMPLAYTRKIND:
22754 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
22755 #if defined(__i386) || defined(__amd64)
22756 		/*
22757 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
22758 		 */
22759 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22760 #else
22761 		if (!ISCD(un)) {
22762 #endif
22763 			err = ENOTTY;
22764 		} else {
22765 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
22766 		}
22767 		break;
22768 
22769 	case CDROMREADTOCHDR:
22770 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
22771 		if (!ISCD(un)) {
22772 			err = ENOTTY;
22773 		} else {
22774 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
22775 		}
22776 		break;
22777 
22778 	case CDROMREADTOCENTRY:
22779 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
22780 		if (!ISCD(un)) {
22781 			err = ENOTTY;
22782 		} else {
22783 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
22784 		}
22785 		break;
22786 
22787 	case CDROMSTOP:
22788 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
22789 		if (!ISCD(un)) {
22790 			err = ENOTTY;
22791 		} else {
22792 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22793 			    SD_TARGET_STOP, SD_PATH_STANDARD);
22794 			goto done_with_assess;
22795 		}
22796 		break;
22797 
22798 	case CDROMSTART:
22799 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
22800 		if (!ISCD(un)) {
22801 			err = ENOTTY;
22802 		} else {
22803 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22804 			    SD_TARGET_START, SD_PATH_STANDARD);
22805 			goto done_with_assess;
22806 		}
22807 		break;
22808 
22809 	case CDROMCLOSETRAY:
22810 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
22811 		if (!ISCD(un)) {
22812 			err = ENOTTY;
22813 		} else {
22814 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22815 			    SD_TARGET_CLOSE, SD_PATH_STANDARD);
22816 			goto done_with_assess;
22817 		}
22818 		break;
22819 
22820 	case FDEJECT:	/* for eject command */
22821 	case DKIOCEJECT:
22822 	case CDROMEJECT:
22823 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
22824 		if (!un->un_f_eject_media_supported) {
22825 			err = ENOTTY;
22826 		} else {
22827 			err = sr_eject(dev);
22828 		}
22829 		break;
22830 
22831 	case CDROMVOLCTRL:
22832 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
22833 		if (!ISCD(un)) {
22834 			err = ENOTTY;
22835 		} else {
22836 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
22837 		}
22838 		break;
22839 
22840 	case CDROMSUBCHNL:
22841 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
22842 		if (!ISCD(un)) {
22843 			err = ENOTTY;
22844 		} else {
22845 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
22846 		}
22847 		break;
22848 
22849 	case CDROMREADMODE2:
22850 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
22851 		if (!ISCD(un)) {
22852 			err = ENOTTY;
22853 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22854 			/*
22855 			 * If the drive supports READ CD, use that instead of
22856 			 * switching the LBA size via a MODE SELECT
22857 			 * Block Descriptor
22858 			 */
22859 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
22860 		} else {
22861 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
22862 		}
22863 		break;
22864 
22865 	case CDROMREADMODE1:
22866 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
22867 		if (!ISCD(un)) {
22868 			err = ENOTTY;
22869 		} else {
22870 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
22871 		}
22872 		break;
22873 
22874 	case CDROMREADOFFSET:
22875 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
22876 		if (!ISCD(un)) {
22877 			err = ENOTTY;
22878 		} else {
22879 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
22880 			    flag);
22881 		}
22882 		break;
22883 
22884 	case CDROMSBLKMODE:
22885 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
22886 		/*
22887 		 * There is no means of changing block size in case of atapi
22888 		 * drives, thus return ENOTTY if drive type is atapi
22889 		 */
22890 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22891 			err = ENOTTY;
22892 		} else if (un->un_f_mmc_cap == TRUE) {
22893 
22894 			/*
22895 			 * MMC Devices do not support changing the
22896 			 * logical block size
22897 			 *
22898 			 * Note: EINVAL is being returned instead of ENOTTY to
22899 			 * maintain consistancy with the original mmc
22900 			 * driver update.
22901 			 */
22902 			err = EINVAL;
22903 		} else {
22904 			mutex_enter(SD_MUTEX(un));
22905 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
22906 			    (un->un_ncmds_in_transport > 0)) {
22907 				mutex_exit(SD_MUTEX(un));
22908 				err = EINVAL;
22909 			} else {
22910 				mutex_exit(SD_MUTEX(un));
22911 				err = sr_change_blkmode(dev, cmd, arg, flag);
22912 			}
22913 		}
22914 		break;
22915 
22916 	case CDROMGBLKMODE:
22917 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
22918 		if (!ISCD(un)) {
22919 			err = ENOTTY;
22920 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
22921 		    (un->un_f_blockcount_is_valid != FALSE)) {
22922 			/*
22923 			 * Drive is an ATAPI drive so return target block
22924 			 * size for ATAPI drives since we cannot change the
22925 			 * blocksize on ATAPI drives. Used primarily to detect
22926 			 * if an ATAPI cdrom is present.
22927 			 */
22928 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
22929 			    sizeof (int), flag) != 0) {
22930 				err = EFAULT;
22931 			} else {
22932 				err = 0;
22933 			}
22934 
22935 		} else {
22936 			/*
22937 			 * Drive supports changing block sizes via a Mode
22938 			 * Select.
22939 			 */
22940 			err = sr_change_blkmode(dev, cmd, arg, flag);
22941 		}
22942 		break;
22943 
22944 	case CDROMGDRVSPEED:
22945 	case CDROMSDRVSPEED:
22946 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
22947 		if (!ISCD(un)) {
22948 			err = ENOTTY;
22949 		} else if (un->un_f_mmc_cap == TRUE) {
22950 			/*
22951 			 * Note: In the future the driver implementation
22952 			 * for getting and
22953 			 * setting cd speed should entail:
22954 			 * 1) If non-mmc try the Toshiba mode page
22955 			 *    (sr_change_speed)
22956 			 * 2) If mmc but no support for Real Time Streaming try
22957 			 *    the SET CD SPEED (0xBB) command
22958 			 *   (sr_atapi_change_speed)
22959 			 * 3) If mmc and support for Real Time Streaming
22960 			 *    try the GET PERFORMANCE and SET STREAMING
22961 			 *    commands (not yet implemented, 4380808)
22962 			 */
22963 			/*
22964 			 * As per recent MMC spec, CD-ROM speed is variable
22965 			 * and changes with LBA. Since there is no such
22966 			 * things as drive speed now, fail this ioctl.
22967 			 *
22968 			 * Note: EINVAL is returned for consistancy of original
22969 			 * implementation which included support for getting
22970 			 * the drive speed of mmc devices but not setting
22971 			 * the drive speed. Thus EINVAL would be returned
22972 			 * if a set request was made for an mmc device.
22973 			 * We no longer support get or set speed for
22974 			 * mmc but need to remain consistent with regard
22975 			 * to the error code returned.
22976 			 */
22977 			err = EINVAL;
22978 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22979 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
22980 		} else {
22981 			err = sr_change_speed(dev, cmd, arg, flag);
22982 		}
22983 		break;
22984 
22985 	case CDROMCDDA:
22986 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
22987 		if (!ISCD(un)) {
22988 			err = ENOTTY;
22989 		} else {
22990 			err = sr_read_cdda(dev, (void *)arg, flag);
22991 		}
22992 		break;
22993 
22994 	case CDROMCDXA:
22995 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
22996 		if (!ISCD(un)) {
22997 			err = ENOTTY;
22998 		} else {
22999 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
23000 		}
23001 		break;
23002 
23003 	case CDROMSUBCODE:
23004 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
23005 		if (!ISCD(un)) {
23006 			err = ENOTTY;
23007 		} else {
23008 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
23009 		}
23010 		break;
23011 
23012 
23013 #ifdef SDDEBUG
23014 /* RESET/ABORTS testing ioctls */
23015 	case DKIOCRESET: {
23016 		int	reset_level;
23017 
23018 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
23019 			err = EFAULT;
23020 		} else {
23021 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
23022 			    "reset_level = 0x%lx\n", reset_level);
23023 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
23024 				err = 0;
23025 			} else {
23026 				err = EIO;
23027 			}
23028 		}
23029 		break;
23030 	}
23031 
23032 	case DKIOCABORT:
23033 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
23034 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
23035 			err = 0;
23036 		} else {
23037 			err = EIO;
23038 		}
23039 		break;
23040 #endif
23041 
23042 #ifdef SD_FAULT_INJECTION
23043 /* SDIOC FaultInjection testing ioctls */
23044 	case SDIOCSTART:
23045 	case SDIOCSTOP:
23046 	case SDIOCINSERTPKT:
23047 	case SDIOCINSERTXB:
23048 	case SDIOCINSERTUN:
23049 	case SDIOCINSERTARQ:
23050 	case SDIOCPUSH:
23051 	case SDIOCRETRIEVE:
23052 	case SDIOCRUN:
23053 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
23054 		    "SDIOC detected cmd:0x%X:\n", cmd);
23055 		/* call error generator */
23056 		sd_faultinjection_ioctl(cmd, arg, un);
23057 		err = 0;
23058 		break;
23059 
23060 #endif /* SD_FAULT_INJECTION */
23061 
23062 	case DKIOCFLUSHWRITECACHE:
23063 		{
23064 			struct dk_callback *dkc = (struct dk_callback *)arg;
23065 
23066 			mutex_enter(SD_MUTEX(un));
23067 			if (!un->un_f_sync_cache_supported ||
23068 			    !un->un_f_write_cache_enabled) {
23069 				err = un->un_f_sync_cache_supported ?
23070 				    0 : ENOTSUP;
23071 				mutex_exit(SD_MUTEX(un));
23072 				if ((flag & FKIOCTL) && dkc != NULL &&
23073 				    dkc->dkc_callback != NULL) {
23074 					(*dkc->dkc_callback)(dkc->dkc_cookie,
23075 					    err);
23076 					/*
23077 					 * Did callback and reported error.
23078 					 * Since we did a callback, ioctl
23079 					 * should return 0.
23080 					 */
23081 					err = 0;
23082 				}
23083 				break;
23084 			}
23085 			mutex_exit(SD_MUTEX(un));
23086 
23087 			if ((flag & FKIOCTL) && dkc != NULL &&
23088 			    dkc->dkc_callback != NULL) {
23089 				/* async SYNC CACHE request */
23090 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
23091 			} else {
23092 				/* synchronous SYNC CACHE request */
23093 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
23094 			}
23095 		}
23096 		break;
23097 
23098 	case DKIOCGETWCE: {
23099 
23100 		int wce;
23101 
23102 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
23103 			break;
23104 		}
23105 
23106 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
23107 			err = EFAULT;
23108 		}
23109 		break;
23110 	}
23111 
23112 	case DKIOCSETWCE: {
23113 
23114 		int wce, sync_supported;
23115 		int cur_wce = 0;
23116 
23117 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
23118 			err = EFAULT;
23119 			break;
23120 		}
23121 
23122 		/*
23123 		 * Synchronize multiple threads trying to enable
23124 		 * or disable the cache via the un_f_wcc_cv
23125 		 * condition variable.
23126 		 */
23127 		mutex_enter(SD_MUTEX(un));
23128 
23129 		/*
23130 		 * Don't allow the cache to be enabled if the
23131 		 * config file has it disabled.
23132 		 */
23133 		if (un->un_f_opt_disable_cache && wce) {
23134 			mutex_exit(SD_MUTEX(un));
23135 			err = EINVAL;
23136 			break;
23137 		}
23138 
23139 		/*
23140 		 * Wait for write cache change in progress
23141 		 * bit to be clear before proceeding.
23142 		 */
23143 		while (un->un_f_wcc_inprog)
23144 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
23145 
23146 		un->un_f_wcc_inprog = 1;
23147 
23148 		mutex_exit(SD_MUTEX(un));
23149 
23150 		/*
23151 		 * Get the current write cache state
23152 		 */
23153 		if ((err = sd_get_write_cache_enabled(ssc, &cur_wce)) != 0) {
23154 			mutex_enter(SD_MUTEX(un));
23155 			un->un_f_wcc_inprog = 0;
23156 			cv_broadcast(&un->un_wcc_cv);
23157 			mutex_exit(SD_MUTEX(un));
23158 			break;
23159 		}
23160 
23161 		mutex_enter(SD_MUTEX(un));
23162 		un->un_f_write_cache_enabled = (cur_wce != 0);
23163 
23164 		if (un->un_f_write_cache_enabled && wce == 0) {
23165 			/*
23166 			 * Disable the write cache.  Don't clear
23167 			 * un_f_write_cache_enabled until after
23168 			 * the mode select and flush are complete.
23169 			 */
23170 			sync_supported = un->un_f_sync_cache_supported;
23171 
23172 			/*
23173 			 * If cache flush is suppressed, we assume that the
23174 			 * controller firmware will take care of managing the
23175 			 * write cache for us: no need to explicitly
23176 			 * disable it.
23177 			 */
23178 			if (!un->un_f_suppress_cache_flush) {
23179 				mutex_exit(SD_MUTEX(un));
23180 				if ((err = sd_cache_control(ssc,
23181 				    SD_CACHE_NOCHANGE,
23182 				    SD_CACHE_DISABLE)) == 0 &&
23183 				    sync_supported) {
23184 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
23185 					    NULL);
23186 				}
23187 			} else {
23188 				mutex_exit(SD_MUTEX(un));
23189 			}
23190 
23191 			mutex_enter(SD_MUTEX(un));
23192 			if (err == 0) {
23193 				un->un_f_write_cache_enabled = 0;
23194 			}
23195 
23196 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
23197 			/*
23198 			 * Set un_f_write_cache_enabled first, so there is
23199 			 * no window where the cache is enabled, but the
23200 			 * bit says it isn't.
23201 			 */
23202 			un->un_f_write_cache_enabled = 1;
23203 
23204 			/*
23205 			 * If cache flush is suppressed, we assume that the
23206 			 * controller firmware will take care of managing the
23207 			 * write cache for us: no need to explicitly
23208 			 * enable it.
23209 			 */
23210 			if (!un->un_f_suppress_cache_flush) {
23211 				mutex_exit(SD_MUTEX(un));
23212 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
23213 				    SD_CACHE_ENABLE);
23214 			} else {
23215 				mutex_exit(SD_MUTEX(un));
23216 			}
23217 
23218 			mutex_enter(SD_MUTEX(un));
23219 
23220 			if (err) {
23221 				un->un_f_write_cache_enabled = 0;
23222 			}
23223 		}
23224 
23225 		un->un_f_wcc_inprog = 0;
23226 		cv_broadcast(&un->un_wcc_cv);
23227 		mutex_exit(SD_MUTEX(un));
23228 		break;
23229 	}
23230 
23231 	default:
23232 		err = ENOTTY;
23233 		break;
23234 	}
23235 	mutex_enter(SD_MUTEX(un));
23236 	un->un_ncmds_in_driver--;
23237 	ASSERT(un->un_ncmds_in_driver >= 0);
23238 	mutex_exit(SD_MUTEX(un));
23239 
23240 
23241 done_without_assess:
23242 	sd_ssc_fini(ssc);
23243 
23244 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23245 	return (err);
23246 
23247 done_with_assess:
23248 	mutex_enter(SD_MUTEX(un));
23249 	un->un_ncmds_in_driver--;
23250 	ASSERT(un->un_ncmds_in_driver >= 0);
23251 	mutex_exit(SD_MUTEX(un));
23252 
23253 done_quick_assess:
23254 	if (err != 0)
23255 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23256 	/* Uninitialize sd_ssc_t pointer */
23257 	sd_ssc_fini(ssc);
23258 
23259 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23260 	return (err);
23261 }
23262 
23263 
23264 /*
23265  *    Function: sd_dkio_ctrl_info
23266  *
23267  * Description: This routine is the driver entry point for handling controller
23268  *		information ioctl requests (DKIOCINFO).
23269  *
23270  *   Arguments: dev  - the device number
23271  *		arg  - pointer to user provided dk_cinfo structure
23272  *		       specifying the controller type and attributes.
23273  *		flag - this argument is a pass through to ddi_copyxxx()
23274  *		       directly from the mode argument of ioctl().
23275  *
23276  * Return Code: 0
23277  *		EFAULT
23278  *		ENXIO
23279  */
23280 
23281 static int
23282 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
23283 {
23284 	struct sd_lun	*un = NULL;
23285 	struct dk_cinfo	*info;
23286 	dev_info_t	*pdip;
23287 	int		lun, tgt;
23288 
23289 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23290 		return (ENXIO);
23291 	}
23292 
23293 	info = (struct dk_cinfo *)
23294 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
23295 
23296 	switch (un->un_ctype) {
23297 	case CTYPE_CDROM:
23298 		info->dki_ctype = DKC_CDROM;
23299 		break;
23300 	default:
23301 		info->dki_ctype = DKC_SCSI_CCS;
23302 		break;
23303 	}
23304 	pdip = ddi_get_parent(SD_DEVINFO(un));
23305 	info->dki_cnum = ddi_get_instance(pdip);
23306 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
23307 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
23308 	} else {
23309 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
23310 		    DK_DEVLEN - 1);
23311 	}
23312 
23313 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23314 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
23315 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23316 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
23317 
23318 	/* Unit Information */
23319 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
23320 	info->dki_slave = ((tgt << 3) | lun);
23321 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
23322 	    DK_DEVLEN - 1);
23323 	info->dki_flags = DKI_FMTVOL;
23324 	info->dki_partition = SDPART(dev);
23325 
23326 	/* Max Transfer size of this device in blocks */
23327 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
23328 	info->dki_addr = 0;
23329 	info->dki_space = 0;
23330 	info->dki_prio = 0;
23331 	info->dki_vec = 0;
23332 
23333 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
23334 		kmem_free(info, sizeof (struct dk_cinfo));
23335 		return (EFAULT);
23336 	} else {
23337 		kmem_free(info, sizeof (struct dk_cinfo));
23338 		return (0);
23339 	}
23340 }
23341 
23342 /*
23343  *    Function: sd_get_media_info_com
23344  *
23345  * Description: This routine returns the information required to populate
23346  *		the fields for the dk_minfo/dk_minfo_ext structures.
23347  *
23348  *   Arguments: dev		- the device number
23349  *		dki_media_type	- media_type
23350  *		dki_lbsize	- logical block size
23351  *		dki_capacity	- capacity in blocks
23352  *		dki_pbsize	- physical block size (if requested)
23353  *
23354  * Return Code: 0
23355  *		EACCESS
23356  *		EFAULT
23357  *		ENXIO
23358  *		EIO
23359  */
23360 static int
23361 sd_get_media_info_com(dev_t dev, uint_t *dki_media_type, uint_t *dki_lbsize,
23362 	diskaddr_t *dki_capacity, uint_t *dki_pbsize)
23363 {
23364 	struct sd_lun		*un = NULL;
23365 	struct uscsi_cmd	com;
23366 	struct scsi_inquiry	*sinq;
23367 	u_longlong_t		media_capacity;
23368 	uint64_t		capacity;
23369 	uint_t			lbasize;
23370 	uint_t			pbsize;
23371 	uchar_t			*out_data;
23372 	uchar_t			*rqbuf;
23373 	int			rval = 0;
23374 	int			rtn;
23375 	sd_ssc_t		*ssc;
23376 
23377 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
23378 	    (un->un_state == SD_STATE_OFFLINE)) {
23379 		return (ENXIO);
23380 	}
23381 
23382 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info_com: entry\n");
23383 
23384 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
23385 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
23386 	ssc = sd_ssc_init(un);
23387 
23388 	/* Issue a TUR to determine if the drive is ready with media present */
23389 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
23390 	if (rval == ENXIO) {
23391 		goto done;
23392 	} else if (rval != 0) {
23393 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23394 	}
23395 
23396 	/* Now get configuration data */
23397 	if (ISCD(un)) {
23398 		*dki_media_type = DK_CDROM;
23399 
23400 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
23401 		if (un->un_f_mmc_cap == TRUE) {
23402 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
23403 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
23404 			    SD_PATH_STANDARD);
23405 
23406 			if (rtn) {
23407 				/*
23408 				 * We ignore all failures for CD and need to
23409 				 * put the assessment before processing code
23410 				 * to avoid missing assessment for FMA.
23411 				 */
23412 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23413 				/*
23414 				 * Failed for other than an illegal request
23415 				 * or command not supported
23416 				 */
23417 				if ((com.uscsi_status == STATUS_CHECK) &&
23418 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
23419 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
23420 					    (rqbuf[12] != 0x20)) {
23421 						rval = EIO;
23422 						goto no_assessment;
23423 					}
23424 				}
23425 			} else {
23426 				/*
23427 				 * The GET CONFIGURATION command succeeded
23428 				 * so set the media type according to the
23429 				 * returned data
23430 				 */
23431 				*dki_media_type = out_data[6];
23432 				*dki_media_type <<= 8;
23433 				*dki_media_type |= out_data[7];
23434 			}
23435 		}
23436 	} else {
23437 		/*
23438 		 * The profile list is not available, so we attempt to identify
23439 		 * the media type based on the inquiry data
23440 		 */
23441 		sinq = un->un_sd->sd_inq;
23442 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
23443 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
23444 			/* This is a direct access device  or optical disk */
23445 			*dki_media_type = DK_FIXED_DISK;
23446 
23447 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
23448 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
23449 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
23450 					*dki_media_type = DK_ZIP;
23451 				} else if (
23452 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
23453 					*dki_media_type = DK_JAZ;
23454 				}
23455 			}
23456 		} else {
23457 			/*
23458 			 * Not a CD, direct access or optical disk so return
23459 			 * unknown media
23460 			 */
23461 			*dki_media_type = DK_UNKNOWN;
23462 		}
23463 	}
23464 
23465 	/*
23466 	 * Now read the capacity so we can provide the lbasize,
23467 	 * pbsize and capacity.
23468 	 */
23469 	if (dki_pbsize && un->un_f_descr_format_supported)
23470 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
23471 		    &pbsize, SD_PATH_DIRECT);
23472 
23473 	if (dki_pbsize == NULL || rval != 0 ||
23474 	    !un->un_f_descr_format_supported) {
23475 		rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
23476 		    SD_PATH_DIRECT);
23477 
23478 		switch (rval) {
23479 		case 0:
23480 			if (un->un_f_enable_rmw &&
23481 			    un->un_phy_blocksize != 0) {
23482 				pbsize = un->un_phy_blocksize;
23483 			} else {
23484 				pbsize = lbasize;
23485 			}
23486 			media_capacity = capacity;
23487 
23488 			/*
23489 			 * sd_send_scsi_READ_CAPACITY() reports capacity in
23490 			 * un->un_sys_blocksize chunks. So we need to convert
23491 			 * it into cap.lbsize chunks.
23492 			 */
23493 			if (un->un_f_has_removable_media) {
23494 				media_capacity *= un->un_sys_blocksize;
23495 				media_capacity /= lbasize;
23496 			}
23497 			break;
23498 		case EACCES:
23499 			rval = EACCES;
23500 			goto done;
23501 		default:
23502 			rval = EIO;
23503 			goto done;
23504 		}
23505 	} else {
23506 		if (un->un_f_enable_rmw &&
23507 		    !ISP2(pbsize % DEV_BSIZE)) {
23508 			pbsize = SSD_SECSIZE;
23509 		} else if (!ISP2(lbasize % DEV_BSIZE) ||
23510 		    !ISP2(pbsize % DEV_BSIZE)) {
23511 			pbsize = lbasize = DEV_BSIZE;
23512 		}
23513 		media_capacity = capacity;
23514 	}
23515 
23516 	/*
23517 	 * If lun is expanded dynamically, update the un structure.
23518 	 */
23519 	mutex_enter(SD_MUTEX(un));
23520 	if ((un->un_f_blockcount_is_valid == TRUE) &&
23521 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
23522 	    (capacity > un->un_blockcount)) {
23523 		un->un_f_expnevent = B_FALSE;
23524 		sd_update_block_info(un, lbasize, capacity);
23525 	}
23526 	mutex_exit(SD_MUTEX(un));
23527 
23528 	*dki_lbsize = lbasize;
23529 	*dki_capacity = media_capacity;
23530 	if (dki_pbsize)
23531 		*dki_pbsize = pbsize;
23532 
23533 done:
23534 	if (rval != 0) {
23535 		if (rval == EIO)
23536 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23537 		else
23538 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23539 	}
23540 no_assessment:
23541 	sd_ssc_fini(ssc);
23542 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
23543 	kmem_free(rqbuf, SENSE_LENGTH);
23544 	return (rval);
23545 }
23546 
23547 /*
23548  *    Function: sd_get_media_info
23549  *
23550  * Description: This routine is the driver entry point for handling ioctl
23551  *		requests for the media type or command set profile used by the
23552  *		drive to operate on the media (DKIOCGMEDIAINFO).
23553  *
23554  *   Arguments: dev	- the device number
23555  *		arg	- pointer to user provided dk_minfo structure
23556  *			  specifying the media type, logical block size and
23557  *			  drive capacity.
23558  *		flag	- this argument is a pass through to ddi_copyxxx()
23559  *			  directly from the mode argument of ioctl().
23560  *
23561  * Return Code: returns the value from sd_get_media_info_com
23562  */
23563 static int
23564 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
23565 {
23566 	struct dk_minfo		mi;
23567 	int			rval;
23568 
23569 	rval = sd_get_media_info_com(dev, &mi.dki_media_type,
23570 	    &mi.dki_lbsize, &mi.dki_capacity, NULL);
23571 
23572 	if (rval)
23573 		return (rval);
23574 	if (ddi_copyout(&mi, arg, sizeof (struct dk_minfo), flag))
23575 		rval = EFAULT;
23576 	return (rval);
23577 }
23578 
23579 /*
23580  *    Function: sd_get_media_info_ext
23581  *
23582  * Description: This routine is the driver entry point for handling ioctl
23583  *		requests for the media type or command set profile used by the
23584  *		drive to operate on the media (DKIOCGMEDIAINFOEXT). The
23585  *		difference this ioctl and DKIOCGMEDIAINFO is the return value
23586  *		of this ioctl contains both logical block size and physical
23587  *		block size.
23588  *
23589  *
23590  *   Arguments: dev	- the device number
23591  *		arg	- pointer to user provided dk_minfo_ext structure
23592  *			  specifying the media type, logical block size,
23593  *			  physical block size and disk capacity.
23594  *		flag	- this argument is a pass through to ddi_copyxxx()
23595  *			  directly from the mode argument of ioctl().
23596  *
23597  * Return Code: returns the value from sd_get_media_info_com
23598  */
23599 static int
23600 sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag)
23601 {
23602 	struct dk_minfo_ext	mie;
23603 	int			rval = 0;
23604 
23605 	rval = sd_get_media_info_com(dev, &mie.dki_media_type,
23606 	    &mie.dki_lbsize, &mie.dki_capacity, &mie.dki_pbsize);
23607 
23608 	if (rval)
23609 		return (rval);
23610 	if (ddi_copyout(&mie, arg, sizeof (struct dk_minfo_ext), flag))
23611 		rval = EFAULT;
23612 	return (rval);
23613 
23614 }
23615 
23616 /*
23617  *    Function: sd_watch_request_submit
23618  *
23619  * Description: Call scsi_watch_request_submit or scsi_mmc_watch_request_submit
23620  *		depending on which is supported by device.
23621  */
23622 static opaque_t
23623 sd_watch_request_submit(struct sd_lun *un)
23624 {
23625 	dev_t			dev;
23626 
23627 	/* All submissions are unified to use same device number */
23628 	dev = sd_make_device(SD_DEVINFO(un));
23629 
23630 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
23631 		return (scsi_mmc_watch_request_submit(SD_SCSI_DEVP(un),
23632 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23633 		    (caddr_t)dev));
23634 	} else {
23635 		return (scsi_watch_request_submit(SD_SCSI_DEVP(un),
23636 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23637 		    (caddr_t)dev));
23638 	}
23639 }
23640 
23641 
23642 /*
23643  *    Function: sd_check_media
23644  *
23645  * Description: This utility routine implements the functionality for the
23646  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
23647  *		driver state changes from that specified by the user
23648  *		(inserted or ejected). For example, if the user specifies
23649  *		DKIO_EJECTED and the current media state is inserted this
23650  *		routine will immediately return DKIO_INSERTED. However, if the
23651  *		current media state is not inserted the user thread will be
23652  *		blocked until the drive state changes. If DKIO_NONE is specified
23653  *		the user thread will block until a drive state change occurs.
23654  *
23655  *   Arguments: dev  - the device number
23656  *		state  - user pointer to a dkio_state, updated with the current
23657  *			drive state at return.
23658  *
23659  * Return Code: ENXIO
23660  *		EIO
23661  *		EAGAIN
23662  *		EINTR
23663  */
23664 
23665 static int
23666 sd_check_media(dev_t dev, enum dkio_state state)
23667 {
23668 	struct sd_lun		*un = NULL;
23669 	enum dkio_state		prev_state;
23670 	opaque_t		token = NULL;
23671 	int			rval = 0;
23672 	sd_ssc_t		*ssc;
23673 
23674 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23675 		return (ENXIO);
23676 	}
23677 
23678 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
23679 
23680 	ssc = sd_ssc_init(un);
23681 
23682 	mutex_enter(SD_MUTEX(un));
23683 
23684 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
23685 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
23686 
23687 	prev_state = un->un_mediastate;
23688 
23689 	/* is there anything to do? */
23690 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
23691 		/*
23692 		 * submit the request to the scsi_watch service;
23693 		 * scsi_media_watch_cb() does the real work
23694 		 */
23695 		mutex_exit(SD_MUTEX(un));
23696 
23697 		/*
23698 		 * This change handles the case where a scsi watch request is
23699 		 * added to a device that is powered down. To accomplish this
23700 		 * we power up the device before adding the scsi watch request,
23701 		 * since the scsi watch sends a TUR directly to the device
23702 		 * which the device cannot handle if it is powered down.
23703 		 */
23704 		if (sd_pm_entry(un) != DDI_SUCCESS) {
23705 			mutex_enter(SD_MUTEX(un));
23706 			goto done;
23707 		}
23708 
23709 		token = sd_watch_request_submit(un);
23710 
23711 		sd_pm_exit(un);
23712 
23713 		mutex_enter(SD_MUTEX(un));
23714 		if (token == NULL) {
23715 			rval = EAGAIN;
23716 			goto done;
23717 		}
23718 
23719 		/*
23720 		 * This is a special case IOCTL that doesn't return
23721 		 * until the media state changes. Routine sdpower
23722 		 * knows about and handles this so don't count it
23723 		 * as an active cmd in the driver, which would
23724 		 * keep the device busy to the pm framework.
23725 		 * If the count isn't decremented the device can't
23726 		 * be powered down.
23727 		 */
23728 		un->un_ncmds_in_driver--;
23729 		ASSERT(un->un_ncmds_in_driver >= 0);
23730 
23731 		/*
23732 		 * if a prior request had been made, this will be the same
23733 		 * token, as scsi_watch was designed that way.
23734 		 */
23735 		un->un_swr_token = token;
23736 		un->un_specified_mediastate = state;
23737 
23738 		/*
23739 		 * now wait for media change
23740 		 * we will not be signalled unless mediastate == state but it is
23741 		 * still better to test for this condition, since there is a
23742 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
23743 		 */
23744 		SD_TRACE(SD_LOG_COMMON, un,
23745 		    "sd_check_media: waiting for media state change\n");
23746 		while (un->un_mediastate == state) {
23747 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
23748 				SD_TRACE(SD_LOG_COMMON, un,
23749 				    "sd_check_media: waiting for media state "
23750 				    "was interrupted\n");
23751 				un->un_ncmds_in_driver++;
23752 				rval = EINTR;
23753 				goto done;
23754 			}
23755 			SD_TRACE(SD_LOG_COMMON, un,
23756 			    "sd_check_media: received signal, state=%x\n",
23757 			    un->un_mediastate);
23758 		}
23759 		/*
23760 		 * Inc the counter to indicate the device once again
23761 		 * has an active outstanding cmd.
23762 		 */
23763 		un->un_ncmds_in_driver++;
23764 	}
23765 
23766 	/* invalidate geometry */
23767 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
23768 		sr_ejected(un);
23769 	}
23770 
23771 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
23772 		uint64_t	capacity;
23773 		uint_t		lbasize;
23774 
23775 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
23776 		mutex_exit(SD_MUTEX(un));
23777 		/*
23778 		 * Since the following routines use SD_PATH_DIRECT, we must
23779 		 * call PM directly before the upcoming disk accesses. This
23780 		 * may cause the disk to be power/spin up.
23781 		 */
23782 
23783 		if (sd_pm_entry(un) == DDI_SUCCESS) {
23784 			rval = sd_send_scsi_READ_CAPACITY(ssc,
23785 			    &capacity, &lbasize, SD_PATH_DIRECT);
23786 			if (rval != 0) {
23787 				sd_pm_exit(un);
23788 				if (rval == EIO)
23789 					sd_ssc_assessment(ssc,
23790 					    SD_FMT_STATUS_CHECK);
23791 				else
23792 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23793 				mutex_enter(SD_MUTEX(un));
23794 				goto done;
23795 			}
23796 		} else {
23797 			rval = EIO;
23798 			mutex_enter(SD_MUTEX(un));
23799 			goto done;
23800 		}
23801 		mutex_enter(SD_MUTEX(un));
23802 
23803 		sd_update_block_info(un, lbasize, capacity);
23804 
23805 		/*
23806 		 *  Check if the media in the device is writable or not
23807 		 */
23808 		if (ISCD(un)) {
23809 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
23810 		}
23811 
23812 		mutex_exit(SD_MUTEX(un));
23813 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
23814 		if ((cmlb_validate(un->un_cmlbhandle, 0,
23815 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
23816 			sd_set_pstats(un);
23817 			SD_TRACE(SD_LOG_IO_PARTITION, un,
23818 			    "sd_check_media: un:0x%p pstats created and "
23819 			    "set\n", un);
23820 		}
23821 
23822 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
23823 		    SD_PATH_DIRECT);
23824 
23825 		sd_pm_exit(un);
23826 
23827 		if (rval != 0) {
23828 			if (rval == EIO)
23829 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23830 			else
23831 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23832 		}
23833 
23834 		mutex_enter(SD_MUTEX(un));
23835 	}
23836 done:
23837 	sd_ssc_fini(ssc);
23838 	un->un_f_watcht_stopped = FALSE;
23839 	if (token != NULL && un->un_swr_token != NULL) {
23840 		/*
23841 		 * Use of this local token and the mutex ensures that we avoid
23842 		 * some race conditions associated with terminating the
23843 		 * scsi watch.
23844 		 */
23845 		token = un->un_swr_token;
23846 		mutex_exit(SD_MUTEX(un));
23847 		(void) scsi_watch_request_terminate(token,
23848 		    SCSI_WATCH_TERMINATE_WAIT);
23849 		if (scsi_watch_get_ref_count(token) == 0) {
23850 			mutex_enter(SD_MUTEX(un));
23851 			un->un_swr_token = (opaque_t)NULL;
23852 		} else {
23853 			mutex_enter(SD_MUTEX(un));
23854 		}
23855 	}
23856 
23857 	/*
23858 	 * Update the capacity kstat value, if no media previously
23859 	 * (capacity kstat is 0) and a media has been inserted
23860 	 * (un_f_blockcount_is_valid == TRUE)
23861 	 */
23862 	if (un->un_errstats) {
23863 		struct sd_errstats	*stp = NULL;
23864 
23865 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
23866 		if ((stp->sd_capacity.value.ui64 == 0) &&
23867 		    (un->un_f_blockcount_is_valid == TRUE)) {
23868 			stp->sd_capacity.value.ui64 =
23869 			    (uint64_t)((uint64_t)un->un_blockcount *
23870 			    un->un_sys_blocksize);
23871 		}
23872 	}
23873 	mutex_exit(SD_MUTEX(un));
23874 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
23875 	return (rval);
23876 }
23877 
23878 
23879 /*
23880  *    Function: sd_delayed_cv_broadcast
23881  *
23882  * Description: Delayed cv_broadcast to allow for target to recover from media
23883  *		insertion.
23884  *
23885  *   Arguments: arg - driver soft state (unit) structure
23886  */
23887 
23888 static void
23889 sd_delayed_cv_broadcast(void *arg)
23890 {
23891 	struct sd_lun *un = arg;
23892 
23893 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
23894 
23895 	mutex_enter(SD_MUTEX(un));
23896 	un->un_dcvb_timeid = NULL;
23897 	cv_broadcast(&un->un_state_cv);
23898 	mutex_exit(SD_MUTEX(un));
23899 }
23900 
23901 
23902 /*
23903  *    Function: sd_media_watch_cb
23904  *
23905  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
23906  *		routine processes the TUR sense data and updates the driver
23907  *		state if a transition has occurred. The user thread
23908  *		(sd_check_media) is then signalled.
23909  *
23910  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
23911  *			among multiple watches that share this callback function
23912  *		resultp - scsi watch facility result packet containing scsi
23913  *			  packet, status byte and sense data
23914  *
23915  * Return Code: 0 for success, -1 for failure
23916  */
23917 
23918 static int
23919 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
23920 {
23921 	struct sd_lun			*un;
23922 	struct scsi_status		*statusp = resultp->statusp;
23923 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
23924 	enum dkio_state			state = DKIO_NONE;
23925 	dev_t				dev = (dev_t)arg;
23926 	uchar_t				actual_sense_length;
23927 	uint8_t				skey, asc, ascq;
23928 
23929 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23930 		return (-1);
23931 	}
23932 	actual_sense_length = resultp->actual_sense_length;
23933 
23934 	mutex_enter(SD_MUTEX(un));
23935 	SD_TRACE(SD_LOG_COMMON, un,
23936 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
23937 	    *((char *)statusp), (void *)sensep, actual_sense_length);
23938 
23939 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
23940 		un->un_mediastate = DKIO_DEV_GONE;
23941 		cv_broadcast(&un->un_state_cv);
23942 		mutex_exit(SD_MUTEX(un));
23943 
23944 		return (0);
23945 	}
23946 
23947 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
23948 		if (sd_gesn_media_data_valid(resultp->mmc_data)) {
23949 			if ((resultp->mmc_data[5] &
23950 			    SD_GESN_MEDIA_EVENT_STATUS_PRESENT) != 0) {
23951 				state = DKIO_INSERTED;
23952 			} else {
23953 				state = DKIO_EJECTED;
23954 			}
23955 			if ((resultp->mmc_data[4] & SD_GESN_MEDIA_EVENT_CODE) ==
23956 			    SD_GESN_MEDIA_EVENT_EJECTREQUEST) {
23957 				sd_log_eject_request_event(un, KM_NOSLEEP);
23958 			}
23959 		}
23960 	} else if (sensep != NULL) {
23961 		/*
23962 		 * If there was a check condition then sensep points to valid
23963 		 * sense data. If status was not a check condition but a
23964 		 * reservation or busy status then the new state is DKIO_NONE.
23965 		 */
23966 		skey = scsi_sense_key(sensep);
23967 		asc = scsi_sense_asc(sensep);
23968 		ascq = scsi_sense_ascq(sensep);
23969 
23970 		SD_INFO(SD_LOG_COMMON, un,
23971 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
23972 		    skey, asc, ascq);
23973 		/* This routine only uses up to 13 bytes of sense data. */
23974 		if (actual_sense_length >= 13) {
23975 			if (skey == KEY_UNIT_ATTENTION) {
23976 				if (asc == 0x28) {
23977 					state = DKIO_INSERTED;
23978 				}
23979 			} else if (skey == KEY_NOT_READY) {
23980 				/*
23981 				 * Sense data of 02/06/00 means that the
23982 				 * drive could not read the media (No
23983 				 * reference position found). In this case
23984 				 * to prevent a hang on the DKIOCSTATE IOCTL
23985 				 * we set the media state to DKIO_INSERTED.
23986 				 */
23987 				if (asc == 0x06 && ascq == 0x00)
23988 					state = DKIO_INSERTED;
23989 
23990 				/*
23991 				 * if 02/04/02  means that the host
23992 				 * should send start command. Explicitly
23993 				 * leave the media state as is
23994 				 * (inserted) as the media is inserted
23995 				 * and host has stopped device for PM
23996 				 * reasons. Upon next true read/write
23997 				 * to this media will bring the
23998 				 * device to the right state good for
23999 				 * media access.
24000 				 */
24001 				if (asc == 0x3a) {
24002 					state = DKIO_EJECTED;
24003 				} else {
24004 					/*
24005 					 * If the drive is busy with an
24006 					 * operation or long write, keep the
24007 					 * media in an inserted state.
24008 					 */
24009 
24010 					if ((asc == 0x04) &&
24011 					    ((ascq == 0x02) ||
24012 					    (ascq == 0x07) ||
24013 					    (ascq == 0x08))) {
24014 						state = DKIO_INSERTED;
24015 					}
24016 				}
24017 			} else if (skey == KEY_NO_SENSE) {
24018 				if ((asc == 0x00) && (ascq == 0x00)) {
24019 					/*
24020 					 * Sense Data 00/00/00 does not provide
24021 					 * any information about the state of
24022 					 * the media. Ignore it.
24023 					 */
24024 					mutex_exit(SD_MUTEX(un));
24025 					return (0);
24026 				}
24027 			}
24028 		}
24029 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
24030 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
24031 		state = DKIO_INSERTED;
24032 	}
24033 
24034 	SD_TRACE(SD_LOG_COMMON, un,
24035 	    "sd_media_watch_cb: state=%x, specified=%x\n",
24036 	    state, un->un_specified_mediastate);
24037 
24038 	/*
24039 	 * now signal the waiting thread if this is *not* the specified state;
24040 	 * delay the signal if the state is DKIO_INSERTED to allow the target
24041 	 * to recover
24042 	 */
24043 	if (state != un->un_specified_mediastate) {
24044 		un->un_mediastate = state;
24045 		if (state == DKIO_INSERTED) {
24046 			/*
24047 			 * delay the signal to give the drive a chance
24048 			 * to do what it apparently needs to do
24049 			 */
24050 			SD_TRACE(SD_LOG_COMMON, un,
24051 			    "sd_media_watch_cb: delayed cv_broadcast\n");
24052 			if (un->un_dcvb_timeid == NULL) {
24053 				un->un_dcvb_timeid =
24054 				    timeout(sd_delayed_cv_broadcast, un,
24055 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
24056 			}
24057 		} else {
24058 			SD_TRACE(SD_LOG_COMMON, un,
24059 			    "sd_media_watch_cb: immediate cv_broadcast\n");
24060 			cv_broadcast(&un->un_state_cv);
24061 		}
24062 	}
24063 	mutex_exit(SD_MUTEX(un));
24064 	return (0);
24065 }
24066 
24067 
24068 /*
24069  *    Function: sd_dkio_get_temp
24070  *
24071  * Description: This routine is the driver entry point for handling ioctl
24072  *		requests to get the disk temperature.
24073  *
24074  *   Arguments: dev  - the device number
24075  *		arg  - pointer to user provided dk_temperature structure.
24076  *		flag - this argument is a pass through to ddi_copyxxx()
24077  *		       directly from the mode argument of ioctl().
24078  *
24079  * Return Code: 0
24080  *		EFAULT
24081  *		ENXIO
24082  *		EAGAIN
24083  */
24084 
24085 static int
24086 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
24087 {
24088 	struct sd_lun		*un = NULL;
24089 	struct dk_temperature	*dktemp = NULL;
24090 	uchar_t			*temperature_page;
24091 	int			rval = 0;
24092 	int			path_flag = SD_PATH_STANDARD;
24093 	sd_ssc_t		*ssc;
24094 
24095 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24096 		return (ENXIO);
24097 	}
24098 
24099 	ssc = sd_ssc_init(un);
24100 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
24101 
24102 	/* copyin the disk temp argument to get the user flags */
24103 	if (ddi_copyin((void *)arg, dktemp,
24104 	    sizeof (struct dk_temperature), flag) != 0) {
24105 		rval = EFAULT;
24106 		goto done;
24107 	}
24108 
24109 	/* Initialize the temperature to invalid. */
24110 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24111 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24112 
24113 	/*
24114 	 * Note: Investigate removing the "bypass pm" semantic.
24115 	 * Can we just bypass PM always?
24116 	 */
24117 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
24118 		path_flag = SD_PATH_DIRECT;
24119 		ASSERT(!mutex_owned(&un->un_pm_mutex));
24120 		mutex_enter(&un->un_pm_mutex);
24121 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24122 			/*
24123 			 * If DKT_BYPASS_PM is set, and the drive happens to be
24124 			 * in low power mode, we can not wake it up, Need to
24125 			 * return EAGAIN.
24126 			 */
24127 			mutex_exit(&un->un_pm_mutex);
24128 			rval = EAGAIN;
24129 			goto done;
24130 		} else {
24131 			/*
24132 			 * Indicate to PM the device is busy. This is required
24133 			 * to avoid a race - i.e. the ioctl is issuing a
24134 			 * command and the pm framework brings down the device
24135 			 * to low power mode (possible power cut-off on some
24136 			 * platforms).
24137 			 */
24138 			mutex_exit(&un->un_pm_mutex);
24139 			if (sd_pm_entry(un) != DDI_SUCCESS) {
24140 				rval = EAGAIN;
24141 				goto done;
24142 			}
24143 		}
24144 	}
24145 
24146 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
24147 
24148 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
24149 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
24150 	if (rval != 0)
24151 		goto done2;
24152 
24153 	/*
24154 	 * For the current temperature verify that the parameter length is 0x02
24155 	 * and the parameter code is 0x00
24156 	 */
24157 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
24158 	    (temperature_page[5] == 0x00)) {
24159 		if (temperature_page[9] == 0xFF) {
24160 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24161 		} else {
24162 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
24163 		}
24164 	}
24165 
24166 	/*
24167 	 * For the reference temperature verify that the parameter
24168 	 * length is 0x02 and the parameter code is 0x01
24169 	 */
24170 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
24171 	    (temperature_page[11] == 0x01)) {
24172 		if (temperature_page[15] == 0xFF) {
24173 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24174 		} else {
24175 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
24176 		}
24177 	}
24178 
24179 	/* Do the copyout regardless of the temperature commands status. */
24180 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
24181 	    flag) != 0) {
24182 		rval = EFAULT;
24183 		goto done1;
24184 	}
24185 
24186 done2:
24187 	if (rval != 0) {
24188 		if (rval == EIO)
24189 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24190 		else
24191 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24192 	}
24193 done1:
24194 	if (path_flag == SD_PATH_DIRECT) {
24195 		sd_pm_exit(un);
24196 	}
24197 
24198 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
24199 done:
24200 	sd_ssc_fini(ssc);
24201 	if (dktemp != NULL) {
24202 		kmem_free(dktemp, sizeof (struct dk_temperature));
24203 	}
24204 
24205 	return (rval);
24206 }
24207 
24208 
24209 /*
24210  *    Function: sd_log_page_supported
24211  *
24212  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
24213  *		supported log pages.
24214  *
24215  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
24216  *                      structure for this target.
24217  *		log_page -
24218  *
24219  * Return Code: -1 - on error (log sense is optional and may not be supported).
24220  *		0  - log page not found.
24221  *  		1  - log page found.
24222  */
24223 
24224 static int
24225 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
24226 {
24227 	uchar_t *log_page_data;
24228 	int	i;
24229 	int	match = 0;
24230 	int	log_size;
24231 	int	status = 0;
24232 	struct sd_lun	*un;
24233 
24234 	ASSERT(ssc != NULL);
24235 	un = ssc->ssc_un;
24236 	ASSERT(un != NULL);
24237 
24238 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
24239 
24240 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
24241 	    SD_PATH_DIRECT);
24242 
24243 	if (status != 0) {
24244 		if (status == EIO) {
24245 			/*
24246 			 * Some disks do not support log sense, we
24247 			 * should ignore this kind of error(sense key is
24248 			 * 0x5 - illegal request).
24249 			 */
24250 			uint8_t *sensep;
24251 			int senlen;
24252 
24253 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
24254 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
24255 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
24256 
24257 			if (senlen > 0 &&
24258 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
24259 				sd_ssc_assessment(ssc,
24260 				    SD_FMT_IGNORE_COMPROMISE);
24261 			} else {
24262 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24263 			}
24264 		} else {
24265 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24266 		}
24267 
24268 		SD_ERROR(SD_LOG_COMMON, un,
24269 		    "sd_log_page_supported: failed log page retrieval\n");
24270 		kmem_free(log_page_data, 0xFF);
24271 		return (-1);
24272 	}
24273 
24274 	log_size = log_page_data[3];
24275 
24276 	/*
24277 	 * The list of supported log pages start from the fourth byte. Check
24278 	 * until we run out of log pages or a match is found.
24279 	 */
24280 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
24281 		if (log_page_data[i] == log_page) {
24282 			match++;
24283 		}
24284 	}
24285 	kmem_free(log_page_data, 0xFF);
24286 	return (match);
24287 }
24288 
24289 
24290 /*
24291  *    Function: sd_mhdioc_failfast
24292  *
24293  * Description: This routine is the driver entry point for handling ioctl
24294  *		requests to enable/disable the multihost failfast option.
24295  *		(MHIOCENFAILFAST)
24296  *
24297  *   Arguments: dev	- the device number
24298  *		arg	- user specified probing interval.
24299  *		flag	- this argument is a pass through to ddi_copyxxx()
24300  *			  directly from the mode argument of ioctl().
24301  *
24302  * Return Code: 0
24303  *		EFAULT
24304  *		ENXIO
24305  */
24306 
24307 static int
24308 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
24309 {
24310 	struct sd_lun	*un = NULL;
24311 	int		mh_time;
24312 	int		rval = 0;
24313 
24314 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24315 		return (ENXIO);
24316 	}
24317 
24318 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
24319 		return (EFAULT);
24320 
24321 	if (mh_time) {
24322 		mutex_enter(SD_MUTEX(un));
24323 		un->un_resvd_status |= SD_FAILFAST;
24324 		mutex_exit(SD_MUTEX(un));
24325 		/*
24326 		 * If mh_time is INT_MAX, then this ioctl is being used for
24327 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
24328 		 */
24329 		if (mh_time != INT_MAX) {
24330 			rval = sd_check_mhd(dev, mh_time);
24331 		}
24332 	} else {
24333 		(void) sd_check_mhd(dev, 0);
24334 		mutex_enter(SD_MUTEX(un));
24335 		un->un_resvd_status &= ~SD_FAILFAST;
24336 		mutex_exit(SD_MUTEX(un));
24337 	}
24338 	return (rval);
24339 }
24340 
24341 
24342 /*
24343  *    Function: sd_mhdioc_takeown
24344  *
24345  * Description: This routine is the driver entry point for handling ioctl
24346  *		requests to forcefully acquire exclusive access rights to the
24347  *		multihost disk (MHIOCTKOWN).
24348  *
24349  *   Arguments: dev	- the device number
24350  *		arg	- user provided structure specifying the delay
24351  *			  parameters in milliseconds
24352  *		flag	- this argument is a pass through to ddi_copyxxx()
24353  *			  directly from the mode argument of ioctl().
24354  *
24355  * Return Code: 0
24356  *		EFAULT
24357  *		ENXIO
24358  */
24359 
24360 static int
24361 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
24362 {
24363 	struct sd_lun		*un = NULL;
24364 	struct mhioctkown	*tkown = NULL;
24365 	int			rval = 0;
24366 
24367 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24368 		return (ENXIO);
24369 	}
24370 
24371 	if (arg != NULL) {
24372 		tkown = (struct mhioctkown *)
24373 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
24374 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
24375 		if (rval != 0) {
24376 			rval = EFAULT;
24377 			goto error;
24378 		}
24379 	}
24380 
24381 	rval = sd_take_ownership(dev, tkown);
24382 	mutex_enter(SD_MUTEX(un));
24383 	if (rval == 0) {
24384 		un->un_resvd_status |= SD_RESERVE;
24385 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
24386 			sd_reinstate_resv_delay =
24387 			    tkown->reinstate_resv_delay * 1000;
24388 		} else {
24389 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
24390 		}
24391 		/*
24392 		 * Give the scsi_watch routine interval set by
24393 		 * the MHIOCENFAILFAST ioctl precedence here.
24394 		 */
24395 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
24396 			mutex_exit(SD_MUTEX(un));
24397 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
24398 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
24399 			    "sd_mhdioc_takeown : %d\n",
24400 			    sd_reinstate_resv_delay);
24401 		} else {
24402 			mutex_exit(SD_MUTEX(un));
24403 		}
24404 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
24405 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24406 	} else {
24407 		un->un_resvd_status &= ~SD_RESERVE;
24408 		mutex_exit(SD_MUTEX(un));
24409 	}
24410 
24411 error:
24412 	if (tkown != NULL) {
24413 		kmem_free(tkown, sizeof (struct mhioctkown));
24414 	}
24415 	return (rval);
24416 }
24417 
24418 
24419 /*
24420  *    Function: sd_mhdioc_release
24421  *
24422  * Description: This routine is the driver entry point for handling ioctl
24423  *		requests to release exclusive access rights to the multihost
24424  *		disk (MHIOCRELEASE).
24425  *
24426  *   Arguments: dev	- the device number
24427  *
24428  * Return Code: 0
24429  *		ENXIO
24430  */
24431 
24432 static int
24433 sd_mhdioc_release(dev_t dev)
24434 {
24435 	struct sd_lun		*un = NULL;
24436 	timeout_id_t		resvd_timeid_save;
24437 	int			resvd_status_save;
24438 	int			rval = 0;
24439 
24440 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24441 		return (ENXIO);
24442 	}
24443 
24444 	mutex_enter(SD_MUTEX(un));
24445 	resvd_status_save = un->un_resvd_status;
24446 	un->un_resvd_status &=
24447 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
24448 	if (un->un_resvd_timeid) {
24449 		resvd_timeid_save = un->un_resvd_timeid;
24450 		un->un_resvd_timeid = NULL;
24451 		mutex_exit(SD_MUTEX(un));
24452 		(void) untimeout(resvd_timeid_save);
24453 	} else {
24454 		mutex_exit(SD_MUTEX(un));
24455 	}
24456 
24457 	/*
24458 	 * destroy any pending timeout thread that may be attempting to
24459 	 * reinstate reservation on this device.
24460 	 */
24461 	sd_rmv_resv_reclaim_req(dev);
24462 
24463 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
24464 		mutex_enter(SD_MUTEX(un));
24465 		if ((un->un_mhd_token) &&
24466 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
24467 			mutex_exit(SD_MUTEX(un));
24468 			(void) sd_check_mhd(dev, 0);
24469 		} else {
24470 			mutex_exit(SD_MUTEX(un));
24471 		}
24472 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
24473 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24474 	} else {
24475 		/*
24476 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
24477 		 */
24478 		mutex_enter(SD_MUTEX(un));
24479 		un->un_resvd_status = resvd_status_save;
24480 		mutex_exit(SD_MUTEX(un));
24481 	}
24482 	return (rval);
24483 }
24484 
24485 
24486 /*
24487  *    Function: sd_mhdioc_register_devid
24488  *
24489  * Description: This routine is the driver entry point for handling ioctl
24490  *		requests to register the device id (MHIOCREREGISTERDEVID).
24491  *
24492  *		Note: The implementation for this ioctl has been updated to
24493  *		be consistent with the original PSARC case (1999/357)
24494  *		(4375899, 4241671, 4220005)
24495  *
24496  *   Arguments: dev	- the device number
24497  *
24498  * Return Code: 0
24499  *		ENXIO
24500  */
24501 
24502 static int
24503 sd_mhdioc_register_devid(dev_t dev)
24504 {
24505 	struct sd_lun	*un = NULL;
24506 	int		rval = 0;
24507 	sd_ssc_t	*ssc;
24508 
24509 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24510 		return (ENXIO);
24511 	}
24512 
24513 	ASSERT(!mutex_owned(SD_MUTEX(un)));
24514 
24515 	mutex_enter(SD_MUTEX(un));
24516 
24517 	/* If a devid already exists, de-register it */
24518 	if (un->un_devid != NULL) {
24519 		ddi_devid_unregister(SD_DEVINFO(un));
24520 		/*
24521 		 * After unregister devid, needs to free devid memory
24522 		 */
24523 		ddi_devid_free(un->un_devid);
24524 		un->un_devid = NULL;
24525 	}
24526 
24527 	/* Check for reservation conflict */
24528 	mutex_exit(SD_MUTEX(un));
24529 	ssc = sd_ssc_init(un);
24530 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
24531 	mutex_enter(SD_MUTEX(un));
24532 
24533 	switch (rval) {
24534 	case 0:
24535 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
24536 		break;
24537 	case EACCES:
24538 		break;
24539 	default:
24540 		rval = EIO;
24541 	}
24542 
24543 	mutex_exit(SD_MUTEX(un));
24544 	if (rval != 0) {
24545 		if (rval == EIO)
24546 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24547 		else
24548 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24549 	}
24550 	sd_ssc_fini(ssc);
24551 	return (rval);
24552 }
24553 
24554 
24555 /*
24556  *    Function: sd_mhdioc_inkeys
24557  *
24558  * Description: This routine is the driver entry point for handling ioctl
24559  *		requests to issue the SCSI-3 Persistent In Read Keys command
24560  *		to the device (MHIOCGRP_INKEYS).
24561  *
24562  *   Arguments: dev	- the device number
24563  *		arg	- user provided in_keys structure
24564  *		flag	- this argument is a pass through to ddi_copyxxx()
24565  *			  directly from the mode argument of ioctl().
24566  *
24567  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
24568  *		ENXIO
24569  *		EFAULT
24570  */
24571 
24572 static int
24573 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
24574 {
24575 	struct sd_lun		*un;
24576 	mhioc_inkeys_t		inkeys;
24577 	int			rval = 0;
24578 
24579 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24580 		return (ENXIO);
24581 	}
24582 
24583 #ifdef _MULTI_DATAMODEL
24584 	switch (ddi_model_convert_from(flag & FMODELS)) {
24585 	case DDI_MODEL_ILP32: {
24586 		struct mhioc_inkeys32	inkeys32;
24587 
24588 		if (ddi_copyin(arg, &inkeys32,
24589 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
24590 			return (EFAULT);
24591 		}
24592 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
24593 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24594 		    &inkeys, flag)) != 0) {
24595 			return (rval);
24596 		}
24597 		inkeys32.generation = inkeys.generation;
24598 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
24599 		    flag) != 0) {
24600 			return (EFAULT);
24601 		}
24602 		break;
24603 	}
24604 	case DDI_MODEL_NONE:
24605 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
24606 		    flag) != 0) {
24607 			return (EFAULT);
24608 		}
24609 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24610 		    &inkeys, flag)) != 0) {
24611 			return (rval);
24612 		}
24613 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
24614 		    flag) != 0) {
24615 			return (EFAULT);
24616 		}
24617 		break;
24618 	}
24619 
24620 #else /* ! _MULTI_DATAMODEL */
24621 
24622 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
24623 		return (EFAULT);
24624 	}
24625 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
24626 	if (rval != 0) {
24627 		return (rval);
24628 	}
24629 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
24630 		return (EFAULT);
24631 	}
24632 
24633 #endif /* _MULTI_DATAMODEL */
24634 
24635 	return (rval);
24636 }
24637 
24638 
24639 /*
24640  *    Function: sd_mhdioc_inresv
24641  *
24642  * Description: This routine is the driver entry point for handling ioctl
24643  *		requests to issue the SCSI-3 Persistent In Read Reservations
24644  *		command to the device (MHIOCGRP_INKEYS).
24645  *
24646  *   Arguments: dev	- the device number
24647  *		arg	- user provided in_resv structure
24648  *		flag	- this argument is a pass through to ddi_copyxxx()
24649  *			  directly from the mode argument of ioctl().
24650  *
24651  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
24652  *		ENXIO
24653  *		EFAULT
24654  */
24655 
24656 static int
24657 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
24658 {
24659 	struct sd_lun		*un;
24660 	mhioc_inresvs_t		inresvs;
24661 	int			rval = 0;
24662 
24663 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24664 		return (ENXIO);
24665 	}
24666 
24667 #ifdef _MULTI_DATAMODEL
24668 
24669 	switch (ddi_model_convert_from(flag & FMODELS)) {
24670 	case DDI_MODEL_ILP32: {
24671 		struct mhioc_inresvs32	inresvs32;
24672 
24673 		if (ddi_copyin(arg, &inresvs32,
24674 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24675 			return (EFAULT);
24676 		}
24677 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
24678 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24679 		    &inresvs, flag)) != 0) {
24680 			return (rval);
24681 		}
24682 		inresvs32.generation = inresvs.generation;
24683 		if (ddi_copyout(&inresvs32, arg,
24684 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24685 			return (EFAULT);
24686 		}
24687 		break;
24688 	}
24689 	case DDI_MODEL_NONE:
24690 		if (ddi_copyin(arg, &inresvs,
24691 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24692 			return (EFAULT);
24693 		}
24694 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24695 		    &inresvs, flag)) != 0) {
24696 			return (rval);
24697 		}
24698 		if (ddi_copyout(&inresvs, arg,
24699 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24700 			return (EFAULT);
24701 		}
24702 		break;
24703 	}
24704 
24705 #else /* ! _MULTI_DATAMODEL */
24706 
24707 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
24708 		return (EFAULT);
24709 	}
24710 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
24711 	if (rval != 0) {
24712 		return (rval);
24713 	}
24714 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
24715 		return (EFAULT);
24716 	}
24717 
24718 #endif /* ! _MULTI_DATAMODEL */
24719 
24720 	return (rval);
24721 }
24722 
24723 
24724 /*
24725  * The following routines support the clustering functionality described below
24726  * and implement lost reservation reclaim functionality.
24727  *
24728  * Clustering
24729  * ----------
24730  * The clustering code uses two different, independent forms of SCSI
24731  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
24732  * Persistent Group Reservations. For any particular disk, it will use either
24733  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
24734  *
24735  * SCSI-2
24736  * The cluster software takes ownership of a multi-hosted disk by issuing the
24737  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
24738  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
24739  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
24740  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
24741  * driver. The meaning of failfast is that if the driver (on this host) ever
24742  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
24743  * it should immediately panic the host. The motivation for this ioctl is that
24744  * if this host does encounter reservation conflict, the underlying cause is
24745  * that some other host of the cluster has decided that this host is no longer
24746  * in the cluster and has seized control of the disks for itself. Since this
24747  * host is no longer in the cluster, it ought to panic itself. The
24748  * MHIOCENFAILFAST ioctl does two things:
24749  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
24750  *      error to panic the host
24751  *      (b) it sets up a periodic timer to test whether this host still has
24752  *      "access" (in that no other host has reserved the device):  if the
24753  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
24754  *      purpose of that periodic timer is to handle scenarios where the host is
24755  *      otherwise temporarily quiescent, temporarily doing no real i/o.
24756  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
24757  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
24758  * the device itself.
24759  *
24760  * SCSI-3 PGR
24761  * A direct semantic implementation of the SCSI-3 Persistent Reservation
24762  * facility is supported through the shared multihost disk ioctls
24763  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
24764  * MHIOCGRP_PREEMPTANDABORT, MHIOCGRP_CLEAR)
24765  *
24766  * Reservation Reclaim:
24767  * --------------------
24768  * To support the lost reservation reclaim operations this driver creates a
24769  * single thread to handle reinstating reservations on all devices that have
24770  * lost reservations sd_resv_reclaim_requests are logged for all devices that
24771  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
24772  * and the reservation reclaim thread loops through the requests to regain the
24773  * lost reservations.
24774  */
24775 
24776 /*
24777  *    Function: sd_check_mhd()
24778  *
24779  * Description: This function sets up and submits a scsi watch request or
24780  *		terminates an existing watch request. This routine is used in
24781  *		support of reservation reclaim.
24782  *
24783  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
24784  *			 among multiple watches that share the callback function
24785  *		interval - the number of microseconds specifying the watch
24786  *			   interval for issuing TEST UNIT READY commands. If
24787  *			   set to 0 the watch should be terminated. If the
24788  *			   interval is set to 0 and if the device is required
24789  *			   to hold reservation while disabling failfast, the
24790  *			   watch is restarted with an interval of
24791  *			   reinstate_resv_delay.
24792  *
24793  * Return Code: 0	   - Successful submit/terminate of scsi watch request
24794  *		ENXIO      - Indicates an invalid device was specified
24795  *		EAGAIN     - Unable to submit the scsi watch request
24796  */
24797 
24798 static int
24799 sd_check_mhd(dev_t dev, int interval)
24800 {
24801 	struct sd_lun	*un;
24802 	opaque_t	token;
24803 
24804 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24805 		return (ENXIO);
24806 	}
24807 
24808 	/* is this a watch termination request? */
24809 	if (interval == 0) {
24810 		mutex_enter(SD_MUTEX(un));
24811 		/* if there is an existing watch task then terminate it */
24812 		if (un->un_mhd_token) {
24813 			token = un->un_mhd_token;
24814 			un->un_mhd_token = NULL;
24815 			mutex_exit(SD_MUTEX(un));
24816 			(void) scsi_watch_request_terminate(token,
24817 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
24818 			mutex_enter(SD_MUTEX(un));
24819 		} else {
24820 			mutex_exit(SD_MUTEX(un));
24821 			/*
24822 			 * Note: If we return here we don't check for the
24823 			 * failfast case. This is the original legacy
24824 			 * implementation but perhaps we should be checking
24825 			 * the failfast case.
24826 			 */
24827 			return (0);
24828 		}
24829 		/*
24830 		 * If the device is required to hold reservation while
24831 		 * disabling failfast, we need to restart the scsi_watch
24832 		 * routine with an interval of reinstate_resv_delay.
24833 		 */
24834 		if (un->un_resvd_status & SD_RESERVE) {
24835 			interval = sd_reinstate_resv_delay/1000;
24836 		} else {
24837 			/* no failfast so bail */
24838 			mutex_exit(SD_MUTEX(un));
24839 			return (0);
24840 		}
24841 		mutex_exit(SD_MUTEX(un));
24842 	}
24843 
24844 	/*
24845 	 * adjust minimum time interval to 1 second,
24846 	 * and convert from msecs to usecs
24847 	 */
24848 	if (interval > 0 && interval < 1000) {
24849 		interval = 1000;
24850 	}
24851 	interval *= 1000;
24852 
24853 	/*
24854 	 * submit the request to the scsi_watch service
24855 	 */
24856 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
24857 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
24858 	if (token == NULL) {
24859 		return (EAGAIN);
24860 	}
24861 
24862 	/*
24863 	 * save token for termination later on
24864 	 */
24865 	mutex_enter(SD_MUTEX(un));
24866 	un->un_mhd_token = token;
24867 	mutex_exit(SD_MUTEX(un));
24868 	return (0);
24869 }
24870 
24871 
24872 /*
24873  *    Function: sd_mhd_watch_cb()
24874  *
24875  * Description: This function is the call back function used by the scsi watch
24876  *		facility. The scsi watch facility sends the "Test Unit Ready"
24877  *		and processes the status. If applicable (i.e. a "Unit Attention"
24878  *		status and automatic "Request Sense" not used) the scsi watch
24879  *		facility will send a "Request Sense" and retrieve the sense data
24880  *		to be passed to this callback function. In either case the
24881  *		automatic "Request Sense" or the facility submitting one, this
24882  *		callback is passed the status and sense data.
24883  *
24884  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24885  *			among multiple watches that share this callback function
24886  *		resultp - scsi watch facility result packet containing scsi
24887  *			  packet, status byte and sense data
24888  *
24889  * Return Code: 0 - continue the watch task
24890  *		non-zero - terminate the watch task
24891  */
24892 
24893 static int
24894 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
24895 {
24896 	struct sd_lun			*un;
24897 	struct scsi_status		*statusp;
24898 	uint8_t				*sensep;
24899 	struct scsi_pkt			*pkt;
24900 	uchar_t				actual_sense_length;
24901 	dev_t  				dev = (dev_t)arg;
24902 
24903 	ASSERT(resultp != NULL);
24904 	statusp			= resultp->statusp;
24905 	sensep			= (uint8_t *)resultp->sensep;
24906 	pkt			= resultp->pkt;
24907 	actual_sense_length	= resultp->actual_sense_length;
24908 
24909 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24910 		return (ENXIO);
24911 	}
24912 
24913 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
24914 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
24915 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
24916 
24917 	/* Begin processing of the status and/or sense data */
24918 	if (pkt->pkt_reason != CMD_CMPLT) {
24919 		/* Handle the incomplete packet */
24920 		sd_mhd_watch_incomplete(un, pkt);
24921 		return (0);
24922 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
24923 		if (*((unsigned char *)statusp)
24924 		    == STATUS_RESERVATION_CONFLICT) {
24925 			/*
24926 			 * Handle a reservation conflict by panicking if
24927 			 * configured for failfast or by logging the conflict
24928 			 * and updating the reservation status
24929 			 */
24930 			mutex_enter(SD_MUTEX(un));
24931 			if ((un->un_resvd_status & SD_FAILFAST) &&
24932 			    (sd_failfast_enable)) {
24933 				sd_panic_for_res_conflict(un);
24934 				/*NOTREACHED*/
24935 			}
24936 			SD_INFO(SD_LOG_IOCTL_MHD, un,
24937 			    "sd_mhd_watch_cb: Reservation Conflict\n");
24938 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
24939 			mutex_exit(SD_MUTEX(un));
24940 		}
24941 	}
24942 
24943 	if (sensep != NULL) {
24944 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
24945 			mutex_enter(SD_MUTEX(un));
24946 			if ((scsi_sense_asc(sensep) ==
24947 			    SD_SCSI_RESET_SENSE_CODE) &&
24948 			    (un->un_resvd_status & SD_RESERVE)) {
24949 				/*
24950 				 * The additional sense code indicates a power
24951 				 * on or bus device reset has occurred; update
24952 				 * the reservation status.
24953 				 */
24954 				un->un_resvd_status |=
24955 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
24956 				SD_INFO(SD_LOG_IOCTL_MHD, un,
24957 				    "sd_mhd_watch_cb: Lost Reservation\n");
24958 			}
24959 		} else {
24960 			return (0);
24961 		}
24962 	} else {
24963 		mutex_enter(SD_MUTEX(un));
24964 	}
24965 
24966 	if ((un->un_resvd_status & SD_RESERVE) &&
24967 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
24968 		if (un->un_resvd_status & SD_WANT_RESERVE) {
24969 			/*
24970 			 * A reset occurred in between the last probe and this
24971 			 * one so if a timeout is pending cancel it.
24972 			 */
24973 			if (un->un_resvd_timeid) {
24974 				timeout_id_t temp_id = un->un_resvd_timeid;
24975 				un->un_resvd_timeid = NULL;
24976 				mutex_exit(SD_MUTEX(un));
24977 				(void) untimeout(temp_id);
24978 				mutex_enter(SD_MUTEX(un));
24979 			}
24980 			un->un_resvd_status &= ~SD_WANT_RESERVE;
24981 		}
24982 		if (un->un_resvd_timeid == 0) {
24983 			/* Schedule a timeout to handle the lost reservation */
24984 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
24985 			    (void *)dev,
24986 			    drv_usectohz(sd_reinstate_resv_delay));
24987 		}
24988 	}
24989 	mutex_exit(SD_MUTEX(un));
24990 	return (0);
24991 }
24992 
24993 
24994 /*
24995  *    Function: sd_mhd_watch_incomplete()
24996  *
24997  * Description: This function is used to find out why a scsi pkt sent by the
24998  *		scsi watch facility was not completed. Under some scenarios this
24999  *		routine will return. Otherwise it will send a bus reset to see
25000  *		if the drive is still online.
25001  *
25002  *   Arguments: un  - driver soft state (unit) structure
25003  *		pkt - incomplete scsi pkt
25004  */
25005 
25006 static void
25007 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
25008 {
25009 	int	be_chatty;
25010 	int	perr;
25011 
25012 	ASSERT(pkt != NULL);
25013 	ASSERT(un != NULL);
25014 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
25015 	perr		= (pkt->pkt_statistics & STAT_PERR);
25016 
25017 	mutex_enter(SD_MUTEX(un));
25018 	if (un->un_state == SD_STATE_DUMPING) {
25019 		mutex_exit(SD_MUTEX(un));
25020 		return;
25021 	}
25022 
25023 	switch (pkt->pkt_reason) {
25024 	case CMD_UNX_BUS_FREE:
25025 		/*
25026 		 * If we had a parity error that caused the target to drop BSY*,
25027 		 * don't be chatty about it.
25028 		 */
25029 		if (perr && be_chatty) {
25030 			be_chatty = 0;
25031 		}
25032 		break;
25033 	case CMD_TAG_REJECT:
25034 		/*
25035 		 * The SCSI-2 spec states that a tag reject will be sent by the
25036 		 * target if tagged queuing is not supported. A tag reject may
25037 		 * also be sent during certain initialization periods or to
25038 		 * control internal resources. For the latter case the target
25039 		 * may also return Queue Full.
25040 		 *
25041 		 * If this driver receives a tag reject from a target that is
25042 		 * going through an init period or controlling internal
25043 		 * resources tagged queuing will be disabled. This is a less
25044 		 * than optimal behavior but the driver is unable to determine
25045 		 * the target state and assumes tagged queueing is not supported
25046 		 */
25047 		pkt->pkt_flags = 0;
25048 		un->un_tagflags = 0;
25049 
25050 		if (un->un_f_opt_queueing == TRUE) {
25051 			un->un_throttle = min(un->un_throttle, 3);
25052 		} else {
25053 			un->un_throttle = 1;
25054 		}
25055 		mutex_exit(SD_MUTEX(un));
25056 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
25057 		mutex_enter(SD_MUTEX(un));
25058 		break;
25059 	case CMD_INCOMPLETE:
25060 		/*
25061 		 * The transport stopped with an abnormal state, fallthrough and
25062 		 * reset the target and/or bus unless selection did not complete
25063 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
25064 		 * go through a target/bus reset
25065 		 */
25066 		if (pkt->pkt_state == STATE_GOT_BUS) {
25067 			break;
25068 		}
25069 		/*FALLTHROUGH*/
25070 
25071 	case CMD_TIMEOUT:
25072 	default:
25073 		/*
25074 		 * The lun may still be running the command, so a lun reset
25075 		 * should be attempted. If the lun reset fails or cannot be
25076 		 * issued, than try a target reset. Lastly try a bus reset.
25077 		 */
25078 		if ((pkt->pkt_statistics &
25079 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
25080 			int reset_retval = 0;
25081 			mutex_exit(SD_MUTEX(un));
25082 			if (un->un_f_allow_bus_device_reset == TRUE) {
25083 				if (un->un_f_lun_reset_enabled == TRUE) {
25084 					reset_retval =
25085 					    scsi_reset(SD_ADDRESS(un),
25086 					    RESET_LUN);
25087 				}
25088 				if (reset_retval == 0) {
25089 					reset_retval =
25090 					    scsi_reset(SD_ADDRESS(un),
25091 					    RESET_TARGET);
25092 				}
25093 			}
25094 			if (reset_retval == 0) {
25095 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
25096 			}
25097 			mutex_enter(SD_MUTEX(un));
25098 		}
25099 		break;
25100 	}
25101 
25102 	/* A device/bus reset has occurred; update the reservation status. */
25103 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
25104 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
25105 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25106 			un->un_resvd_status |=
25107 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25108 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25109 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
25110 		}
25111 	}
25112 
25113 	/*
25114 	 * The disk has been turned off; Update the device state.
25115 	 *
25116 	 * Note: Should we be offlining the disk here?
25117 	 */
25118 	if (pkt->pkt_state == STATE_GOT_BUS) {
25119 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
25120 		    "Disk not responding to selection\n");
25121 		if (un->un_state != SD_STATE_OFFLINE) {
25122 			New_state(un, SD_STATE_OFFLINE);
25123 		}
25124 	} else if (be_chatty) {
25125 		/*
25126 		 * suppress messages if they are all the same pkt reason;
25127 		 * with TQ, many (up to 256) are returned with the same
25128 		 * pkt_reason
25129 		 */
25130 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
25131 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25132 			    "sd_mhd_watch_incomplete: "
25133 			    "SCSI transport failed: reason '%s'\n",
25134 			    scsi_rname(pkt->pkt_reason));
25135 		}
25136 	}
25137 	un->un_last_pkt_reason = pkt->pkt_reason;
25138 	mutex_exit(SD_MUTEX(un));
25139 }
25140 
25141 
25142 /*
25143  *    Function: sd_sname()
25144  *
25145  * Description: This is a simple little routine to return a string containing
25146  *		a printable description of command status byte for use in
25147  *		logging.
25148  *
25149  *   Arguments: status - pointer to a status byte
25150  *
25151  * Return Code: char * - string containing status description.
25152  */
25153 
25154 static char *
25155 sd_sname(uchar_t status)
25156 {
25157 	switch (status & STATUS_MASK) {
25158 	case STATUS_GOOD:
25159 		return ("good status");
25160 	case STATUS_CHECK:
25161 		return ("check condition");
25162 	case STATUS_MET:
25163 		return ("condition met");
25164 	case STATUS_BUSY:
25165 		return ("busy");
25166 	case STATUS_INTERMEDIATE:
25167 		return ("intermediate");
25168 	case STATUS_INTERMEDIATE_MET:
25169 		return ("intermediate - condition met");
25170 	case STATUS_RESERVATION_CONFLICT:
25171 		return ("reservation_conflict");
25172 	case STATUS_TERMINATED:
25173 		return ("command terminated");
25174 	case STATUS_QFULL:
25175 		return ("queue full");
25176 	default:
25177 		return ("<unknown status>");
25178 	}
25179 }
25180 
25181 
25182 /*
25183  *    Function: sd_mhd_resvd_recover()
25184  *
25185  * Description: This function adds a reservation entry to the
25186  *		sd_resv_reclaim_request list and signals the reservation
25187  *		reclaim thread that there is work pending. If the reservation
25188  *		reclaim thread has not been previously created this function
25189  *		will kick it off.
25190  *
25191  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25192  *			among multiple watches that share this callback function
25193  *
25194  *     Context: This routine is called by timeout() and is run in interrupt
25195  *		context. It must not sleep or call other functions which may
25196  *		sleep.
25197  */
25198 
25199 static void
25200 sd_mhd_resvd_recover(void *arg)
25201 {
25202 	dev_t			dev = (dev_t)arg;
25203 	struct sd_lun		*un;
25204 	struct sd_thr_request	*sd_treq = NULL;
25205 	struct sd_thr_request	*sd_cur = NULL;
25206 	struct sd_thr_request	*sd_prev = NULL;
25207 	int			already_there = 0;
25208 
25209 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25210 		return;
25211 	}
25212 
25213 	mutex_enter(SD_MUTEX(un));
25214 	un->un_resvd_timeid = NULL;
25215 	if (un->un_resvd_status & SD_WANT_RESERVE) {
25216 		/*
25217 		 * There was a reset so don't issue the reserve, allow the
25218 		 * sd_mhd_watch_cb callback function to notice this and
25219 		 * reschedule the timeout for reservation.
25220 		 */
25221 		mutex_exit(SD_MUTEX(un));
25222 		return;
25223 	}
25224 	mutex_exit(SD_MUTEX(un));
25225 
25226 	/*
25227 	 * Add this device to the sd_resv_reclaim_request list and the
25228 	 * sd_resv_reclaim_thread should take care of the rest.
25229 	 *
25230 	 * Note: We can't sleep in this context so if the memory allocation
25231 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
25232 	 * reschedule the timeout for reservation.  (4378460)
25233 	 */
25234 	sd_treq = (struct sd_thr_request *)
25235 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
25236 	if (sd_treq == NULL) {
25237 		return;
25238 	}
25239 
25240 	sd_treq->sd_thr_req_next = NULL;
25241 	sd_treq->dev = dev;
25242 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25243 	if (sd_tr.srq_thr_req_head == NULL) {
25244 		sd_tr.srq_thr_req_head = sd_treq;
25245 	} else {
25246 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
25247 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
25248 			if (sd_cur->dev == dev) {
25249 				/*
25250 				 * already in Queue so don't log
25251 				 * another request for the device
25252 				 */
25253 				already_there = 1;
25254 				break;
25255 			}
25256 			sd_prev = sd_cur;
25257 		}
25258 		if (!already_there) {
25259 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
25260 			    "logging request for %lx\n", dev);
25261 			sd_prev->sd_thr_req_next = sd_treq;
25262 		} else {
25263 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
25264 		}
25265 	}
25266 
25267 	/*
25268 	 * Create a kernel thread to do the reservation reclaim and free up this
25269 	 * thread. We cannot block this thread while we go away to do the
25270 	 * reservation reclaim
25271 	 */
25272 	if (sd_tr.srq_resv_reclaim_thread == NULL)
25273 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
25274 		    sd_resv_reclaim_thread, NULL,
25275 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
25276 
25277 	/* Tell the reservation reclaim thread that it has work to do */
25278 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
25279 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25280 }
25281 
25282 /*
25283  *    Function: sd_resv_reclaim_thread()
25284  *
25285  * Description: This function implements the reservation reclaim operations
25286  *
25287  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
25288  *		      among multiple watches that share this callback function
25289  */
25290 
25291 static void
25292 sd_resv_reclaim_thread()
25293 {
25294 	struct sd_lun		*un;
25295 	struct sd_thr_request	*sd_mhreq;
25296 
25297 	/* Wait for work */
25298 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25299 	if (sd_tr.srq_thr_req_head == NULL) {
25300 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
25301 		    &sd_tr.srq_resv_reclaim_mutex);
25302 	}
25303 
25304 	/* Loop while we have work */
25305 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
25306 		un = ddi_get_soft_state(sd_state,
25307 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
25308 		if (un == NULL) {
25309 			/*
25310 			 * softstate structure is NULL so just
25311 			 * dequeue the request and continue
25312 			 */
25313 			sd_tr.srq_thr_req_head =
25314 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25315 			kmem_free(sd_tr.srq_thr_cur_req,
25316 			    sizeof (struct sd_thr_request));
25317 			continue;
25318 		}
25319 
25320 		/* dequeue the request */
25321 		sd_mhreq = sd_tr.srq_thr_cur_req;
25322 		sd_tr.srq_thr_req_head =
25323 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25324 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25325 
25326 		/*
25327 		 * Reclaim reservation only if SD_RESERVE is still set. There
25328 		 * may have been a call to MHIOCRELEASE before we got here.
25329 		 */
25330 		mutex_enter(SD_MUTEX(un));
25331 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25332 			/*
25333 			 * Note: The SD_LOST_RESERVE flag is cleared before
25334 			 * reclaiming the reservation. If this is done after the
25335 			 * call to sd_reserve_release a reservation loss in the
25336 			 * window between pkt completion of reserve cmd and
25337 			 * mutex_enter below may not be recognized
25338 			 */
25339 			un->un_resvd_status &= ~SD_LOST_RESERVE;
25340 			mutex_exit(SD_MUTEX(un));
25341 
25342 			if (sd_reserve_release(sd_mhreq->dev,
25343 			    SD_RESERVE) == 0) {
25344 				mutex_enter(SD_MUTEX(un));
25345 				un->un_resvd_status |= SD_RESERVE;
25346 				mutex_exit(SD_MUTEX(un));
25347 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25348 				    "sd_resv_reclaim_thread: "
25349 				    "Reservation Recovered\n");
25350 			} else {
25351 				mutex_enter(SD_MUTEX(un));
25352 				un->un_resvd_status |= SD_LOST_RESERVE;
25353 				mutex_exit(SD_MUTEX(un));
25354 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25355 				    "sd_resv_reclaim_thread: Failed "
25356 				    "Reservation Recovery\n");
25357 			}
25358 		} else {
25359 			mutex_exit(SD_MUTEX(un));
25360 		}
25361 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25362 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
25363 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25364 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
25365 		/*
25366 		 * wakeup the destroy thread if anyone is waiting on
25367 		 * us to complete.
25368 		 */
25369 		cv_signal(&sd_tr.srq_inprocess_cv);
25370 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
25371 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
25372 	}
25373 
25374 	/*
25375 	 * cleanup the sd_tr structure now that this thread will not exist
25376 	 */
25377 	ASSERT(sd_tr.srq_thr_req_head == NULL);
25378 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
25379 	sd_tr.srq_resv_reclaim_thread = NULL;
25380 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25381 	thread_exit();
25382 }
25383 
25384 
25385 /*
25386  *    Function: sd_rmv_resv_reclaim_req()
25387  *
25388  * Description: This function removes any pending reservation reclaim requests
25389  *		for the specified device.
25390  *
25391  *   Arguments: dev - the device 'dev_t'
25392  */
25393 
25394 static void
25395 sd_rmv_resv_reclaim_req(dev_t dev)
25396 {
25397 	struct sd_thr_request *sd_mhreq;
25398 	struct sd_thr_request *sd_prev;
25399 
25400 	/* Remove a reservation reclaim request from the list */
25401 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25402 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
25403 		/*
25404 		 * We are attempting to reinstate reservation for
25405 		 * this device. We wait for sd_reserve_release()
25406 		 * to return before we return.
25407 		 */
25408 		cv_wait(&sd_tr.srq_inprocess_cv,
25409 		    &sd_tr.srq_resv_reclaim_mutex);
25410 	} else {
25411 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
25412 		if (sd_mhreq && sd_mhreq->dev == dev) {
25413 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
25414 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25415 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25416 			return;
25417 		}
25418 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
25419 			if (sd_mhreq && sd_mhreq->dev == dev) {
25420 				break;
25421 			}
25422 			sd_prev = sd_mhreq;
25423 		}
25424 		if (sd_mhreq != NULL) {
25425 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
25426 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25427 		}
25428 	}
25429 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25430 }
25431 
25432 
25433 /*
25434  *    Function: sd_mhd_reset_notify_cb()
25435  *
25436  * Description: This is a call back function for scsi_reset_notify. This
25437  *		function updates the softstate reserved status and logs the
25438  *		reset. The driver scsi watch facility callback function
25439  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
25440  *		will reclaim the reservation.
25441  *
25442  *   Arguments: arg  - driver soft state (unit) structure
25443  */
25444 
25445 static void
25446 sd_mhd_reset_notify_cb(caddr_t arg)
25447 {
25448 	struct sd_lun *un = (struct sd_lun *)arg;
25449 
25450 	mutex_enter(SD_MUTEX(un));
25451 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25452 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
25453 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25454 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
25455 	}
25456 	mutex_exit(SD_MUTEX(un));
25457 }
25458 
25459 
25460 /*
25461  *    Function: sd_take_ownership()
25462  *
25463  * Description: This routine implements an algorithm to achieve a stable
25464  *		reservation on disks which don't implement priority reserve,
25465  *		and makes sure that other host lose re-reservation attempts.
25466  *		This algorithm contains of a loop that keeps issuing the RESERVE
25467  *		for some period of time (min_ownership_delay, default 6 seconds)
25468  *		During that loop, it looks to see if there has been a bus device
25469  *		reset or bus reset (both of which cause an existing reservation
25470  *		to be lost). If the reservation is lost issue RESERVE until a
25471  *		period of min_ownership_delay with no resets has gone by, or
25472  *		until max_ownership_delay has expired. This loop ensures that
25473  *		the host really did manage to reserve the device, in spite of
25474  *		resets. The looping for min_ownership_delay (default six
25475  *		seconds) is important to early generation clustering products,
25476  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
25477  *		MHIOCENFAILFAST periodic timer of two seconds. By having
25478  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
25479  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
25480  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
25481  *		have already noticed, via the MHIOCENFAILFAST polling, that it
25482  *		no longer "owns" the disk and will have panicked itself.  Thus,
25483  *		the host issuing the MHIOCTKOWN is assured (with timing
25484  *		dependencies) that by the time it actually starts to use the
25485  *		disk for real work, the old owner is no longer accessing it.
25486  *
25487  *		min_ownership_delay is the minimum amount of time for which the
25488  *		disk must be reserved continuously devoid of resets before the
25489  *		MHIOCTKOWN ioctl will return success.
25490  *
25491  *		max_ownership_delay indicates the amount of time by which the
25492  *		take ownership should succeed or timeout with an error.
25493  *
25494  *   Arguments: dev - the device 'dev_t'
25495  *		*p  - struct containing timing info.
25496  *
25497  * Return Code: 0 for success or error code
25498  */
25499 
25500 static int
25501 sd_take_ownership(dev_t dev, struct mhioctkown *p)
25502 {
25503 	struct sd_lun	*un;
25504 	int		rval;
25505 	int		err;
25506 	int		reservation_count   = 0;
25507 	int		min_ownership_delay =  6000000; /* in usec */
25508 	int		max_ownership_delay = 30000000; /* in usec */
25509 	clock_t		start_time;	/* starting time of this algorithm */
25510 	clock_t		end_time;	/* time limit for giving up */
25511 	clock_t		ownership_time;	/* time limit for stable ownership */
25512 	clock_t		current_time;
25513 	clock_t		previous_current_time;
25514 
25515 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25516 		return (ENXIO);
25517 	}
25518 
25519 	/*
25520 	 * Attempt a device reservation. A priority reservation is requested.
25521 	 */
25522 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
25523 	    != SD_SUCCESS) {
25524 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25525 		    "sd_take_ownership: return(1)=%d\n", rval);
25526 		return (rval);
25527 	}
25528 
25529 	/* Update the softstate reserved status to indicate the reservation */
25530 	mutex_enter(SD_MUTEX(un));
25531 	un->un_resvd_status |= SD_RESERVE;
25532 	un->un_resvd_status &=
25533 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
25534 	mutex_exit(SD_MUTEX(un));
25535 
25536 	if (p != NULL) {
25537 		if (p->min_ownership_delay != 0) {
25538 			min_ownership_delay = p->min_ownership_delay * 1000;
25539 		}
25540 		if (p->max_ownership_delay != 0) {
25541 			max_ownership_delay = p->max_ownership_delay * 1000;
25542 		}
25543 	}
25544 	SD_INFO(SD_LOG_IOCTL_MHD, un,
25545 	    "sd_take_ownership: min, max delays: %d, %d\n",
25546 	    min_ownership_delay, max_ownership_delay);
25547 
25548 	start_time = ddi_get_lbolt();
25549 	current_time	= start_time;
25550 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
25551 	end_time	= start_time + drv_usectohz(max_ownership_delay);
25552 
25553 	while (current_time - end_time < 0) {
25554 		delay(drv_usectohz(500000));
25555 
25556 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
25557 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
25558 				mutex_enter(SD_MUTEX(un));
25559 				rval = (un->un_resvd_status &
25560 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
25561 				mutex_exit(SD_MUTEX(un));
25562 				break;
25563 			}
25564 		}
25565 		previous_current_time = current_time;
25566 		current_time = ddi_get_lbolt();
25567 		mutex_enter(SD_MUTEX(un));
25568 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
25569 			ownership_time = ddi_get_lbolt() +
25570 			    drv_usectohz(min_ownership_delay);
25571 			reservation_count = 0;
25572 		} else {
25573 			reservation_count++;
25574 		}
25575 		un->un_resvd_status |= SD_RESERVE;
25576 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
25577 		mutex_exit(SD_MUTEX(un));
25578 
25579 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25580 		    "sd_take_ownership: ticks for loop iteration=%ld, "
25581 		    "reservation=%s\n", (current_time - previous_current_time),
25582 		    reservation_count ? "ok" : "reclaimed");
25583 
25584 		if (current_time - ownership_time >= 0 &&
25585 		    reservation_count >= 4) {
25586 			rval = 0; /* Achieved a stable ownership */
25587 			break;
25588 		}
25589 		if (current_time - end_time >= 0) {
25590 			rval = EACCES; /* No ownership in max possible time */
25591 			break;
25592 		}
25593 	}
25594 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25595 	    "sd_take_ownership: return(2)=%d\n", rval);
25596 	return (rval);
25597 }
25598 
25599 
25600 /*
25601  *    Function: sd_reserve_release()
25602  *
25603  * Description: This function builds and sends scsi RESERVE, RELEASE, and
25604  *		PRIORITY RESERVE commands based on a user specified command type
25605  *
25606  *   Arguments: dev - the device 'dev_t'
25607  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
25608  *		      SD_RESERVE, SD_RELEASE
25609  *
25610  * Return Code: 0 or Error Code
25611  */
25612 
25613 static int
25614 sd_reserve_release(dev_t dev, int cmd)
25615 {
25616 	struct uscsi_cmd	*com = NULL;
25617 	struct sd_lun		*un = NULL;
25618 	char			cdb[CDB_GROUP0];
25619 	int			rval;
25620 
25621 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
25622 	    (cmd == SD_PRIORITY_RESERVE));
25623 
25624 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25625 		return (ENXIO);
25626 	}
25627 
25628 	/* instantiate and initialize the command and cdb */
25629 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25630 	bzero(cdb, CDB_GROUP0);
25631 	com->uscsi_flags   = USCSI_SILENT;
25632 	com->uscsi_timeout = un->un_reserve_release_time;
25633 	com->uscsi_cdblen  = CDB_GROUP0;
25634 	com->uscsi_cdb	   = cdb;
25635 	if (cmd == SD_RELEASE) {
25636 		cdb[0] = SCMD_RELEASE;
25637 	} else {
25638 		cdb[0] = SCMD_RESERVE;
25639 	}
25640 
25641 	/* Send the command. */
25642 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25643 	    SD_PATH_STANDARD);
25644 
25645 	/*
25646 	 * "break" a reservation that is held by another host, by issuing a
25647 	 * reset if priority reserve is desired, and we could not get the
25648 	 * device.
25649 	 */
25650 	if ((cmd == SD_PRIORITY_RESERVE) &&
25651 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25652 		/*
25653 		 * First try to reset the LUN. If we cannot, then try a target
25654 		 * reset, followed by a bus reset if the target reset fails.
25655 		 */
25656 		int reset_retval = 0;
25657 		if (un->un_f_lun_reset_enabled == TRUE) {
25658 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
25659 		}
25660 		if (reset_retval == 0) {
25661 			/* The LUN reset either failed or was not issued */
25662 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
25663 		}
25664 		if ((reset_retval == 0) &&
25665 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
25666 			rval = EIO;
25667 			kmem_free(com, sizeof (*com));
25668 			return (rval);
25669 		}
25670 
25671 		bzero(com, sizeof (struct uscsi_cmd));
25672 		com->uscsi_flags   = USCSI_SILENT;
25673 		com->uscsi_cdb	   = cdb;
25674 		com->uscsi_cdblen  = CDB_GROUP0;
25675 		com->uscsi_timeout = 5;
25676 
25677 		/*
25678 		 * Reissue the last reserve command, this time without request
25679 		 * sense.  Assume that it is just a regular reserve command.
25680 		 */
25681 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25682 		    SD_PATH_STANDARD);
25683 	}
25684 
25685 	/* Return an error if still getting a reservation conflict. */
25686 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25687 		rval = EACCES;
25688 	}
25689 
25690 	kmem_free(com, sizeof (*com));
25691 	return (rval);
25692 }
25693 
25694 
25695 #define	SD_NDUMP_RETRIES	12
25696 /*
25697  *	System Crash Dump routine
25698  */
25699 
25700 static int
25701 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
25702 {
25703 	int		instance;
25704 	int		partition;
25705 	int		i;
25706 	int		err;
25707 	struct sd_lun	*un;
25708 	struct scsi_pkt *wr_pktp;
25709 	struct buf	*wr_bp;
25710 	struct buf	wr_buf;
25711 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
25712 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
25713 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
25714 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
25715 	size_t		io_start_offset;
25716 	int		doing_rmw = FALSE;
25717 	int		rval;
25718 	ssize_t		dma_resid;
25719 	daddr_t		oblkno;
25720 	diskaddr_t	nblks = 0;
25721 	diskaddr_t	start_block;
25722 
25723 	instance = SDUNIT(dev);
25724 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
25725 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
25726 		return (ENXIO);
25727 	}
25728 
25729 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
25730 
25731 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
25732 
25733 	partition = SDPART(dev);
25734 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
25735 
25736 	if (!(NOT_DEVBSIZE(un))) {
25737 		int secmask = 0;
25738 		int blknomask = 0;
25739 
25740 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
25741 		secmask = un->un_tgt_blocksize - 1;
25742 
25743 		if (blkno & blknomask) {
25744 			SD_TRACE(SD_LOG_DUMP, un,
25745 			    "sddump: dump start block not modulo %d\n",
25746 			    un->un_tgt_blocksize);
25747 			return (EINVAL);
25748 		}
25749 
25750 		if ((nblk * DEV_BSIZE) & secmask) {
25751 			SD_TRACE(SD_LOG_DUMP, un,
25752 			    "sddump: dump length not modulo %d\n",
25753 			    un->un_tgt_blocksize);
25754 			return (EINVAL);
25755 		}
25756 
25757 	}
25758 
25759 	/* Validate blocks to dump at against partition size. */
25760 
25761 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
25762 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
25763 
25764 	if (NOT_DEVBSIZE(un)) {
25765 		if ((blkno + nblk) > nblks) {
25766 			SD_TRACE(SD_LOG_DUMP, un,
25767 			    "sddump: dump range larger than partition: "
25768 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25769 			    blkno, nblk, nblks);
25770 			return (EINVAL);
25771 		}
25772 	} else {
25773 		if (((blkno / (un->un_tgt_blocksize / DEV_BSIZE)) +
25774 		    (nblk / (un->un_tgt_blocksize / DEV_BSIZE))) > nblks) {
25775 			SD_TRACE(SD_LOG_DUMP, un,
25776 			    "sddump: dump range larger than partition: "
25777 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25778 			    blkno, nblk, nblks);
25779 			return (EINVAL);
25780 		}
25781 	}
25782 
25783 	mutex_enter(&un->un_pm_mutex);
25784 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
25785 		struct scsi_pkt *start_pktp;
25786 
25787 		mutex_exit(&un->un_pm_mutex);
25788 
25789 		/*
25790 		 * use pm framework to power on HBA 1st
25791 		 */
25792 		(void) pm_raise_power(SD_DEVINFO(un), 0,
25793 		    SD_PM_STATE_ACTIVE(un));
25794 
25795 		/*
25796 		 * Dump no long uses sdpower to power on a device, it's
25797 		 * in-line here so it can be done in polled mode.
25798 		 */
25799 
25800 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
25801 
25802 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
25803 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
25804 
25805 		if (start_pktp == NULL) {
25806 			/* We were not given a SCSI packet, fail. */
25807 			return (EIO);
25808 		}
25809 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
25810 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
25811 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
25812 		start_pktp->pkt_flags = FLAG_NOINTR;
25813 
25814 		mutex_enter(SD_MUTEX(un));
25815 		SD_FILL_SCSI1_LUN(un, start_pktp);
25816 		mutex_exit(SD_MUTEX(un));
25817 		/*
25818 		 * Scsi_poll returns 0 (success) if the command completes and
25819 		 * the status block is STATUS_GOOD.
25820 		 */
25821 		if (sd_scsi_poll(un, start_pktp) != 0) {
25822 			scsi_destroy_pkt(start_pktp);
25823 			return (EIO);
25824 		}
25825 		scsi_destroy_pkt(start_pktp);
25826 		(void) sd_pm_state_change(un, SD_PM_STATE_ACTIVE(un),
25827 		    SD_PM_STATE_CHANGE);
25828 	} else {
25829 		mutex_exit(&un->un_pm_mutex);
25830 	}
25831 
25832 	mutex_enter(SD_MUTEX(un));
25833 	un->un_throttle = 0;
25834 
25835 	/*
25836 	 * The first time through, reset the specific target device.
25837 	 * However, when cpr calls sddump we know that sd is in a
25838 	 * a good state so no bus reset is required.
25839 	 * Clear sense data via Request Sense cmd.
25840 	 * In sddump we don't care about allow_bus_device_reset anymore
25841 	 */
25842 
25843 	if ((un->un_state != SD_STATE_SUSPENDED) &&
25844 	    (un->un_state != SD_STATE_DUMPING)) {
25845 
25846 		New_state(un, SD_STATE_DUMPING);
25847 
25848 		if (un->un_f_is_fibre == FALSE) {
25849 			mutex_exit(SD_MUTEX(un));
25850 			/*
25851 			 * Attempt a bus reset for parallel scsi.
25852 			 *
25853 			 * Note: A bus reset is required because on some host
25854 			 * systems (i.e. E420R) a bus device reset is
25855 			 * insufficient to reset the state of the target.
25856 			 *
25857 			 * Note: Don't issue the reset for fibre-channel,
25858 			 * because this tends to hang the bus (loop) for
25859 			 * too long while everyone is logging out and in
25860 			 * and the deadman timer for dumping will fire
25861 			 * before the dump is complete.
25862 			 */
25863 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
25864 				mutex_enter(SD_MUTEX(un));
25865 				Restore_state(un);
25866 				mutex_exit(SD_MUTEX(un));
25867 				return (EIO);
25868 			}
25869 
25870 			/* Delay to give the device some recovery time. */
25871 			drv_usecwait(10000);
25872 
25873 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
25874 				SD_INFO(SD_LOG_DUMP, un,
25875 				    "sddump: sd_send_polled_RQS failed\n");
25876 			}
25877 			mutex_enter(SD_MUTEX(un));
25878 		}
25879 	}
25880 
25881 	/*
25882 	 * Convert the partition-relative block number to a
25883 	 * disk physical block number.
25884 	 */
25885 	if (NOT_DEVBSIZE(un)) {
25886 		blkno += start_block;
25887 	} else {
25888 		blkno = blkno / (un->un_tgt_blocksize / DEV_BSIZE);
25889 		blkno += start_block;
25890 	}
25891 
25892 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
25893 
25894 
25895 	/*
25896 	 * Check if the device has a non-512 block size.
25897 	 */
25898 	wr_bp = NULL;
25899 	if (NOT_DEVBSIZE(un)) {
25900 		tgt_byte_offset = blkno * un->un_sys_blocksize;
25901 		tgt_byte_count = nblk * un->un_sys_blocksize;
25902 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
25903 		    (tgt_byte_count % un->un_tgt_blocksize)) {
25904 			doing_rmw = TRUE;
25905 			/*
25906 			 * Calculate the block number and number of block
25907 			 * in terms of the media block size.
25908 			 */
25909 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
25910 			tgt_nblk =
25911 			    ((tgt_byte_offset + tgt_byte_count +
25912 			    (un->un_tgt_blocksize - 1)) /
25913 			    un->un_tgt_blocksize) - tgt_blkno;
25914 
25915 			/*
25916 			 * Invoke the routine which is going to do read part
25917 			 * of read-modify-write.
25918 			 * Note that this routine returns a pointer to
25919 			 * a valid bp in wr_bp.
25920 			 */
25921 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
25922 			    &wr_bp);
25923 			if (err) {
25924 				mutex_exit(SD_MUTEX(un));
25925 				return (err);
25926 			}
25927 			/*
25928 			 * Offset is being calculated as -
25929 			 * (original block # * system block size) -
25930 			 * (new block # * target block size)
25931 			 */
25932 			io_start_offset =
25933 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
25934 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
25935 
25936 			ASSERT((io_start_offset >= 0) &&
25937 			    (io_start_offset < un->un_tgt_blocksize));
25938 			/*
25939 			 * Do the modify portion of read modify write.
25940 			 */
25941 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
25942 			    (size_t)nblk * un->un_sys_blocksize);
25943 		} else {
25944 			doing_rmw = FALSE;
25945 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
25946 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
25947 		}
25948 
25949 		/* Convert blkno and nblk to target blocks */
25950 		blkno = tgt_blkno;
25951 		nblk = tgt_nblk;
25952 	} else {
25953 		wr_bp = &wr_buf;
25954 		bzero(wr_bp, sizeof (struct buf));
25955 		wr_bp->b_flags		= B_BUSY;
25956 		wr_bp->b_un.b_addr	= addr;
25957 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
25958 		wr_bp->b_resid		= 0;
25959 	}
25960 
25961 	mutex_exit(SD_MUTEX(un));
25962 
25963 	/*
25964 	 * Obtain a SCSI packet for the write command.
25965 	 * It should be safe to call the allocator here without
25966 	 * worrying about being locked for DVMA mapping because
25967 	 * the address we're passed is already a DVMA mapping
25968 	 *
25969 	 * We are also not going to worry about semaphore ownership
25970 	 * in the dump buffer. Dumping is single threaded at present.
25971 	 */
25972 
25973 	wr_pktp = NULL;
25974 
25975 	dma_resid = wr_bp->b_bcount;
25976 	oblkno = blkno;
25977 
25978 	if (!(NOT_DEVBSIZE(un))) {
25979 		nblk = nblk / (un->un_tgt_blocksize / DEV_BSIZE);
25980 	}
25981 
25982 	while (dma_resid != 0) {
25983 
25984 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
25985 		wr_bp->b_flags &= ~B_ERROR;
25986 
25987 		if (un->un_partial_dma_supported == 1) {
25988 			blkno = oblkno +
25989 			    ((wr_bp->b_bcount - dma_resid) /
25990 			    un->un_tgt_blocksize);
25991 			nblk = dma_resid / un->un_tgt_blocksize;
25992 
25993 			if (wr_pktp) {
25994 				/*
25995 				 * Partial DMA transfers after initial transfer
25996 				 */
25997 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
25998 				    blkno, nblk);
25999 			} else {
26000 				/* Initial transfer */
26001 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26002 				    un->un_pkt_flags, NULL_FUNC, NULL,
26003 				    blkno, nblk);
26004 			}
26005 		} else {
26006 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26007 			    0, NULL_FUNC, NULL, blkno, nblk);
26008 		}
26009 
26010 		if (rval == 0) {
26011 			/* We were given a SCSI packet, continue. */
26012 			break;
26013 		}
26014 
26015 		if (i == 0) {
26016 			if (wr_bp->b_flags & B_ERROR) {
26017 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26018 				    "no resources for dumping; "
26019 				    "error code: 0x%x, retrying",
26020 				    geterror(wr_bp));
26021 			} else {
26022 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26023 				    "no resources for dumping; retrying");
26024 			}
26025 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
26026 			if (wr_bp->b_flags & B_ERROR) {
26027 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26028 				    "no resources for dumping; error code: "
26029 				    "0x%x, retrying\n", geterror(wr_bp));
26030 			}
26031 		} else {
26032 			if (wr_bp->b_flags & B_ERROR) {
26033 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26034 				    "no resources for dumping; "
26035 				    "error code: 0x%x, retries failed, "
26036 				    "giving up.\n", geterror(wr_bp));
26037 			} else {
26038 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26039 				    "no resources for dumping; "
26040 				    "retries failed, giving up.\n");
26041 			}
26042 			mutex_enter(SD_MUTEX(un));
26043 			Restore_state(un);
26044 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
26045 				mutex_exit(SD_MUTEX(un));
26046 				scsi_free_consistent_buf(wr_bp);
26047 			} else {
26048 				mutex_exit(SD_MUTEX(un));
26049 			}
26050 			return (EIO);
26051 		}
26052 		drv_usecwait(10000);
26053 	}
26054 
26055 	if (un->un_partial_dma_supported == 1) {
26056 		/*
26057 		 * save the resid from PARTIAL_DMA
26058 		 */
26059 		dma_resid = wr_pktp->pkt_resid;
26060 		if (dma_resid != 0)
26061 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
26062 		wr_pktp->pkt_resid = 0;
26063 	} else {
26064 		dma_resid = 0;
26065 	}
26066 
26067 	/* SunBug 1222170 */
26068 	wr_pktp->pkt_flags = FLAG_NOINTR;
26069 
26070 	err = EIO;
26071 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26072 
26073 		/*
26074 		 * Scsi_poll returns 0 (success) if the command completes and
26075 		 * the status block is STATUS_GOOD.  We should only check
26076 		 * errors if this condition is not true.  Even then we should
26077 		 * send our own request sense packet only if we have a check
26078 		 * condition and auto request sense has not been performed by
26079 		 * the hba.
26080 		 */
26081 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
26082 
26083 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
26084 		    (wr_pktp->pkt_resid == 0)) {
26085 			err = SD_SUCCESS;
26086 			break;
26087 		}
26088 
26089 		/*
26090 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
26091 		 */
26092 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
26093 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26094 			    "Error while dumping state...Device is gone\n");
26095 			break;
26096 		}
26097 
26098 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
26099 			SD_INFO(SD_LOG_DUMP, un,
26100 			    "sddump: write failed with CHECK, try # %d\n", i);
26101 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
26102 				(void) sd_send_polled_RQS(un);
26103 			}
26104 
26105 			continue;
26106 		}
26107 
26108 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
26109 			int reset_retval = 0;
26110 
26111 			SD_INFO(SD_LOG_DUMP, un,
26112 			    "sddump: write failed with BUSY, try # %d\n", i);
26113 
26114 			if (un->un_f_lun_reset_enabled == TRUE) {
26115 				reset_retval = scsi_reset(SD_ADDRESS(un),
26116 				    RESET_LUN);
26117 			}
26118 			if (reset_retval == 0) {
26119 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26120 			}
26121 			(void) sd_send_polled_RQS(un);
26122 
26123 		} else {
26124 			SD_INFO(SD_LOG_DUMP, un,
26125 			    "sddump: write failed with 0x%x, try # %d\n",
26126 			    SD_GET_PKT_STATUS(wr_pktp), i);
26127 			mutex_enter(SD_MUTEX(un));
26128 			sd_reset_target(un, wr_pktp);
26129 			mutex_exit(SD_MUTEX(un));
26130 		}
26131 
26132 		/*
26133 		 * If we are not getting anywhere with lun/target resets,
26134 		 * let's reset the bus.
26135 		 */
26136 		if (i == SD_NDUMP_RETRIES/2) {
26137 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26138 			(void) sd_send_polled_RQS(un);
26139 		}
26140 	}
26141 	}
26142 
26143 	scsi_destroy_pkt(wr_pktp);
26144 	mutex_enter(SD_MUTEX(un));
26145 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
26146 		mutex_exit(SD_MUTEX(un));
26147 		scsi_free_consistent_buf(wr_bp);
26148 	} else {
26149 		mutex_exit(SD_MUTEX(un));
26150 	}
26151 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
26152 	return (err);
26153 }
26154 
26155 /*
26156  *    Function: sd_scsi_poll()
26157  *
26158  * Description: This is a wrapper for the scsi_poll call.
26159  *
26160  *   Arguments: sd_lun - The unit structure
26161  *              scsi_pkt - The scsi packet being sent to the device.
26162  *
26163  * Return Code: 0 - Command completed successfully with good status
26164  *             -1 - Command failed.  This could indicate a check condition
26165  *                  or other status value requiring recovery action.
26166  *
26167  * NOTE: This code is only called off sddump().
26168  */
26169 
26170 static int
26171 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
26172 {
26173 	int status;
26174 
26175 	ASSERT(un != NULL);
26176 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26177 	ASSERT(pktp != NULL);
26178 
26179 	status = SD_SUCCESS;
26180 
26181 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
26182 		pktp->pkt_flags |= un->un_tagflags;
26183 		pktp->pkt_flags &= ~FLAG_NODISCON;
26184 	}
26185 
26186 	status = sd_ddi_scsi_poll(pktp);
26187 	/*
26188 	 * Scsi_poll returns 0 (success) if the command completes and the
26189 	 * status block is STATUS_GOOD.  We should only check errors if this
26190 	 * condition is not true.  Even then we should send our own request
26191 	 * sense packet only if we have a check condition and auto
26192 	 * request sense has not been performed by the hba.
26193 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
26194 	 */
26195 	if ((status != SD_SUCCESS) &&
26196 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
26197 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
26198 	    (pktp->pkt_reason != CMD_DEV_GONE))
26199 		(void) sd_send_polled_RQS(un);
26200 
26201 	return (status);
26202 }
26203 
26204 /*
26205  *    Function: sd_send_polled_RQS()
26206  *
26207  * Description: This sends the request sense command to a device.
26208  *
26209  *   Arguments: sd_lun - The unit structure
26210  *
26211  * Return Code: 0 - Command completed successfully with good status
26212  *             -1 - Command failed.
26213  *
26214  */
26215 
26216 static int
26217 sd_send_polled_RQS(struct sd_lun *un)
26218 {
26219 	int	ret_val;
26220 	struct	scsi_pkt	*rqs_pktp;
26221 	struct	buf		*rqs_bp;
26222 
26223 	ASSERT(un != NULL);
26224 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26225 
26226 	ret_val = SD_SUCCESS;
26227 
26228 	rqs_pktp = un->un_rqs_pktp;
26229 	rqs_bp	 = un->un_rqs_bp;
26230 
26231 	mutex_enter(SD_MUTEX(un));
26232 
26233 	if (un->un_sense_isbusy) {
26234 		ret_val = SD_FAILURE;
26235 		mutex_exit(SD_MUTEX(un));
26236 		return (ret_val);
26237 	}
26238 
26239 	/*
26240 	 * If the request sense buffer (and packet) is not in use,
26241 	 * let's set the un_sense_isbusy and send our packet
26242 	 */
26243 	un->un_sense_isbusy 	= 1;
26244 	rqs_pktp->pkt_resid  	= 0;
26245 	rqs_pktp->pkt_reason 	= 0;
26246 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
26247 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
26248 
26249 	mutex_exit(SD_MUTEX(un));
26250 
26251 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
26252 	    " 0x%p\n", rqs_bp->b_un.b_addr);
26253 
26254 	/*
26255 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
26256 	 * axle - it has a call into us!
26257 	 */
26258 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
26259 		SD_INFO(SD_LOG_COMMON, un,
26260 		    "sd_send_polled_RQS: RQS failed\n");
26261 	}
26262 
26263 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
26264 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
26265 
26266 	mutex_enter(SD_MUTEX(un));
26267 	un->un_sense_isbusy = 0;
26268 	mutex_exit(SD_MUTEX(un));
26269 
26270 	return (ret_val);
26271 }
26272 
26273 /*
26274  * Defines needed for localized version of the scsi_poll routine.
26275  */
26276 #define	CSEC		10000			/* usecs */
26277 #define	SEC_TO_CSEC	(1000000/CSEC)
26278 
26279 /*
26280  *    Function: sd_ddi_scsi_poll()
26281  *
26282  * Description: Localized version of the scsi_poll routine.  The purpose is to
26283  *		send a scsi_pkt to a device as a polled command.  This version
26284  *		is to ensure more robust handling of transport errors.
26285  *		Specifically this routine cures not ready, coming ready
26286  *		transition for power up and reset of sonoma's.  This can take
26287  *		up to 45 seconds for power-on and 20 seconds for reset of a
26288  * 		sonoma lun.
26289  *
26290  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
26291  *
26292  * Return Code: 0 - Command completed successfully with good status
26293  *             -1 - Command failed.
26294  *
26295  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
26296  * be fixed (removing this code), we need to determine how to handle the
26297  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
26298  *
26299  * NOTE: This code is only called off sddump().
26300  */
26301 static int
26302 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
26303 {
26304 	int			rval = -1;
26305 	int			savef;
26306 	long			savet;
26307 	void			(*savec)();
26308 	int			timeout;
26309 	int			busy_count;
26310 	int			poll_delay;
26311 	int			rc;
26312 	uint8_t			*sensep;
26313 	struct scsi_arq_status	*arqstat;
26314 	extern int		do_polled_io;
26315 
26316 	ASSERT(pkt->pkt_scbp);
26317 
26318 	/*
26319 	 * save old flags..
26320 	 */
26321 	savef = pkt->pkt_flags;
26322 	savec = pkt->pkt_comp;
26323 	savet = pkt->pkt_time;
26324 
26325 	pkt->pkt_flags |= FLAG_NOINTR;
26326 
26327 	/*
26328 	 * XXX there is nothing in the SCSA spec that states that we should not
26329 	 * do a callback for polled cmds; however, removing this will break sd
26330 	 * and probably other target drivers
26331 	 */
26332 	pkt->pkt_comp = NULL;
26333 
26334 	/*
26335 	 * we don't like a polled command without timeout.
26336 	 * 60 seconds seems long enough.
26337 	 */
26338 	if (pkt->pkt_time == 0)
26339 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
26340 
26341 	/*
26342 	 * Send polled cmd.
26343 	 *
26344 	 * We do some error recovery for various errors.  Tran_busy,
26345 	 * queue full, and non-dispatched commands are retried every 10 msec.
26346 	 * as they are typically transient failures.  Busy status and Not
26347 	 * Ready are retried every second as this status takes a while to
26348 	 * change.
26349 	 */
26350 	timeout = pkt->pkt_time * SEC_TO_CSEC;
26351 
26352 	for (busy_count = 0; busy_count < timeout; busy_count++) {
26353 		/*
26354 		 * Initialize pkt status variables.
26355 		 */
26356 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
26357 
26358 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
26359 			if (rc != TRAN_BUSY) {
26360 				/* Transport failed - give up. */
26361 				break;
26362 			} else {
26363 				/* Transport busy - try again. */
26364 				poll_delay = 1 * CSEC;		/* 10 msec. */
26365 			}
26366 		} else {
26367 			/*
26368 			 * Transport accepted - check pkt status.
26369 			 */
26370 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
26371 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26372 			    (rc == STATUS_CHECK) &&
26373 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
26374 				arqstat =
26375 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
26376 				sensep = (uint8_t *)&arqstat->sts_sensedata;
26377 			} else {
26378 				sensep = NULL;
26379 			}
26380 
26381 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26382 			    (rc == STATUS_GOOD)) {
26383 				/* No error - we're done */
26384 				rval = 0;
26385 				break;
26386 
26387 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
26388 				/* Lost connection - give up */
26389 				break;
26390 
26391 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
26392 			    (pkt->pkt_state == 0)) {
26393 				/* Pkt not dispatched - try again. */
26394 				poll_delay = 1 * CSEC;		/* 10 msec. */
26395 
26396 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26397 			    (rc == STATUS_QFULL)) {
26398 				/* Queue full - try again. */
26399 				poll_delay = 1 * CSEC;		/* 10 msec. */
26400 
26401 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26402 			    (rc == STATUS_BUSY)) {
26403 				/* Busy - try again. */
26404 				poll_delay = 100 * CSEC;	/* 1 sec. */
26405 				busy_count += (SEC_TO_CSEC - 1);
26406 
26407 			} else if ((sensep != NULL) &&
26408 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
26409 				/*
26410 				 * Unit Attention - try again.
26411 				 * Pretend it took 1 sec.
26412 				 * NOTE: 'continue' avoids poll_delay
26413 				 */
26414 				busy_count += (SEC_TO_CSEC - 1);
26415 				continue;
26416 
26417 			} else if ((sensep != NULL) &&
26418 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
26419 			    (scsi_sense_asc(sensep) == 0x04) &&
26420 			    (scsi_sense_ascq(sensep) == 0x01)) {
26421 				/*
26422 				 * Not ready -> ready - try again.
26423 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
26424 				 * ...same as STATUS_BUSY
26425 				 */
26426 				poll_delay = 100 * CSEC;	/* 1 sec. */
26427 				busy_count += (SEC_TO_CSEC - 1);
26428 
26429 			} else {
26430 				/* BAD status - give up. */
26431 				break;
26432 			}
26433 		}
26434 
26435 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
26436 		    !do_polled_io) {
26437 			delay(drv_usectohz(poll_delay));
26438 		} else {
26439 			/* we busy wait during cpr_dump or interrupt threads */
26440 			drv_usecwait(poll_delay);
26441 		}
26442 	}
26443 
26444 	pkt->pkt_flags = savef;
26445 	pkt->pkt_comp = savec;
26446 	pkt->pkt_time = savet;
26447 
26448 	/* return on error */
26449 	if (rval)
26450 		return (rval);
26451 
26452 	/*
26453 	 * This is not a performance critical code path.
26454 	 *
26455 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
26456 	 * issues associated with looking at DMA memory prior to
26457 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
26458 	 */
26459 	scsi_sync_pkt(pkt);
26460 	return (0);
26461 }
26462 
26463 
26464 
26465 /*
26466  *    Function: sd_persistent_reservation_in_read_keys
26467  *
26468  * Description: This routine is the driver entry point for handling CD-ROM
26469  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
26470  *		by sending the SCSI-3 PRIN commands to the device.
26471  *		Processes the read keys command response by copying the
26472  *		reservation key information into the user provided buffer.
26473  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
26474  *
26475  *   Arguments: un   -  Pointer to soft state struct for the target.
26476  *		usrp -	user provided pointer to multihost Persistent In Read
26477  *			Keys structure (mhioc_inkeys_t)
26478  *		flag -	this argument is a pass through to ddi_copyxxx()
26479  *			directly from the mode argument of ioctl().
26480  *
26481  * Return Code: 0   - Success
26482  *		EACCES
26483  *		ENOTSUP
26484  *		errno return code from sd_send_scsi_cmd()
26485  *
26486  *     Context: Can sleep. Does not return until command is completed.
26487  */
26488 
26489 static int
26490 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
26491     mhioc_inkeys_t *usrp, int flag)
26492 {
26493 #ifdef _MULTI_DATAMODEL
26494 	struct mhioc_key_list32	li32;
26495 #endif
26496 	sd_prin_readkeys_t	*in;
26497 	mhioc_inkeys_t		*ptr;
26498 	mhioc_key_list_t	li;
26499 	uchar_t			*data_bufp;
26500 	int 			data_len;
26501 	int			rval = 0;
26502 	size_t			copysz;
26503 	sd_ssc_t		*ssc;
26504 
26505 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
26506 		return (EINVAL);
26507 	}
26508 	bzero(&li, sizeof (mhioc_key_list_t));
26509 
26510 	ssc = sd_ssc_init(un);
26511 
26512 	/*
26513 	 * Get the listsize from user
26514 	 */
26515 #ifdef _MULTI_DATAMODEL
26516 
26517 	switch (ddi_model_convert_from(flag & FMODELS)) {
26518 	case DDI_MODEL_ILP32:
26519 		copysz = sizeof (struct mhioc_key_list32);
26520 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
26521 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26522 			    "sd_persistent_reservation_in_read_keys: "
26523 			    "failed ddi_copyin: mhioc_key_list32_t\n");
26524 			rval = EFAULT;
26525 			goto done;
26526 		}
26527 		li.listsize = li32.listsize;
26528 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
26529 		break;
26530 
26531 	case DDI_MODEL_NONE:
26532 		copysz = sizeof (mhioc_key_list_t);
26533 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26534 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26535 			    "sd_persistent_reservation_in_read_keys: "
26536 			    "failed ddi_copyin: mhioc_key_list_t\n");
26537 			rval = EFAULT;
26538 			goto done;
26539 		}
26540 		break;
26541 	}
26542 
26543 #else /* ! _MULTI_DATAMODEL */
26544 	copysz = sizeof (mhioc_key_list_t);
26545 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26546 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26547 		    "sd_persistent_reservation_in_read_keys: "
26548 		    "failed ddi_copyin: mhioc_key_list_t\n");
26549 		rval = EFAULT;
26550 		goto done;
26551 	}
26552 #endif
26553 
26554 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
26555 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
26556 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26557 
26558 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
26559 	    data_len, data_bufp);
26560 	if (rval != 0) {
26561 		if (rval == EIO)
26562 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26563 		else
26564 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26565 		goto done;
26566 	}
26567 	in = (sd_prin_readkeys_t *)data_bufp;
26568 	ptr->generation = BE_32(in->generation);
26569 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
26570 
26571 	/*
26572 	 * Return the min(listsize, listlen) keys
26573 	 */
26574 #ifdef _MULTI_DATAMODEL
26575 
26576 	switch (ddi_model_convert_from(flag & FMODELS)) {
26577 	case DDI_MODEL_ILP32:
26578 		li32.listlen = li.listlen;
26579 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
26580 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26581 			    "sd_persistent_reservation_in_read_keys: "
26582 			    "failed ddi_copyout: mhioc_key_list32_t\n");
26583 			rval = EFAULT;
26584 			goto done;
26585 		}
26586 		break;
26587 
26588 	case DDI_MODEL_NONE:
26589 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26590 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26591 			    "sd_persistent_reservation_in_read_keys: "
26592 			    "failed ddi_copyout: mhioc_key_list_t\n");
26593 			rval = EFAULT;
26594 			goto done;
26595 		}
26596 		break;
26597 	}
26598 
26599 #else /* ! _MULTI_DATAMODEL */
26600 
26601 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26602 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26603 		    "sd_persistent_reservation_in_read_keys: "
26604 		    "failed ddi_copyout: mhioc_key_list_t\n");
26605 		rval = EFAULT;
26606 		goto done;
26607 	}
26608 
26609 #endif /* _MULTI_DATAMODEL */
26610 
26611 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
26612 	    li.listsize * MHIOC_RESV_KEY_SIZE);
26613 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
26614 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26615 		    "sd_persistent_reservation_in_read_keys: "
26616 		    "failed ddi_copyout: keylist\n");
26617 		rval = EFAULT;
26618 	}
26619 done:
26620 	sd_ssc_fini(ssc);
26621 	kmem_free(data_bufp, data_len);
26622 	return (rval);
26623 }
26624 
26625 
26626 /*
26627  *    Function: sd_persistent_reservation_in_read_resv
26628  *
26629  * Description: This routine is the driver entry point for handling CD-ROM
26630  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
26631  *		by sending the SCSI-3 PRIN commands to the device.
26632  *		Process the read persistent reservations command response by
26633  *		copying the reservation information into the user provided
26634  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
26635  *
26636  *   Arguments: un   -  Pointer to soft state struct for the target.
26637  *		usrp -	user provided pointer to multihost Persistent In Read
26638  *			Keys structure (mhioc_inkeys_t)
26639  *		flag -	this argument is a pass through to ddi_copyxxx()
26640  *			directly from the mode argument of ioctl().
26641  *
26642  * Return Code: 0   - Success
26643  *		EACCES
26644  *		ENOTSUP
26645  *		errno return code from sd_send_scsi_cmd()
26646  *
26647  *     Context: Can sleep. Does not return until command is completed.
26648  */
26649 
26650 static int
26651 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
26652     mhioc_inresvs_t *usrp, int flag)
26653 {
26654 #ifdef _MULTI_DATAMODEL
26655 	struct mhioc_resv_desc_list32 resvlist32;
26656 #endif
26657 	sd_prin_readresv_t	*in;
26658 	mhioc_inresvs_t		*ptr;
26659 	sd_readresv_desc_t	*readresv_ptr;
26660 	mhioc_resv_desc_list_t	resvlist;
26661 	mhioc_resv_desc_t 	resvdesc;
26662 	uchar_t			*data_bufp = NULL;
26663 	int 			data_len;
26664 	int			rval = 0;
26665 	int			i;
26666 	size_t			copysz;
26667 	mhioc_resv_desc_t	*bufp;
26668 	sd_ssc_t		*ssc;
26669 
26670 	if ((ptr = usrp) == NULL) {
26671 		return (EINVAL);
26672 	}
26673 
26674 	ssc = sd_ssc_init(un);
26675 
26676 	/*
26677 	 * Get the listsize from user
26678 	 */
26679 #ifdef _MULTI_DATAMODEL
26680 	switch (ddi_model_convert_from(flag & FMODELS)) {
26681 	case DDI_MODEL_ILP32:
26682 		copysz = sizeof (struct mhioc_resv_desc_list32);
26683 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
26684 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26685 			    "sd_persistent_reservation_in_read_resv: "
26686 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26687 			rval = EFAULT;
26688 			goto done;
26689 		}
26690 		resvlist.listsize = resvlist32.listsize;
26691 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
26692 		break;
26693 
26694 	case DDI_MODEL_NONE:
26695 		copysz = sizeof (mhioc_resv_desc_list_t);
26696 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26697 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26698 			    "sd_persistent_reservation_in_read_resv: "
26699 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26700 			rval = EFAULT;
26701 			goto done;
26702 		}
26703 		break;
26704 	}
26705 #else /* ! _MULTI_DATAMODEL */
26706 	copysz = sizeof (mhioc_resv_desc_list_t);
26707 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26708 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26709 		    "sd_persistent_reservation_in_read_resv: "
26710 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26711 		rval = EFAULT;
26712 		goto done;
26713 	}
26714 #endif /* ! _MULTI_DATAMODEL */
26715 
26716 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
26717 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
26718 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26719 
26720 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
26721 	    data_len, data_bufp);
26722 	if (rval != 0) {
26723 		if (rval == EIO)
26724 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26725 		else
26726 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26727 		goto done;
26728 	}
26729 	in = (sd_prin_readresv_t *)data_bufp;
26730 	ptr->generation = BE_32(in->generation);
26731 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
26732 
26733 	/*
26734 	 * Return the min(listsize, listlen( keys
26735 	 */
26736 #ifdef _MULTI_DATAMODEL
26737 
26738 	switch (ddi_model_convert_from(flag & FMODELS)) {
26739 	case DDI_MODEL_ILP32:
26740 		resvlist32.listlen = resvlist.listlen;
26741 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
26742 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26743 			    "sd_persistent_reservation_in_read_resv: "
26744 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26745 			rval = EFAULT;
26746 			goto done;
26747 		}
26748 		break;
26749 
26750 	case DDI_MODEL_NONE:
26751 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26752 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26753 			    "sd_persistent_reservation_in_read_resv: "
26754 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26755 			rval = EFAULT;
26756 			goto done;
26757 		}
26758 		break;
26759 	}
26760 
26761 #else /* ! _MULTI_DATAMODEL */
26762 
26763 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26764 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26765 		    "sd_persistent_reservation_in_read_resv: "
26766 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26767 		rval = EFAULT;
26768 		goto done;
26769 	}
26770 
26771 #endif /* ! _MULTI_DATAMODEL */
26772 
26773 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
26774 	bufp = resvlist.list;
26775 	copysz = sizeof (mhioc_resv_desc_t);
26776 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
26777 	    i++, readresv_ptr++, bufp++) {
26778 
26779 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
26780 		    MHIOC_RESV_KEY_SIZE);
26781 		resvdesc.type  = readresv_ptr->type;
26782 		resvdesc.scope = readresv_ptr->scope;
26783 		resvdesc.scope_specific_addr =
26784 		    BE_32(readresv_ptr->scope_specific_addr);
26785 
26786 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
26787 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26788 			    "sd_persistent_reservation_in_read_resv: "
26789 			    "failed ddi_copyout: resvlist\n");
26790 			rval = EFAULT;
26791 			goto done;
26792 		}
26793 	}
26794 done:
26795 	sd_ssc_fini(ssc);
26796 	/* only if data_bufp is allocated, we need to free it */
26797 	if (data_bufp) {
26798 		kmem_free(data_bufp, data_len);
26799 	}
26800 	return (rval);
26801 }
26802 
26803 
26804 /*
26805  *    Function: sr_change_blkmode()
26806  *
26807  * Description: This routine is the driver entry point for handling CD-ROM
26808  *		block mode ioctl requests. Support for returning and changing
26809  *		the current block size in use by the device is implemented. The
26810  *		LBA size is changed via a MODE SELECT Block Descriptor.
26811  *
26812  *		This routine issues a mode sense with an allocation length of
26813  *		12 bytes for the mode page header and a single block descriptor.
26814  *
26815  *   Arguments: dev - the device 'dev_t'
26816  *		cmd - the request type; one of CDROMGBLKMODE (get) or
26817  *		      CDROMSBLKMODE (set)
26818  *		data - current block size or requested block size
26819  *		flag - this argument is a pass through to ddi_copyxxx() directly
26820  *		       from the mode argument of ioctl().
26821  *
26822  * Return Code: the code returned by sd_send_scsi_cmd()
26823  *		EINVAL if invalid arguments are provided
26824  *		EFAULT if ddi_copyxxx() fails
26825  *		ENXIO if fail ddi_get_soft_state
26826  *		EIO if invalid mode sense block descriptor length
26827  *
26828  */
26829 
26830 static int
26831 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
26832 {
26833 	struct sd_lun			*un = NULL;
26834 	struct mode_header		*sense_mhp, *select_mhp;
26835 	struct block_descriptor		*sense_desc, *select_desc;
26836 	int				current_bsize;
26837 	int				rval = EINVAL;
26838 	uchar_t				*sense = NULL;
26839 	uchar_t				*select = NULL;
26840 	sd_ssc_t			*ssc;
26841 
26842 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
26843 
26844 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26845 		return (ENXIO);
26846 	}
26847 
26848 	/*
26849 	 * The block length is changed via the Mode Select block descriptor, the
26850 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
26851 	 * required as part of this routine. Therefore the mode sense allocation
26852 	 * length is specified to be the length of a mode page header and a
26853 	 * block descriptor.
26854 	 */
26855 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
26856 
26857 	ssc = sd_ssc_init(un);
26858 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
26859 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
26860 	sd_ssc_fini(ssc);
26861 	if (rval != 0) {
26862 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26863 		    "sr_change_blkmode: Mode Sense Failed\n");
26864 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26865 		return (rval);
26866 	}
26867 
26868 	/* Check the block descriptor len to handle only 1 block descriptor */
26869 	sense_mhp = (struct mode_header *)sense;
26870 	if ((sense_mhp->bdesc_length == 0) ||
26871 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
26872 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26873 		    "sr_change_blkmode: Mode Sense returned invalid block"
26874 		    " descriptor length\n");
26875 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26876 		return (EIO);
26877 	}
26878 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
26879 	current_bsize = ((sense_desc->blksize_hi << 16) |
26880 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
26881 
26882 	/* Process command */
26883 	switch (cmd) {
26884 	case CDROMGBLKMODE:
26885 		/* Return the block size obtained during the mode sense */
26886 		if (ddi_copyout(&current_bsize, (void *)data,
26887 		    sizeof (int), flag) != 0)
26888 			rval = EFAULT;
26889 		break;
26890 	case CDROMSBLKMODE:
26891 		/* Validate the requested block size */
26892 		switch (data) {
26893 		case CDROM_BLK_512:
26894 		case CDROM_BLK_1024:
26895 		case CDROM_BLK_2048:
26896 		case CDROM_BLK_2056:
26897 		case CDROM_BLK_2336:
26898 		case CDROM_BLK_2340:
26899 		case CDROM_BLK_2352:
26900 		case CDROM_BLK_2368:
26901 		case CDROM_BLK_2448:
26902 		case CDROM_BLK_2646:
26903 		case CDROM_BLK_2647:
26904 			break;
26905 		default:
26906 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26907 			    "sr_change_blkmode: "
26908 			    "Block Size '%ld' Not Supported\n", data);
26909 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26910 			return (EINVAL);
26911 		}
26912 
26913 		/*
26914 		 * The current block size matches the requested block size so
26915 		 * there is no need to send the mode select to change the size
26916 		 */
26917 		if (current_bsize == data) {
26918 			break;
26919 		}
26920 
26921 		/* Build the select data for the requested block size */
26922 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
26923 		select_mhp = (struct mode_header *)select;
26924 		select_desc =
26925 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
26926 		/*
26927 		 * The LBA size is changed via the block descriptor, so the
26928 		 * descriptor is built according to the user data
26929 		 */
26930 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
26931 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
26932 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
26933 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
26934 
26935 		/* Send the mode select for the requested block size */
26936 		ssc = sd_ssc_init(un);
26937 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
26938 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
26939 		    SD_PATH_STANDARD);
26940 		sd_ssc_fini(ssc);
26941 		if (rval != 0) {
26942 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26943 			    "sr_change_blkmode: Mode Select Failed\n");
26944 			/*
26945 			 * The mode select failed for the requested block size,
26946 			 * so reset the data for the original block size and
26947 			 * send it to the target. The error is indicated by the
26948 			 * return value for the failed mode select.
26949 			 */
26950 			select_desc->blksize_hi  = sense_desc->blksize_hi;
26951 			select_desc->blksize_mid = sense_desc->blksize_mid;
26952 			select_desc->blksize_lo  = sense_desc->blksize_lo;
26953 			ssc = sd_ssc_init(un);
26954 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
26955 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
26956 			    SD_PATH_STANDARD);
26957 			sd_ssc_fini(ssc);
26958 		} else {
26959 			ASSERT(!mutex_owned(SD_MUTEX(un)));
26960 			mutex_enter(SD_MUTEX(un));
26961 			sd_update_block_info(un, (uint32_t)data, 0);
26962 			mutex_exit(SD_MUTEX(un));
26963 		}
26964 		break;
26965 	default:
26966 		/* should not reach here, but check anyway */
26967 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26968 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
26969 		rval = EINVAL;
26970 		break;
26971 	}
26972 
26973 	if (select) {
26974 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
26975 	}
26976 	if (sense) {
26977 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26978 	}
26979 	return (rval);
26980 }
26981 
26982 
26983 /*
26984  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
26985  * implement driver support for getting and setting the CD speed. The command
26986  * set used will be based on the device type. If the device has not been
26987  * identified as MMC the Toshiba vendor specific mode page will be used. If
26988  * the device is MMC but does not support the Real Time Streaming feature
26989  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
26990  * be used to read the speed.
26991  */
26992 
26993 /*
26994  *    Function: sr_change_speed()
26995  *
26996  * Description: This routine is the driver entry point for handling CD-ROM
26997  *		drive speed ioctl requests for devices supporting the Toshiba
26998  *		vendor specific drive speed mode page. Support for returning
26999  *		and changing the current drive speed in use by the device is
27000  *		implemented.
27001  *
27002  *   Arguments: dev - the device 'dev_t'
27003  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
27004  *		      CDROMSDRVSPEED (set)
27005  *		data - current drive speed or requested drive speed
27006  *		flag - this argument is a pass through to ddi_copyxxx() directly
27007  *		       from the mode argument of ioctl().
27008  *
27009  * Return Code: the code returned by sd_send_scsi_cmd()
27010  *		EINVAL if invalid arguments are provided
27011  *		EFAULT if ddi_copyxxx() fails
27012  *		ENXIO if fail ddi_get_soft_state
27013  *		EIO if invalid mode sense block descriptor length
27014  */
27015 
27016 static int
27017 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27018 {
27019 	struct sd_lun			*un = NULL;
27020 	struct mode_header		*sense_mhp, *select_mhp;
27021 	struct mode_speed		*sense_page, *select_page;
27022 	int				current_speed;
27023 	int				rval = EINVAL;
27024 	int				bd_len;
27025 	uchar_t				*sense = NULL;
27026 	uchar_t				*select = NULL;
27027 	sd_ssc_t			*ssc;
27028 
27029 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27030 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27031 		return (ENXIO);
27032 	}
27033 
27034 	/*
27035 	 * Note: The drive speed is being modified here according to a Toshiba
27036 	 * vendor specific mode page (0x31).
27037 	 */
27038 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27039 
27040 	ssc = sd_ssc_init(un);
27041 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27042 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
27043 	    SD_PATH_STANDARD);
27044 	sd_ssc_fini(ssc);
27045 	if (rval != 0) {
27046 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27047 		    "sr_change_speed: Mode Sense Failed\n");
27048 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27049 		return (rval);
27050 	}
27051 	sense_mhp  = (struct mode_header *)sense;
27052 
27053 	/* Check the block descriptor len to handle only 1 block descriptor */
27054 	bd_len = sense_mhp->bdesc_length;
27055 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27056 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27057 		    "sr_change_speed: Mode Sense returned invalid block "
27058 		    "descriptor length\n");
27059 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27060 		return (EIO);
27061 	}
27062 
27063 	sense_page = (struct mode_speed *)
27064 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27065 	current_speed = sense_page->speed;
27066 
27067 	/* Process command */
27068 	switch (cmd) {
27069 	case CDROMGDRVSPEED:
27070 		/* Return the drive speed obtained during the mode sense */
27071 		if (current_speed == 0x2) {
27072 			current_speed = CDROM_TWELVE_SPEED;
27073 		}
27074 		if (ddi_copyout(&current_speed, (void *)data,
27075 		    sizeof (int), flag) != 0) {
27076 			rval = EFAULT;
27077 		}
27078 		break;
27079 	case CDROMSDRVSPEED:
27080 		/* Validate the requested drive speed */
27081 		switch ((uchar_t)data) {
27082 		case CDROM_TWELVE_SPEED:
27083 			data = 0x2;
27084 			/*FALLTHROUGH*/
27085 		case CDROM_NORMAL_SPEED:
27086 		case CDROM_DOUBLE_SPEED:
27087 		case CDROM_QUAD_SPEED:
27088 		case CDROM_MAXIMUM_SPEED:
27089 			break;
27090 		default:
27091 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27092 			    "sr_change_speed: "
27093 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
27094 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27095 			return (EINVAL);
27096 		}
27097 
27098 		/*
27099 		 * The current drive speed matches the requested drive speed so
27100 		 * there is no need to send the mode select to change the speed
27101 		 */
27102 		if (current_speed == data) {
27103 			break;
27104 		}
27105 
27106 		/* Build the select data for the requested drive speed */
27107 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27108 		select_mhp = (struct mode_header *)select;
27109 		select_mhp->bdesc_length = 0;
27110 		select_page =
27111 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27112 		select_page =
27113 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27114 		select_page->mode_page.code = CDROM_MODE_SPEED;
27115 		select_page->mode_page.length = 2;
27116 		select_page->speed = (uchar_t)data;
27117 
27118 		/* Send the mode select for the requested block size */
27119 		ssc = sd_ssc_init(un);
27120 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27121 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27122 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27123 		sd_ssc_fini(ssc);
27124 		if (rval != 0) {
27125 			/*
27126 			 * The mode select failed for the requested drive speed,
27127 			 * so reset the data for the original drive speed and
27128 			 * send it to the target. The error is indicated by the
27129 			 * return value for the failed mode select.
27130 			 */
27131 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27132 			    "sr_drive_speed: Mode Select Failed\n");
27133 			select_page->speed = sense_page->speed;
27134 			ssc = sd_ssc_init(un);
27135 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27136 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27137 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27138 			sd_ssc_fini(ssc);
27139 		}
27140 		break;
27141 	default:
27142 		/* should not reach here, but check anyway */
27143 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27144 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
27145 		rval = EINVAL;
27146 		break;
27147 	}
27148 
27149 	if (select) {
27150 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
27151 	}
27152 	if (sense) {
27153 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27154 	}
27155 
27156 	return (rval);
27157 }
27158 
27159 
27160 /*
27161  *    Function: sr_atapi_change_speed()
27162  *
27163  * Description: This routine is the driver entry point for handling CD-ROM
27164  *		drive speed ioctl requests for MMC devices that do not support
27165  *		the Real Time Streaming feature (0x107).
27166  *
27167  *		Note: This routine will use the SET SPEED command which may not
27168  *		be supported by all devices.
27169  *
27170  *   Arguments: dev- the device 'dev_t'
27171  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
27172  *		     CDROMSDRVSPEED (set)
27173  *		data- current drive speed or requested drive speed
27174  *		flag- this argument is a pass through to ddi_copyxxx() directly
27175  *		      from the mode argument of ioctl().
27176  *
27177  * Return Code: the code returned by sd_send_scsi_cmd()
27178  *		EINVAL if invalid arguments are provided
27179  *		EFAULT if ddi_copyxxx() fails
27180  *		ENXIO if fail ddi_get_soft_state
27181  *		EIO if invalid mode sense block descriptor length
27182  */
27183 
27184 static int
27185 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27186 {
27187 	struct sd_lun			*un;
27188 	struct uscsi_cmd		*com = NULL;
27189 	struct mode_header_grp2		*sense_mhp;
27190 	uchar_t				*sense_page;
27191 	uchar_t				*sense = NULL;
27192 	char				cdb[CDB_GROUP5];
27193 	int				bd_len;
27194 	int				current_speed = 0;
27195 	int				max_speed = 0;
27196 	int				rval;
27197 	sd_ssc_t			*ssc;
27198 
27199 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27200 
27201 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27202 		return (ENXIO);
27203 	}
27204 
27205 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
27206 
27207 	ssc = sd_ssc_init(un);
27208 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
27209 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
27210 	    SD_PATH_STANDARD);
27211 	sd_ssc_fini(ssc);
27212 	if (rval != 0) {
27213 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27214 		    "sr_atapi_change_speed: Mode Sense Failed\n");
27215 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27216 		return (rval);
27217 	}
27218 
27219 	/* Check the block descriptor len to handle only 1 block descriptor */
27220 	sense_mhp = (struct mode_header_grp2 *)sense;
27221 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
27222 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27223 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27224 		    "sr_atapi_change_speed: Mode Sense returned invalid "
27225 		    "block descriptor length\n");
27226 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27227 		return (EIO);
27228 	}
27229 
27230 	/* Calculate the current and maximum drive speeds */
27231 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27232 	current_speed = (sense_page[14] << 8) | sense_page[15];
27233 	max_speed = (sense_page[8] << 8) | sense_page[9];
27234 
27235 	/* Process the command */
27236 	switch (cmd) {
27237 	case CDROMGDRVSPEED:
27238 		current_speed /= SD_SPEED_1X;
27239 		if (ddi_copyout(&current_speed, (void *)data,
27240 		    sizeof (int), flag) != 0)
27241 			rval = EFAULT;
27242 		break;
27243 	case CDROMSDRVSPEED:
27244 		/* Convert the speed code to KB/sec */
27245 		switch ((uchar_t)data) {
27246 		case CDROM_NORMAL_SPEED:
27247 			current_speed = SD_SPEED_1X;
27248 			break;
27249 		case CDROM_DOUBLE_SPEED:
27250 			current_speed = 2 * SD_SPEED_1X;
27251 			break;
27252 		case CDROM_QUAD_SPEED:
27253 			current_speed = 4 * SD_SPEED_1X;
27254 			break;
27255 		case CDROM_TWELVE_SPEED:
27256 			current_speed = 12 * SD_SPEED_1X;
27257 			break;
27258 		case CDROM_MAXIMUM_SPEED:
27259 			current_speed = 0xffff;
27260 			break;
27261 		default:
27262 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27263 			    "sr_atapi_change_speed: invalid drive speed %d\n",
27264 			    (uchar_t)data);
27265 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27266 			return (EINVAL);
27267 		}
27268 
27269 		/* Check the request against the drive's max speed. */
27270 		if (current_speed != 0xffff) {
27271 			if (current_speed > max_speed) {
27272 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27273 				return (EINVAL);
27274 			}
27275 		}
27276 
27277 		/*
27278 		 * Build and send the SET SPEED command
27279 		 *
27280 		 * Note: The SET SPEED (0xBB) command used in this routine is
27281 		 * obsolete per the SCSI MMC spec but still supported in the
27282 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27283 		 * therefore the command is still implemented in this routine.
27284 		 */
27285 		bzero(cdb, sizeof (cdb));
27286 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
27287 		cdb[2] = (uchar_t)(current_speed >> 8);
27288 		cdb[3] = (uchar_t)current_speed;
27289 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27290 		com->uscsi_cdb	   = (caddr_t)cdb;
27291 		com->uscsi_cdblen  = CDB_GROUP5;
27292 		com->uscsi_bufaddr = NULL;
27293 		com->uscsi_buflen  = 0;
27294 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
27295 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
27296 		break;
27297 	default:
27298 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27299 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
27300 		rval = EINVAL;
27301 	}
27302 
27303 	if (sense) {
27304 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27305 	}
27306 	if (com) {
27307 		kmem_free(com, sizeof (*com));
27308 	}
27309 	return (rval);
27310 }
27311 
27312 
27313 /*
27314  *    Function: sr_pause_resume()
27315  *
27316  * Description: This routine is the driver entry point for handling CD-ROM
27317  *		pause/resume ioctl requests. This only affects the audio play
27318  *		operation.
27319  *
27320  *   Arguments: dev - the device 'dev_t'
27321  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
27322  *		      for setting the resume bit of the cdb.
27323  *
27324  * Return Code: the code returned by sd_send_scsi_cmd()
27325  *		EINVAL if invalid mode specified
27326  *
27327  */
27328 
27329 static int
27330 sr_pause_resume(dev_t dev, int cmd)
27331 {
27332 	struct sd_lun		*un;
27333 	struct uscsi_cmd	*com;
27334 	char			cdb[CDB_GROUP1];
27335 	int			rval;
27336 
27337 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27338 		return (ENXIO);
27339 	}
27340 
27341 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27342 	bzero(cdb, CDB_GROUP1);
27343 	cdb[0] = SCMD_PAUSE_RESUME;
27344 	switch (cmd) {
27345 	case CDROMRESUME:
27346 		cdb[8] = 1;
27347 		break;
27348 	case CDROMPAUSE:
27349 		cdb[8] = 0;
27350 		break;
27351 	default:
27352 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
27353 		    " Command '%x' Not Supported\n", cmd);
27354 		rval = EINVAL;
27355 		goto done;
27356 	}
27357 
27358 	com->uscsi_cdb    = cdb;
27359 	com->uscsi_cdblen = CDB_GROUP1;
27360 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27361 
27362 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27363 	    SD_PATH_STANDARD);
27364 
27365 done:
27366 	kmem_free(com, sizeof (*com));
27367 	return (rval);
27368 }
27369 
27370 
27371 /*
27372  *    Function: sr_play_msf()
27373  *
27374  * Description: This routine is the driver entry point for handling CD-ROM
27375  *		ioctl requests to output the audio signals at the specified
27376  *		starting address and continue the audio play until the specified
27377  *		ending address (CDROMPLAYMSF) The address is in Minute Second
27378  *		Frame (MSF) format.
27379  *
27380  *   Arguments: dev	- the device 'dev_t'
27381  *		data	- pointer to user provided audio msf structure,
27382  *		          specifying start/end addresses.
27383  *		flag	- this argument is a pass through to ddi_copyxxx()
27384  *		          directly from the mode argument of ioctl().
27385  *
27386  * Return Code: the code returned by sd_send_scsi_cmd()
27387  *		EFAULT if ddi_copyxxx() fails
27388  *		ENXIO if fail ddi_get_soft_state
27389  *		EINVAL if data pointer is NULL
27390  */
27391 
27392 static int
27393 sr_play_msf(dev_t dev, caddr_t data, int flag)
27394 {
27395 	struct sd_lun		*un;
27396 	struct uscsi_cmd	*com;
27397 	struct cdrom_msf	msf_struct;
27398 	struct cdrom_msf	*msf = &msf_struct;
27399 	char			cdb[CDB_GROUP1];
27400 	int			rval;
27401 
27402 	if (data == NULL) {
27403 		return (EINVAL);
27404 	}
27405 
27406 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27407 		return (ENXIO);
27408 	}
27409 
27410 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
27411 		return (EFAULT);
27412 	}
27413 
27414 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27415 	bzero(cdb, CDB_GROUP1);
27416 	cdb[0] = SCMD_PLAYAUDIO_MSF;
27417 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
27418 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
27419 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
27420 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
27421 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
27422 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
27423 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
27424 	} else {
27425 		cdb[3] = msf->cdmsf_min0;
27426 		cdb[4] = msf->cdmsf_sec0;
27427 		cdb[5] = msf->cdmsf_frame0;
27428 		cdb[6] = msf->cdmsf_min1;
27429 		cdb[7] = msf->cdmsf_sec1;
27430 		cdb[8] = msf->cdmsf_frame1;
27431 	}
27432 	com->uscsi_cdb    = cdb;
27433 	com->uscsi_cdblen = CDB_GROUP1;
27434 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27435 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27436 	    SD_PATH_STANDARD);
27437 	kmem_free(com, sizeof (*com));
27438 	return (rval);
27439 }
27440 
27441 
27442 /*
27443  *    Function: sr_play_trkind()
27444  *
27445  * Description: This routine is the driver entry point for handling CD-ROM
27446  *		ioctl requests to output the audio signals at the specified
27447  *		starting address and continue the audio play until the specified
27448  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
27449  *		format.
27450  *
27451  *   Arguments: dev	- the device 'dev_t'
27452  *		data	- pointer to user provided audio track/index structure,
27453  *		          specifying start/end addresses.
27454  *		flag	- this argument is a pass through to ddi_copyxxx()
27455  *		          directly from the mode argument of ioctl().
27456  *
27457  * Return Code: the code returned by sd_send_scsi_cmd()
27458  *		EFAULT if ddi_copyxxx() fails
27459  *		ENXIO if fail ddi_get_soft_state
27460  *		EINVAL if data pointer is NULL
27461  */
27462 
27463 static int
27464 sr_play_trkind(dev_t dev, caddr_t data, int flag)
27465 {
27466 	struct cdrom_ti		ti_struct;
27467 	struct cdrom_ti		*ti = &ti_struct;
27468 	struct uscsi_cmd	*com = NULL;
27469 	char			cdb[CDB_GROUP1];
27470 	int			rval;
27471 
27472 	if (data == NULL) {
27473 		return (EINVAL);
27474 	}
27475 
27476 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
27477 		return (EFAULT);
27478 	}
27479 
27480 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27481 	bzero(cdb, CDB_GROUP1);
27482 	cdb[0] = SCMD_PLAYAUDIO_TI;
27483 	cdb[4] = ti->cdti_trk0;
27484 	cdb[5] = ti->cdti_ind0;
27485 	cdb[7] = ti->cdti_trk1;
27486 	cdb[8] = ti->cdti_ind1;
27487 	com->uscsi_cdb    = cdb;
27488 	com->uscsi_cdblen = CDB_GROUP1;
27489 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
27490 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27491 	    SD_PATH_STANDARD);
27492 	kmem_free(com, sizeof (*com));
27493 	return (rval);
27494 }
27495 
27496 
27497 /*
27498  *    Function: sr_read_all_subcodes()
27499  *
27500  * Description: This routine is the driver entry point for handling CD-ROM
27501  *		ioctl requests to return raw subcode data while the target is
27502  *		playing audio (CDROMSUBCODE).
27503  *
27504  *   Arguments: dev	- the device 'dev_t'
27505  *		data	- pointer to user provided cdrom subcode structure,
27506  *		          specifying the transfer length and address.
27507  *		flag	- this argument is a pass through to ddi_copyxxx()
27508  *		          directly from the mode argument of ioctl().
27509  *
27510  * Return Code: the code returned by sd_send_scsi_cmd()
27511  *		EFAULT if ddi_copyxxx() fails
27512  *		ENXIO if fail ddi_get_soft_state
27513  *		EINVAL if data pointer is NULL
27514  */
27515 
27516 static int
27517 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
27518 {
27519 	struct sd_lun		*un = NULL;
27520 	struct uscsi_cmd	*com = NULL;
27521 	struct cdrom_subcode	*subcode = NULL;
27522 	int			rval;
27523 	size_t			buflen;
27524 	char			cdb[CDB_GROUP5];
27525 
27526 #ifdef _MULTI_DATAMODEL
27527 	/* To support ILP32 applications in an LP64 world */
27528 	struct cdrom_subcode32		cdrom_subcode32;
27529 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
27530 #endif
27531 	if (data == NULL) {
27532 		return (EINVAL);
27533 	}
27534 
27535 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27536 		return (ENXIO);
27537 	}
27538 
27539 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
27540 
27541 #ifdef _MULTI_DATAMODEL
27542 	switch (ddi_model_convert_from(flag & FMODELS)) {
27543 	case DDI_MODEL_ILP32:
27544 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
27545 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27546 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27547 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27548 			return (EFAULT);
27549 		}
27550 		/* Convert the ILP32 uscsi data from the application to LP64 */
27551 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
27552 		break;
27553 	case DDI_MODEL_NONE:
27554 		if (ddi_copyin(data, subcode,
27555 		    sizeof (struct cdrom_subcode), flag)) {
27556 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27557 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27558 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27559 			return (EFAULT);
27560 		}
27561 		break;
27562 	}
27563 #else /* ! _MULTI_DATAMODEL */
27564 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
27565 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27566 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
27567 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27568 		return (EFAULT);
27569 	}
27570 #endif /* _MULTI_DATAMODEL */
27571 
27572 	/*
27573 	 * Since MMC-2 expects max 3 bytes for length, check if the
27574 	 * length input is greater than 3 bytes
27575 	 */
27576 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
27577 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27578 		    "sr_read_all_subcodes: "
27579 		    "cdrom transfer length too large: %d (limit %d)\n",
27580 		    subcode->cdsc_length, 0xFFFFFF);
27581 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27582 		return (EINVAL);
27583 	}
27584 
27585 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
27586 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27587 	bzero(cdb, CDB_GROUP5);
27588 
27589 	if (un->un_f_mmc_cap == TRUE) {
27590 		cdb[0] = (char)SCMD_READ_CD;
27591 		cdb[2] = (char)0xff;
27592 		cdb[3] = (char)0xff;
27593 		cdb[4] = (char)0xff;
27594 		cdb[5] = (char)0xff;
27595 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27596 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27597 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
27598 		cdb[10] = 1;
27599 	} else {
27600 		/*
27601 		 * Note: A vendor specific command (0xDF) is being used her to
27602 		 * request a read of all subcodes.
27603 		 */
27604 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
27605 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
27606 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27607 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27608 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
27609 	}
27610 	com->uscsi_cdb	   = cdb;
27611 	com->uscsi_cdblen  = CDB_GROUP5;
27612 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
27613 	com->uscsi_buflen  = buflen;
27614 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27615 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27616 	    SD_PATH_STANDARD);
27617 	kmem_free(subcode, sizeof (struct cdrom_subcode));
27618 	kmem_free(com, sizeof (*com));
27619 	return (rval);
27620 }
27621 
27622 
27623 /*
27624  *    Function: sr_read_subchannel()
27625  *
27626  * Description: This routine is the driver entry point for handling CD-ROM
27627  *		ioctl requests to return the Q sub-channel data of the CD
27628  *		current position block. (CDROMSUBCHNL) The data includes the
27629  *		track number, index number, absolute CD-ROM address (LBA or MSF
27630  *		format per the user) , track relative CD-ROM address (LBA or MSF
27631  *		format per the user), control data and audio status.
27632  *
27633  *   Arguments: dev	- the device 'dev_t'
27634  *		data	- pointer to user provided cdrom sub-channel structure
27635  *		flag	- this argument is a pass through to ddi_copyxxx()
27636  *		          directly from the mode argument of ioctl().
27637  *
27638  * Return Code: the code returned by sd_send_scsi_cmd()
27639  *		EFAULT if ddi_copyxxx() fails
27640  *		ENXIO if fail ddi_get_soft_state
27641  *		EINVAL if data pointer is NULL
27642  */
27643 
27644 static int
27645 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
27646 {
27647 	struct sd_lun		*un;
27648 	struct uscsi_cmd	*com;
27649 	struct cdrom_subchnl	subchanel;
27650 	struct cdrom_subchnl	*subchnl = &subchanel;
27651 	char			cdb[CDB_GROUP1];
27652 	caddr_t			buffer;
27653 	int			rval;
27654 
27655 	if (data == NULL) {
27656 		return (EINVAL);
27657 	}
27658 
27659 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27660 	    (un->un_state == SD_STATE_OFFLINE)) {
27661 		return (ENXIO);
27662 	}
27663 
27664 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
27665 		return (EFAULT);
27666 	}
27667 
27668 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
27669 	bzero(cdb, CDB_GROUP1);
27670 	cdb[0] = SCMD_READ_SUBCHANNEL;
27671 	/* Set the MSF bit based on the user requested address format */
27672 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
27673 	/*
27674 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
27675 	 * returned
27676 	 */
27677 	cdb[2] = 0x40;
27678 	/*
27679 	 * Set byte 3 to specify the return data format. A value of 0x01
27680 	 * indicates that the CD-ROM current position should be returned.
27681 	 */
27682 	cdb[3] = 0x01;
27683 	cdb[8] = 0x10;
27684 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27685 	com->uscsi_cdb	   = cdb;
27686 	com->uscsi_cdblen  = CDB_GROUP1;
27687 	com->uscsi_bufaddr = buffer;
27688 	com->uscsi_buflen  = 16;
27689 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27690 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27691 	    SD_PATH_STANDARD);
27692 	if (rval != 0) {
27693 		kmem_free(buffer, 16);
27694 		kmem_free(com, sizeof (*com));
27695 		return (rval);
27696 	}
27697 
27698 	/* Process the returned Q sub-channel data */
27699 	subchnl->cdsc_audiostatus = buffer[1];
27700 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
27701 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
27702 	subchnl->cdsc_trk	= buffer[6];
27703 	subchnl->cdsc_ind	= buffer[7];
27704 	if (subchnl->cdsc_format & CDROM_LBA) {
27705 		subchnl->cdsc_absaddr.lba =
27706 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27707 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27708 		subchnl->cdsc_reladdr.lba =
27709 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
27710 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
27711 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
27712 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
27713 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
27714 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
27715 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
27716 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
27717 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
27718 	} else {
27719 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
27720 		subchnl->cdsc_absaddr.msf.second = buffer[10];
27721 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
27722 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
27723 		subchnl->cdsc_reladdr.msf.second = buffer[14];
27724 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
27725 	}
27726 	kmem_free(buffer, 16);
27727 	kmem_free(com, sizeof (*com));
27728 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
27729 	    != 0) {
27730 		return (EFAULT);
27731 	}
27732 	return (rval);
27733 }
27734 
27735 
27736 /*
27737  *    Function: sr_read_tocentry()
27738  *
27739  * Description: This routine is the driver entry point for handling CD-ROM
27740  *		ioctl requests to read from the Table of Contents (TOC)
27741  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
27742  *		fields, the starting address (LBA or MSF format per the user)
27743  *		and the data mode if the user specified track is a data track.
27744  *
27745  *		Note: The READ HEADER (0x44) command used in this routine is
27746  *		obsolete per the SCSI MMC spec but still supported in the
27747  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27748  *		therefore the command is still implemented in this routine.
27749  *
27750  *   Arguments: dev	- the device 'dev_t'
27751  *		data	- pointer to user provided toc entry structure,
27752  *			  specifying the track # and the address format
27753  *			  (LBA or MSF).
27754  *		flag	- this argument is a pass through to ddi_copyxxx()
27755  *		          directly from the mode argument of ioctl().
27756  *
27757  * Return Code: the code returned by sd_send_scsi_cmd()
27758  *		EFAULT if ddi_copyxxx() fails
27759  *		ENXIO if fail ddi_get_soft_state
27760  *		EINVAL if data pointer is NULL
27761  */
27762 
27763 static int
27764 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
27765 {
27766 	struct sd_lun		*un = NULL;
27767 	struct uscsi_cmd	*com;
27768 	struct cdrom_tocentry	toc_entry;
27769 	struct cdrom_tocentry	*entry = &toc_entry;
27770 	caddr_t			buffer;
27771 	int			rval;
27772 	char			cdb[CDB_GROUP1];
27773 
27774 	if (data == NULL) {
27775 		return (EINVAL);
27776 	}
27777 
27778 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27779 	    (un->un_state == SD_STATE_OFFLINE)) {
27780 		return (ENXIO);
27781 	}
27782 
27783 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
27784 		return (EFAULT);
27785 	}
27786 
27787 	/* Validate the requested track and address format */
27788 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
27789 		return (EINVAL);
27790 	}
27791 
27792 	if (entry->cdte_track == 0) {
27793 		return (EINVAL);
27794 	}
27795 
27796 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
27797 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27798 	bzero(cdb, CDB_GROUP1);
27799 
27800 	cdb[0] = SCMD_READ_TOC;
27801 	/* Set the MSF bit based on the user requested address format  */
27802 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
27803 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
27804 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
27805 	} else {
27806 		cdb[6] = entry->cdte_track;
27807 	}
27808 
27809 	/*
27810 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
27811 	 * (4 byte TOC response header + 8 byte track descriptor)
27812 	 */
27813 	cdb[8] = 12;
27814 	com->uscsi_cdb	   = cdb;
27815 	com->uscsi_cdblen  = CDB_GROUP1;
27816 	com->uscsi_bufaddr = buffer;
27817 	com->uscsi_buflen  = 0x0C;
27818 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
27819 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27820 	    SD_PATH_STANDARD);
27821 	if (rval != 0) {
27822 		kmem_free(buffer, 12);
27823 		kmem_free(com, sizeof (*com));
27824 		return (rval);
27825 	}
27826 
27827 	/* Process the toc entry */
27828 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
27829 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
27830 	if (entry->cdte_format & CDROM_LBA) {
27831 		entry->cdte_addr.lba =
27832 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27833 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27834 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
27835 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
27836 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
27837 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
27838 		/*
27839 		 * Send a READ TOC command using the LBA address format to get
27840 		 * the LBA for the track requested so it can be used in the
27841 		 * READ HEADER request
27842 		 *
27843 		 * Note: The MSF bit of the READ HEADER command specifies the
27844 		 * output format. The block address specified in that command
27845 		 * must be in LBA format.
27846 		 */
27847 		cdb[1] = 0;
27848 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27849 		    SD_PATH_STANDARD);
27850 		if (rval != 0) {
27851 			kmem_free(buffer, 12);
27852 			kmem_free(com, sizeof (*com));
27853 			return (rval);
27854 		}
27855 	} else {
27856 		entry->cdte_addr.msf.minute	= buffer[9];
27857 		entry->cdte_addr.msf.second	= buffer[10];
27858 		entry->cdte_addr.msf.frame	= buffer[11];
27859 		/*
27860 		 * Send a READ TOC command using the LBA address format to get
27861 		 * the LBA for the track requested so it can be used in the
27862 		 * READ HEADER request
27863 		 *
27864 		 * Note: The MSF bit of the READ HEADER command specifies the
27865 		 * output format. The block address specified in that command
27866 		 * must be in LBA format.
27867 		 */
27868 		cdb[1] = 0;
27869 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27870 		    SD_PATH_STANDARD);
27871 		if (rval != 0) {
27872 			kmem_free(buffer, 12);
27873 			kmem_free(com, sizeof (*com));
27874 			return (rval);
27875 		}
27876 	}
27877 
27878 	/*
27879 	 * Build and send the READ HEADER command to determine the data mode of
27880 	 * the user specified track.
27881 	 */
27882 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
27883 	    (entry->cdte_track != CDROM_LEADOUT)) {
27884 		bzero(cdb, CDB_GROUP1);
27885 		cdb[0] = SCMD_READ_HEADER;
27886 		cdb[2] = buffer[8];
27887 		cdb[3] = buffer[9];
27888 		cdb[4] = buffer[10];
27889 		cdb[5] = buffer[11];
27890 		cdb[8] = 0x08;
27891 		com->uscsi_buflen = 0x08;
27892 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27893 		    SD_PATH_STANDARD);
27894 		if (rval == 0) {
27895 			entry->cdte_datamode = buffer[0];
27896 		} else {
27897 			/*
27898 			 * READ HEADER command failed, since this is
27899 			 * obsoleted in one spec, its better to return
27900 			 * -1 for an invlid track so that we can still
27901 			 * receive the rest of the TOC data.
27902 			 */
27903 			entry->cdte_datamode = (uchar_t)-1;
27904 		}
27905 	} else {
27906 		entry->cdte_datamode = (uchar_t)-1;
27907 	}
27908 
27909 	kmem_free(buffer, 12);
27910 	kmem_free(com, sizeof (*com));
27911 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
27912 		return (EFAULT);
27913 
27914 	return (rval);
27915 }
27916 
27917 
27918 /*
27919  *    Function: sr_read_tochdr()
27920  *
27921  * Description: This routine is the driver entry point for handling CD-ROM
27922  * 		ioctl requests to read the Table of Contents (TOC) header
27923  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
27924  *		and ending track numbers
27925  *
27926  *   Arguments: dev	- the device 'dev_t'
27927  *		data	- pointer to user provided toc header structure,
27928  *			  specifying the starting and ending track numbers.
27929  *		flag	- this argument is a pass through to ddi_copyxxx()
27930  *			  directly from the mode argument of ioctl().
27931  *
27932  * Return Code: the code returned by sd_send_scsi_cmd()
27933  *		EFAULT if ddi_copyxxx() fails
27934  *		ENXIO if fail ddi_get_soft_state
27935  *		EINVAL if data pointer is NULL
27936  */
27937 
27938 static int
27939 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
27940 {
27941 	struct sd_lun		*un;
27942 	struct uscsi_cmd	*com;
27943 	struct cdrom_tochdr	toc_header;
27944 	struct cdrom_tochdr	*hdr = &toc_header;
27945 	char			cdb[CDB_GROUP1];
27946 	int			rval;
27947 	caddr_t			buffer;
27948 
27949 	if (data == NULL) {
27950 		return (EINVAL);
27951 	}
27952 
27953 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27954 	    (un->un_state == SD_STATE_OFFLINE)) {
27955 		return (ENXIO);
27956 	}
27957 
27958 	buffer = kmem_zalloc(4, KM_SLEEP);
27959 	bzero(cdb, CDB_GROUP1);
27960 	cdb[0] = SCMD_READ_TOC;
27961 	/*
27962 	 * Specifying a track number of 0x00 in the READ TOC command indicates
27963 	 * that the TOC header should be returned
27964 	 */
27965 	cdb[6] = 0x00;
27966 	/*
27967 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
27968 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
27969 	 */
27970 	cdb[8] = 0x04;
27971 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27972 	com->uscsi_cdb	   = cdb;
27973 	com->uscsi_cdblen  = CDB_GROUP1;
27974 	com->uscsi_bufaddr = buffer;
27975 	com->uscsi_buflen  = 0x04;
27976 	com->uscsi_timeout = 300;
27977 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
27978 
27979 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27980 	    SD_PATH_STANDARD);
27981 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
27982 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
27983 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
27984 	} else {
27985 		hdr->cdth_trk0 = buffer[2];
27986 		hdr->cdth_trk1 = buffer[3];
27987 	}
27988 	kmem_free(buffer, 4);
27989 	kmem_free(com, sizeof (*com));
27990 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
27991 		return (EFAULT);
27992 	}
27993 	return (rval);
27994 }
27995 
27996 
27997 /*
27998  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
27999  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
28000  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
28001  * digital audio and extended architecture digital audio. These modes are
28002  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
28003  * MMC specs.
28004  *
28005  * In addition to support for the various data formats these routines also
28006  * include support for devices that implement only the direct access READ
28007  * commands (0x08, 0x28), devices that implement the READ_CD commands
28008  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
28009  * READ CDXA commands (0xD8, 0xDB)
28010  */
28011 
28012 /*
28013  *    Function: sr_read_mode1()
28014  *
28015  * Description: This routine is the driver entry point for handling CD-ROM
28016  *		ioctl read mode1 requests (CDROMREADMODE1).
28017  *
28018  *   Arguments: dev	- the device 'dev_t'
28019  *		data	- pointer to user provided cd read structure specifying
28020  *			  the lba buffer address and length.
28021  *		flag	- this argument is a pass through to ddi_copyxxx()
28022  *			  directly from the mode argument of ioctl().
28023  *
28024  * Return Code: the code returned by sd_send_scsi_cmd()
28025  *		EFAULT if ddi_copyxxx() fails
28026  *		ENXIO if fail ddi_get_soft_state
28027  *		EINVAL if data pointer is NULL
28028  */
28029 
28030 static int
28031 sr_read_mode1(dev_t dev, caddr_t data, int flag)
28032 {
28033 	struct sd_lun		*un;
28034 	struct cdrom_read	mode1_struct;
28035 	struct cdrom_read	*mode1 = &mode1_struct;
28036 	int			rval;
28037 	sd_ssc_t		*ssc;
28038 
28039 #ifdef _MULTI_DATAMODEL
28040 	/* To support ILP32 applications in an LP64 world */
28041 	struct cdrom_read32	cdrom_read32;
28042 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28043 #endif /* _MULTI_DATAMODEL */
28044 
28045 	if (data == NULL) {
28046 		return (EINVAL);
28047 	}
28048 
28049 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28050 	    (un->un_state == SD_STATE_OFFLINE)) {
28051 		return (ENXIO);
28052 	}
28053 
28054 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28055 	    "sd_read_mode1: entry: un:0x%p\n", un);
28056 
28057 #ifdef _MULTI_DATAMODEL
28058 	switch (ddi_model_convert_from(flag & FMODELS)) {
28059 	case DDI_MODEL_ILP32:
28060 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28061 			return (EFAULT);
28062 		}
28063 		/* Convert the ILP32 uscsi data from the application to LP64 */
28064 		cdrom_read32tocdrom_read(cdrd32, mode1);
28065 		break;
28066 	case DDI_MODEL_NONE:
28067 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28068 			return (EFAULT);
28069 		}
28070 	}
28071 #else /* ! _MULTI_DATAMODEL */
28072 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28073 		return (EFAULT);
28074 	}
28075 #endif /* _MULTI_DATAMODEL */
28076 
28077 	ssc = sd_ssc_init(un);
28078 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
28079 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
28080 	sd_ssc_fini(ssc);
28081 
28082 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28083 	    "sd_read_mode1: exit: un:0x%p\n", un);
28084 
28085 	return (rval);
28086 }
28087 
28088 
28089 /*
28090  *    Function: sr_read_cd_mode2()
28091  *
28092  * Description: This routine is the driver entry point for handling CD-ROM
28093  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28094  *		support the READ CD (0xBE) command or the 1st generation
28095  *		READ CD (0xD4) command.
28096  *
28097  *   Arguments: dev	- the device 'dev_t'
28098  *		data	- pointer to user provided cd read structure specifying
28099  *			  the lba buffer address and length.
28100  *		flag	- this argument is a pass through to ddi_copyxxx()
28101  *			  directly from the mode argument of ioctl().
28102  *
28103  * Return Code: the code returned by sd_send_scsi_cmd()
28104  *		EFAULT if ddi_copyxxx() fails
28105  *		ENXIO if fail ddi_get_soft_state
28106  *		EINVAL if data pointer is NULL
28107  */
28108 
28109 static int
28110 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
28111 {
28112 	struct sd_lun		*un;
28113 	struct uscsi_cmd	*com;
28114 	struct cdrom_read	mode2_struct;
28115 	struct cdrom_read	*mode2 = &mode2_struct;
28116 	uchar_t			cdb[CDB_GROUP5];
28117 	int			nblocks;
28118 	int			rval;
28119 #ifdef _MULTI_DATAMODEL
28120 	/*  To support ILP32 applications in an LP64 world */
28121 	struct cdrom_read32	cdrom_read32;
28122 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28123 #endif /* _MULTI_DATAMODEL */
28124 
28125 	if (data == NULL) {
28126 		return (EINVAL);
28127 	}
28128 
28129 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28130 	    (un->un_state == SD_STATE_OFFLINE)) {
28131 		return (ENXIO);
28132 	}
28133 
28134 #ifdef _MULTI_DATAMODEL
28135 	switch (ddi_model_convert_from(flag & FMODELS)) {
28136 	case DDI_MODEL_ILP32:
28137 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28138 			return (EFAULT);
28139 		}
28140 		/* Convert the ILP32 uscsi data from the application to LP64 */
28141 		cdrom_read32tocdrom_read(cdrd32, mode2);
28142 		break;
28143 	case DDI_MODEL_NONE:
28144 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28145 			return (EFAULT);
28146 		}
28147 		break;
28148 	}
28149 
28150 #else /* ! _MULTI_DATAMODEL */
28151 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28152 		return (EFAULT);
28153 	}
28154 #endif /* _MULTI_DATAMODEL */
28155 
28156 	bzero(cdb, sizeof (cdb));
28157 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
28158 		/* Read command supported by 1st generation atapi drives */
28159 		cdb[0] = SCMD_READ_CDD4;
28160 	} else {
28161 		/* Universal CD Access Command */
28162 		cdb[0] = SCMD_READ_CD;
28163 	}
28164 
28165 	/*
28166 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
28167 	 */
28168 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
28169 
28170 	/* set the start address */
28171 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
28172 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
28173 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28174 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
28175 
28176 	/* set the transfer length */
28177 	nblocks = mode2->cdread_buflen / 2336;
28178 	cdb[6] = (uchar_t)(nblocks >> 16);
28179 	cdb[7] = (uchar_t)(nblocks >> 8);
28180 	cdb[8] = (uchar_t)nblocks;
28181 
28182 	/* set the filter bits */
28183 	cdb[9] = CDROM_READ_CD_USERDATA;
28184 
28185 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28186 	com->uscsi_cdb = (caddr_t)cdb;
28187 	com->uscsi_cdblen = sizeof (cdb);
28188 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28189 	com->uscsi_buflen = mode2->cdread_buflen;
28190 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28191 
28192 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28193 	    SD_PATH_STANDARD);
28194 	kmem_free(com, sizeof (*com));
28195 	return (rval);
28196 }
28197 
28198 
28199 /*
28200  *    Function: sr_read_mode2()
28201  *
28202  * Description: This routine is the driver entry point for handling CD-ROM
28203  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28204  *		do not support the READ CD (0xBE) command.
28205  *
28206  *   Arguments: dev	- the device 'dev_t'
28207  *		data	- pointer to user provided cd read structure specifying
28208  *			  the lba buffer address and length.
28209  *		flag	- this argument is a pass through to ddi_copyxxx()
28210  *			  directly from the mode argument of ioctl().
28211  *
28212  * Return Code: the code returned by sd_send_scsi_cmd()
28213  *		EFAULT if ddi_copyxxx() fails
28214  *		ENXIO if fail ddi_get_soft_state
28215  *		EINVAL if data pointer is NULL
28216  *		EIO if fail to reset block size
28217  *		EAGAIN if commands are in progress in the driver
28218  */
28219 
28220 static int
28221 sr_read_mode2(dev_t dev, caddr_t data, int flag)
28222 {
28223 	struct sd_lun		*un;
28224 	struct cdrom_read	mode2_struct;
28225 	struct cdrom_read	*mode2 = &mode2_struct;
28226 	int			rval;
28227 	uint32_t		restore_blksize;
28228 	struct uscsi_cmd	*com;
28229 	uchar_t			cdb[CDB_GROUP0];
28230 	int			nblocks;
28231 
28232 #ifdef _MULTI_DATAMODEL
28233 	/* To support ILP32 applications in an LP64 world */
28234 	struct cdrom_read32	cdrom_read32;
28235 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28236 #endif /* _MULTI_DATAMODEL */
28237 
28238 	if (data == NULL) {
28239 		return (EINVAL);
28240 	}
28241 
28242 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28243 	    (un->un_state == SD_STATE_OFFLINE)) {
28244 		return (ENXIO);
28245 	}
28246 
28247 	/*
28248 	 * Because this routine will update the device and driver block size
28249 	 * being used we want to make sure there are no commands in progress.
28250 	 * If commands are in progress the user will have to try again.
28251 	 *
28252 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
28253 	 * in sdioctl to protect commands from sdioctl through to the top of
28254 	 * sd_uscsi_strategy. See sdioctl for details.
28255 	 */
28256 	mutex_enter(SD_MUTEX(un));
28257 	if (un->un_ncmds_in_driver != 1) {
28258 		mutex_exit(SD_MUTEX(un));
28259 		return (EAGAIN);
28260 	}
28261 	mutex_exit(SD_MUTEX(un));
28262 
28263 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28264 	    "sd_read_mode2: entry: un:0x%p\n", un);
28265 
28266 #ifdef _MULTI_DATAMODEL
28267 	switch (ddi_model_convert_from(flag & FMODELS)) {
28268 	case DDI_MODEL_ILP32:
28269 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28270 			return (EFAULT);
28271 		}
28272 		/* Convert the ILP32 uscsi data from the application to LP64 */
28273 		cdrom_read32tocdrom_read(cdrd32, mode2);
28274 		break;
28275 	case DDI_MODEL_NONE:
28276 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28277 			return (EFAULT);
28278 		}
28279 		break;
28280 	}
28281 #else /* ! _MULTI_DATAMODEL */
28282 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
28283 		return (EFAULT);
28284 	}
28285 #endif /* _MULTI_DATAMODEL */
28286 
28287 	/* Store the current target block size for restoration later */
28288 	restore_blksize = un->un_tgt_blocksize;
28289 
28290 	/* Change the device and soft state target block size to 2336 */
28291 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
28292 		rval = EIO;
28293 		goto done;
28294 	}
28295 
28296 
28297 	bzero(cdb, sizeof (cdb));
28298 
28299 	/* set READ operation */
28300 	cdb[0] = SCMD_READ;
28301 
28302 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
28303 	mode2->cdread_lba >>= 2;
28304 
28305 	/* set the start address */
28306 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
28307 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28308 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
28309 
28310 	/* set the transfer length */
28311 	nblocks = mode2->cdread_buflen / 2336;
28312 	cdb[4] = (uchar_t)nblocks & 0xFF;
28313 
28314 	/* build command */
28315 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28316 	com->uscsi_cdb = (caddr_t)cdb;
28317 	com->uscsi_cdblen = sizeof (cdb);
28318 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28319 	com->uscsi_buflen = mode2->cdread_buflen;
28320 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28321 
28322 	/*
28323 	 * Issue SCSI command with user space address for read buffer.
28324 	 *
28325 	 * This sends the command through main channel in the driver.
28326 	 *
28327 	 * Since this is accessed via an IOCTL call, we go through the
28328 	 * standard path, so that if the device was powered down, then
28329 	 * it would be 'awakened' to handle the command.
28330 	 */
28331 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28332 	    SD_PATH_STANDARD);
28333 
28334 	kmem_free(com, sizeof (*com));
28335 
28336 	/* Restore the device and soft state target block size */
28337 	if (sr_sector_mode(dev, restore_blksize) != 0) {
28338 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28339 		    "can't do switch back to mode 1\n");
28340 		/*
28341 		 * If sd_send_scsi_READ succeeded we still need to report
28342 		 * an error because we failed to reset the block size
28343 		 */
28344 		if (rval == 0) {
28345 			rval = EIO;
28346 		}
28347 	}
28348 
28349 done:
28350 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28351 	    "sd_read_mode2: exit: un:0x%p\n", un);
28352 
28353 	return (rval);
28354 }
28355 
28356 
28357 /*
28358  *    Function: sr_sector_mode()
28359  *
28360  * Description: This utility function is used by sr_read_mode2 to set the target
28361  *		block size based on the user specified size. This is a legacy
28362  *		implementation based upon a vendor specific mode page
28363  *
28364  *   Arguments: dev	- the device 'dev_t'
28365  *		data	- flag indicating if block size is being set to 2336 or
28366  *			  512.
28367  *
28368  * Return Code: the code returned by sd_send_scsi_cmd()
28369  *		EFAULT if ddi_copyxxx() fails
28370  *		ENXIO if fail ddi_get_soft_state
28371  *		EINVAL if data pointer is NULL
28372  */
28373 
28374 static int
28375 sr_sector_mode(dev_t dev, uint32_t blksize)
28376 {
28377 	struct sd_lun	*un;
28378 	uchar_t		*sense;
28379 	uchar_t		*select;
28380 	int		rval;
28381 	sd_ssc_t	*ssc;
28382 
28383 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28384 	    (un->un_state == SD_STATE_OFFLINE)) {
28385 		return (ENXIO);
28386 	}
28387 
28388 	sense = kmem_zalloc(20, KM_SLEEP);
28389 
28390 	/* Note: This is a vendor specific mode page (0x81) */
28391 	ssc = sd_ssc_init(un);
28392 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
28393 	    SD_PATH_STANDARD);
28394 	sd_ssc_fini(ssc);
28395 	if (rval != 0) {
28396 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28397 		    "sr_sector_mode: Mode Sense failed\n");
28398 		kmem_free(sense, 20);
28399 		return (rval);
28400 	}
28401 	select = kmem_zalloc(20, KM_SLEEP);
28402 	select[3] = 0x08;
28403 	select[10] = ((blksize >> 8) & 0xff);
28404 	select[11] = (blksize & 0xff);
28405 	select[12] = 0x01;
28406 	select[13] = 0x06;
28407 	select[14] = sense[14];
28408 	select[15] = sense[15];
28409 	if (blksize == SD_MODE2_BLKSIZE) {
28410 		select[14] |= 0x01;
28411 	}
28412 
28413 	ssc = sd_ssc_init(un);
28414 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
28415 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28416 	sd_ssc_fini(ssc);
28417 	if (rval != 0) {
28418 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28419 		    "sr_sector_mode: Mode Select failed\n");
28420 	} else {
28421 		/*
28422 		 * Only update the softstate block size if we successfully
28423 		 * changed the device block mode.
28424 		 */
28425 		mutex_enter(SD_MUTEX(un));
28426 		sd_update_block_info(un, blksize, 0);
28427 		mutex_exit(SD_MUTEX(un));
28428 	}
28429 	kmem_free(sense, 20);
28430 	kmem_free(select, 20);
28431 	return (rval);
28432 }
28433 
28434 
28435 /*
28436  *    Function: sr_read_cdda()
28437  *
28438  * Description: This routine is the driver entry point for handling CD-ROM
28439  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
28440  *		the target supports CDDA these requests are handled via a vendor
28441  *		specific command (0xD8) If the target does not support CDDA
28442  *		these requests are handled via the READ CD command (0xBE).
28443  *
28444  *   Arguments: dev	- the device 'dev_t'
28445  *		data	- pointer to user provided CD-DA structure specifying
28446  *			  the track starting address, transfer length, and
28447  *			  subcode options.
28448  *		flag	- this argument is a pass through to ddi_copyxxx()
28449  *			  directly from the mode argument of ioctl().
28450  *
28451  * Return Code: the code returned by sd_send_scsi_cmd()
28452  *		EFAULT if ddi_copyxxx() fails
28453  *		ENXIO if fail ddi_get_soft_state
28454  *		EINVAL if invalid arguments are provided
28455  *		ENOTTY
28456  */
28457 
28458 static int
28459 sr_read_cdda(dev_t dev, caddr_t data, int flag)
28460 {
28461 	struct sd_lun			*un;
28462 	struct uscsi_cmd		*com;
28463 	struct cdrom_cdda		*cdda;
28464 	int				rval;
28465 	size_t				buflen;
28466 	char				cdb[CDB_GROUP5];
28467 
28468 #ifdef _MULTI_DATAMODEL
28469 	/* To support ILP32 applications in an LP64 world */
28470 	struct cdrom_cdda32	cdrom_cdda32;
28471 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
28472 #endif /* _MULTI_DATAMODEL */
28473 
28474 	if (data == NULL) {
28475 		return (EINVAL);
28476 	}
28477 
28478 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28479 		return (ENXIO);
28480 	}
28481 
28482 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
28483 
28484 #ifdef _MULTI_DATAMODEL
28485 	switch (ddi_model_convert_from(flag & FMODELS)) {
28486 	case DDI_MODEL_ILP32:
28487 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
28488 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28489 			    "sr_read_cdda: ddi_copyin Failed\n");
28490 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28491 			return (EFAULT);
28492 		}
28493 		/* Convert the ILP32 uscsi data from the application to LP64 */
28494 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
28495 		break;
28496 	case DDI_MODEL_NONE:
28497 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28498 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28499 			    "sr_read_cdda: ddi_copyin Failed\n");
28500 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28501 			return (EFAULT);
28502 		}
28503 		break;
28504 	}
28505 #else /* ! _MULTI_DATAMODEL */
28506 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28507 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28508 		    "sr_read_cdda: ddi_copyin Failed\n");
28509 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28510 		return (EFAULT);
28511 	}
28512 #endif /* _MULTI_DATAMODEL */
28513 
28514 	/*
28515 	 * Since MMC-2 expects max 3 bytes for length, check if the
28516 	 * length input is greater than 3 bytes
28517 	 */
28518 	if ((cdda->cdda_length & 0xFF000000) != 0) {
28519 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
28520 		    "cdrom transfer length too large: %d (limit %d)\n",
28521 		    cdda->cdda_length, 0xFFFFFF);
28522 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28523 		return (EINVAL);
28524 	}
28525 
28526 	switch (cdda->cdda_subcode) {
28527 	case CDROM_DA_NO_SUBCODE:
28528 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
28529 		break;
28530 	case CDROM_DA_SUBQ:
28531 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
28532 		break;
28533 	case CDROM_DA_ALL_SUBCODE:
28534 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
28535 		break;
28536 	case CDROM_DA_SUBCODE_ONLY:
28537 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
28538 		break;
28539 	default:
28540 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28541 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
28542 		    cdda->cdda_subcode);
28543 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28544 		return (EINVAL);
28545 	}
28546 
28547 	/* Build and send the command */
28548 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28549 	bzero(cdb, CDB_GROUP5);
28550 
28551 	if (un->un_f_cfg_cdda == TRUE) {
28552 		cdb[0] = (char)SCMD_READ_CD;
28553 		cdb[1] = 0x04;
28554 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28555 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28556 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28557 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28558 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28559 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28560 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
28561 		cdb[9] = 0x10;
28562 		switch (cdda->cdda_subcode) {
28563 		case CDROM_DA_NO_SUBCODE :
28564 			cdb[10] = 0x0;
28565 			break;
28566 		case CDROM_DA_SUBQ :
28567 			cdb[10] = 0x2;
28568 			break;
28569 		case CDROM_DA_ALL_SUBCODE :
28570 			cdb[10] = 0x1;
28571 			break;
28572 		case CDROM_DA_SUBCODE_ONLY :
28573 			/* FALLTHROUGH */
28574 		default :
28575 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28576 			kmem_free(com, sizeof (*com));
28577 			return (ENOTTY);
28578 		}
28579 	} else {
28580 		cdb[0] = (char)SCMD_READ_CDDA;
28581 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28582 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28583 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28584 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28585 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
28586 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28587 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28588 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
28589 		cdb[10] = cdda->cdda_subcode;
28590 	}
28591 
28592 	com->uscsi_cdb = cdb;
28593 	com->uscsi_cdblen = CDB_GROUP5;
28594 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
28595 	com->uscsi_buflen = buflen;
28596 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28597 
28598 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28599 	    SD_PATH_STANDARD);
28600 
28601 	kmem_free(cdda, sizeof (struct cdrom_cdda));
28602 	kmem_free(com, sizeof (*com));
28603 	return (rval);
28604 }
28605 
28606 
28607 /*
28608  *    Function: sr_read_cdxa()
28609  *
28610  * Description: This routine is the driver entry point for handling CD-ROM
28611  *		ioctl requests to return CD-XA (Extended Architecture) data.
28612  *		(CDROMCDXA).
28613  *
28614  *   Arguments: dev	- the device 'dev_t'
28615  *		data	- pointer to user provided CD-XA structure specifying
28616  *			  the data starting address, transfer length, and format
28617  *		flag	- this argument is a pass through to ddi_copyxxx()
28618  *			  directly from the mode argument of ioctl().
28619  *
28620  * Return Code: the code returned by sd_send_scsi_cmd()
28621  *		EFAULT if ddi_copyxxx() fails
28622  *		ENXIO if fail ddi_get_soft_state
28623  *		EINVAL if data pointer is NULL
28624  */
28625 
28626 static int
28627 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
28628 {
28629 	struct sd_lun		*un;
28630 	struct uscsi_cmd	*com;
28631 	struct cdrom_cdxa	*cdxa;
28632 	int			rval;
28633 	size_t			buflen;
28634 	char			cdb[CDB_GROUP5];
28635 	uchar_t			read_flags;
28636 
28637 #ifdef _MULTI_DATAMODEL
28638 	/* To support ILP32 applications in an LP64 world */
28639 	struct cdrom_cdxa32		cdrom_cdxa32;
28640 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
28641 #endif /* _MULTI_DATAMODEL */
28642 
28643 	if (data == NULL) {
28644 		return (EINVAL);
28645 	}
28646 
28647 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28648 		return (ENXIO);
28649 	}
28650 
28651 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
28652 
28653 #ifdef _MULTI_DATAMODEL
28654 	switch (ddi_model_convert_from(flag & FMODELS)) {
28655 	case DDI_MODEL_ILP32:
28656 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
28657 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28658 			return (EFAULT);
28659 		}
28660 		/*
28661 		 * Convert the ILP32 uscsi data from the
28662 		 * application to LP64 for internal use.
28663 		 */
28664 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
28665 		break;
28666 	case DDI_MODEL_NONE:
28667 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28668 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28669 			return (EFAULT);
28670 		}
28671 		break;
28672 	}
28673 #else /* ! _MULTI_DATAMODEL */
28674 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28675 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28676 		return (EFAULT);
28677 	}
28678 #endif /* _MULTI_DATAMODEL */
28679 
28680 	/*
28681 	 * Since MMC-2 expects max 3 bytes for length, check if the
28682 	 * length input is greater than 3 bytes
28683 	 */
28684 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
28685 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
28686 		    "cdrom transfer length too large: %d (limit %d)\n",
28687 		    cdxa->cdxa_length, 0xFFFFFF);
28688 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28689 		return (EINVAL);
28690 	}
28691 
28692 	switch (cdxa->cdxa_format) {
28693 	case CDROM_XA_DATA:
28694 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
28695 		read_flags = 0x10;
28696 		break;
28697 	case CDROM_XA_SECTOR_DATA:
28698 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
28699 		read_flags = 0xf8;
28700 		break;
28701 	case CDROM_XA_DATA_W_ERROR:
28702 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
28703 		read_flags = 0xfc;
28704 		break;
28705 	default:
28706 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28707 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
28708 		    cdxa->cdxa_format);
28709 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28710 		return (EINVAL);
28711 	}
28712 
28713 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28714 	bzero(cdb, CDB_GROUP5);
28715 	if (un->un_f_mmc_cap == TRUE) {
28716 		cdb[0] = (char)SCMD_READ_CD;
28717 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28718 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28719 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28720 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28721 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28722 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28723 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
28724 		cdb[9] = (char)read_flags;
28725 	} else {
28726 		/*
28727 		 * Note: A vendor specific command (0xDB) is being used her to
28728 		 * request a read of all subcodes.
28729 		 */
28730 		cdb[0] = (char)SCMD_READ_CDXA;
28731 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28732 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28733 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28734 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28735 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
28736 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28737 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28738 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
28739 		cdb[10] = cdxa->cdxa_format;
28740 	}
28741 	com->uscsi_cdb	   = cdb;
28742 	com->uscsi_cdblen  = CDB_GROUP5;
28743 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
28744 	com->uscsi_buflen  = buflen;
28745 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
28746 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28747 	    SD_PATH_STANDARD);
28748 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28749 	kmem_free(com, sizeof (*com));
28750 	return (rval);
28751 }
28752 
28753 
28754 /*
28755  *    Function: sr_eject()
28756  *
28757  * Description: This routine is the driver entry point for handling CD-ROM
28758  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
28759  *
28760  *   Arguments: dev	- the device 'dev_t'
28761  *
28762  * Return Code: the code returned by sd_send_scsi_cmd()
28763  */
28764 
28765 static int
28766 sr_eject(dev_t dev)
28767 {
28768 	struct sd_lun	*un;
28769 	int		rval;
28770 	sd_ssc_t	*ssc;
28771 
28772 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28773 	    (un->un_state == SD_STATE_OFFLINE)) {
28774 		return (ENXIO);
28775 	}
28776 
28777 	/*
28778 	 * To prevent race conditions with the eject
28779 	 * command, keep track of an eject command as
28780 	 * it progresses. If we are already handling
28781 	 * an eject command in the driver for the given
28782 	 * unit and another request to eject is received
28783 	 * immediately return EAGAIN so we don't lose
28784 	 * the command if the current eject command fails.
28785 	 */
28786 	mutex_enter(SD_MUTEX(un));
28787 	if (un->un_f_ejecting == TRUE) {
28788 		mutex_exit(SD_MUTEX(un));
28789 		return (EAGAIN);
28790 	}
28791 	un->un_f_ejecting = TRUE;
28792 	mutex_exit(SD_MUTEX(un));
28793 
28794 	ssc = sd_ssc_init(un);
28795 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
28796 	    SD_PATH_STANDARD);
28797 	sd_ssc_fini(ssc);
28798 
28799 	if (rval != 0) {
28800 		mutex_enter(SD_MUTEX(un));
28801 		un->un_f_ejecting = FALSE;
28802 		mutex_exit(SD_MUTEX(un));
28803 		return (rval);
28804 	}
28805 
28806 	ssc = sd_ssc_init(un);
28807 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
28808 	    SD_TARGET_EJECT, SD_PATH_STANDARD);
28809 	sd_ssc_fini(ssc);
28810 
28811 	if (rval == 0) {
28812 		mutex_enter(SD_MUTEX(un));
28813 		sr_ejected(un);
28814 		un->un_mediastate = DKIO_EJECTED;
28815 		un->un_f_ejecting = FALSE;
28816 		cv_broadcast(&un->un_state_cv);
28817 		mutex_exit(SD_MUTEX(un));
28818 	} else {
28819 		mutex_enter(SD_MUTEX(un));
28820 		un->un_f_ejecting = FALSE;
28821 		mutex_exit(SD_MUTEX(un));
28822 	}
28823 	return (rval);
28824 }
28825 
28826 
28827 /*
28828  *    Function: sr_ejected()
28829  *
28830  * Description: This routine updates the soft state structure to invalidate the
28831  *		geometry information after the media has been ejected or a
28832  *		media eject has been detected.
28833  *
28834  *   Arguments: un - driver soft state (unit) structure
28835  */
28836 
28837 static void
28838 sr_ejected(struct sd_lun *un)
28839 {
28840 	struct sd_errstats *stp;
28841 
28842 	ASSERT(un != NULL);
28843 	ASSERT(mutex_owned(SD_MUTEX(un)));
28844 
28845 	un->un_f_blockcount_is_valid	= FALSE;
28846 	un->un_f_tgt_blocksize_is_valid	= FALSE;
28847 	mutex_exit(SD_MUTEX(un));
28848 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
28849 	mutex_enter(SD_MUTEX(un));
28850 
28851 	if (un->un_errstats != NULL) {
28852 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
28853 		stp->sd_capacity.value.ui64 = 0;
28854 	}
28855 }
28856 
28857 
28858 /*
28859  *    Function: sr_check_wp()
28860  *
28861  * Description: This routine checks the write protection of a removable
28862  *      media disk and hotpluggable devices via the write protect bit of
28863  *      the Mode Page Header device specific field. Some devices choke
28864  *      on unsupported mode page. In order to workaround this issue,
28865  *      this routine has been implemented to use 0x3f mode page(request
28866  *      for all pages) for all device types.
28867  *
28868  *   Arguments: dev             - the device 'dev_t'
28869  *
28870  * Return Code: int indicating if the device is write protected (1) or not (0)
28871  *
28872  *     Context: Kernel thread.
28873  *
28874  */
28875 
28876 static int
28877 sr_check_wp(dev_t dev)
28878 {
28879 	struct sd_lun	*un;
28880 	uchar_t		device_specific;
28881 	uchar_t		*sense;
28882 	int		hdrlen;
28883 	int		rval = FALSE;
28884 	int		status;
28885 	sd_ssc_t	*ssc;
28886 
28887 	/*
28888 	 * Note: The return codes for this routine should be reworked to
28889 	 * properly handle the case of a NULL softstate.
28890 	 */
28891 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28892 		return (FALSE);
28893 	}
28894 
28895 	if (un->un_f_cfg_is_atapi == TRUE) {
28896 		/*
28897 		 * The mode page contents are not required; set the allocation
28898 		 * length for the mode page header only
28899 		 */
28900 		hdrlen = MODE_HEADER_LENGTH_GRP2;
28901 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
28902 		ssc = sd_ssc_init(un);
28903 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
28904 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
28905 		sd_ssc_fini(ssc);
28906 		if (status != 0)
28907 			goto err_exit;
28908 		device_specific =
28909 		    ((struct mode_header_grp2 *)sense)->device_specific;
28910 	} else {
28911 		hdrlen = MODE_HEADER_LENGTH;
28912 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
28913 		ssc = sd_ssc_init(un);
28914 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
28915 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
28916 		sd_ssc_fini(ssc);
28917 		if (status != 0)
28918 			goto err_exit;
28919 		device_specific =
28920 		    ((struct mode_header *)sense)->device_specific;
28921 	}
28922 
28923 
28924 	/*
28925 	 * Write protect mode sense failed; not all disks
28926 	 * understand this query. Return FALSE assuming that
28927 	 * these devices are not writable.
28928 	 */
28929 	if (device_specific & WRITE_PROTECT) {
28930 		rval = TRUE;
28931 	}
28932 
28933 err_exit:
28934 	kmem_free(sense, hdrlen);
28935 	return (rval);
28936 }
28937 
28938 /*
28939  *    Function: sr_volume_ctrl()
28940  *
28941  * Description: This routine is the driver entry point for handling CD-ROM
28942  *		audio output volume ioctl requests. (CDROMVOLCTRL)
28943  *
28944  *   Arguments: dev	- the device 'dev_t'
28945  *		data	- pointer to user audio volume control structure
28946  *		flag	- this argument is a pass through to ddi_copyxxx()
28947  *			  directly from the mode argument of ioctl().
28948  *
28949  * Return Code: the code returned by sd_send_scsi_cmd()
28950  *		EFAULT if ddi_copyxxx() fails
28951  *		ENXIO if fail ddi_get_soft_state
28952  *		EINVAL if data pointer is NULL
28953  *
28954  */
28955 
28956 static int
28957 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
28958 {
28959 	struct sd_lun		*un;
28960 	struct cdrom_volctrl    volume;
28961 	struct cdrom_volctrl    *vol = &volume;
28962 	uchar_t			*sense_page;
28963 	uchar_t			*select_page;
28964 	uchar_t			*sense;
28965 	uchar_t			*select;
28966 	int			sense_buflen;
28967 	int			select_buflen;
28968 	int			rval;
28969 	sd_ssc_t		*ssc;
28970 
28971 	if (data == NULL) {
28972 		return (EINVAL);
28973 	}
28974 
28975 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28976 	    (un->un_state == SD_STATE_OFFLINE)) {
28977 		return (ENXIO);
28978 	}
28979 
28980 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
28981 		return (EFAULT);
28982 	}
28983 
28984 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
28985 		struct mode_header_grp2		*sense_mhp;
28986 		struct mode_header_grp2		*select_mhp;
28987 		int				bd_len;
28988 
28989 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
28990 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
28991 		    MODEPAGE_AUDIO_CTRL_LEN;
28992 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
28993 		select = kmem_zalloc(select_buflen, KM_SLEEP);
28994 		ssc = sd_ssc_init(un);
28995 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
28996 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
28997 		    SD_PATH_STANDARD);
28998 		sd_ssc_fini(ssc);
28999 
29000 		if (rval != 0) {
29001 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
29002 			    "sr_volume_ctrl: Mode Sense Failed\n");
29003 			kmem_free(sense, sense_buflen);
29004 			kmem_free(select, select_buflen);
29005 			return (rval);
29006 		}
29007 		sense_mhp = (struct mode_header_grp2 *)sense;
29008 		select_mhp = (struct mode_header_grp2 *)select;
29009 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
29010 		    sense_mhp->bdesc_length_lo;
29011 		if (bd_len > MODE_BLK_DESC_LENGTH) {
29012 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29013 			    "sr_volume_ctrl: Mode Sense returned invalid "
29014 			    "block descriptor length\n");
29015 			kmem_free(sense, sense_buflen);
29016 			kmem_free(select, select_buflen);
29017 			return (EIO);
29018 		}
29019 		sense_page = (uchar_t *)
29020 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
29021 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
29022 		select_mhp->length_msb = 0;
29023 		select_mhp->length_lsb = 0;
29024 		select_mhp->bdesc_length_hi = 0;
29025 		select_mhp->bdesc_length_lo = 0;
29026 	} else {
29027 		struct mode_header		*sense_mhp, *select_mhp;
29028 
29029 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29030 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29031 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29032 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29033 		ssc = sd_ssc_init(un);
29034 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
29035 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29036 		    SD_PATH_STANDARD);
29037 		sd_ssc_fini(ssc);
29038 
29039 		if (rval != 0) {
29040 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29041 			    "sr_volume_ctrl: Mode Sense Failed\n");
29042 			kmem_free(sense, sense_buflen);
29043 			kmem_free(select, select_buflen);
29044 			return (rval);
29045 		}
29046 		sense_mhp  = (struct mode_header *)sense;
29047 		select_mhp = (struct mode_header *)select;
29048 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
29049 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29050 			    "sr_volume_ctrl: Mode Sense returned invalid "
29051 			    "block descriptor length\n");
29052 			kmem_free(sense, sense_buflen);
29053 			kmem_free(select, select_buflen);
29054 			return (EIO);
29055 		}
29056 		sense_page = (uchar_t *)
29057 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
29058 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
29059 		select_mhp->length = 0;
29060 		select_mhp->bdesc_length = 0;
29061 	}
29062 	/*
29063 	 * Note: An audio control data structure could be created and overlayed
29064 	 * on the following in place of the array indexing method implemented.
29065 	 */
29066 
29067 	/* Build the select data for the user volume data */
29068 	select_page[0] = MODEPAGE_AUDIO_CTRL;
29069 	select_page[1] = 0xE;
29070 	/* Set the immediate bit */
29071 	select_page[2] = 0x04;
29072 	/* Zero out reserved fields */
29073 	select_page[3] = 0x00;
29074 	select_page[4] = 0x00;
29075 	/* Return sense data for fields not to be modified */
29076 	select_page[5] = sense_page[5];
29077 	select_page[6] = sense_page[6];
29078 	select_page[7] = sense_page[7];
29079 	/* Set the user specified volume levels for channel 0 and 1 */
29080 	select_page[8] = 0x01;
29081 	select_page[9] = vol->channel0;
29082 	select_page[10] = 0x02;
29083 	select_page[11] = vol->channel1;
29084 	/* Channel 2 and 3 are currently unsupported so return the sense data */
29085 	select_page[12] = sense_page[12];
29086 	select_page[13] = sense_page[13];
29087 	select_page[14] = sense_page[14];
29088 	select_page[15] = sense_page[15];
29089 
29090 	ssc = sd_ssc_init(un);
29091 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29092 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
29093 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29094 	} else {
29095 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
29096 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29097 	}
29098 	sd_ssc_fini(ssc);
29099 
29100 	kmem_free(sense, sense_buflen);
29101 	kmem_free(select, select_buflen);
29102 	return (rval);
29103 }
29104 
29105 
29106 /*
29107  *    Function: sr_read_sony_session_offset()
29108  *
29109  * Description: This routine is the driver entry point for handling CD-ROM
29110  *		ioctl requests for session offset information. (CDROMREADOFFSET)
29111  *		The address of the first track in the last session of a
29112  *		multi-session CD-ROM is returned
29113  *
29114  *		Note: This routine uses a vendor specific key value in the
29115  *		command control field without implementing any vendor check here
29116  *		or in the ioctl routine.
29117  *
29118  *   Arguments: dev	- the device 'dev_t'
29119  *		data	- pointer to an int to hold the requested address
29120  *		flag	- this argument is a pass through to ddi_copyxxx()
29121  *			  directly from the mode argument of ioctl().
29122  *
29123  * Return Code: the code returned by sd_send_scsi_cmd()
29124  *		EFAULT if ddi_copyxxx() fails
29125  *		ENXIO if fail ddi_get_soft_state
29126  *		EINVAL if data pointer is NULL
29127  */
29128 
29129 static int
29130 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
29131 {
29132 	struct sd_lun		*un;
29133 	struct uscsi_cmd	*com;
29134 	caddr_t			buffer;
29135 	char			cdb[CDB_GROUP1];
29136 	int			session_offset = 0;
29137 	int			rval;
29138 
29139 	if (data == NULL) {
29140 		return (EINVAL);
29141 	}
29142 
29143 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29144 	    (un->un_state == SD_STATE_OFFLINE)) {
29145 		return (ENXIO);
29146 	}
29147 
29148 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
29149 	bzero(cdb, CDB_GROUP1);
29150 	cdb[0] = SCMD_READ_TOC;
29151 	/*
29152 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
29153 	 * (4 byte TOC response header + 8 byte response data)
29154 	 */
29155 	cdb[8] = SONY_SESSION_OFFSET_LEN;
29156 	/* Byte 9 is the control byte. A vendor specific value is used */
29157 	cdb[9] = SONY_SESSION_OFFSET_KEY;
29158 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
29159 	com->uscsi_cdb = cdb;
29160 	com->uscsi_cdblen = CDB_GROUP1;
29161 	com->uscsi_bufaddr = buffer;
29162 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
29163 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
29164 
29165 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
29166 	    SD_PATH_STANDARD);
29167 	if (rval != 0) {
29168 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29169 		kmem_free(com, sizeof (*com));
29170 		return (rval);
29171 	}
29172 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
29173 		session_offset =
29174 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
29175 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
29176 		/*
29177 		 * Offset returned offset in current lbasize block's. Convert to
29178 		 * 2k block's to return to the user
29179 		 */
29180 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
29181 			session_offset >>= 2;
29182 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
29183 			session_offset >>= 1;
29184 		}
29185 	}
29186 
29187 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
29188 		rval = EFAULT;
29189 	}
29190 
29191 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29192 	kmem_free(com, sizeof (*com));
29193 	return (rval);
29194 }
29195 
29196 
29197 /*
29198  *    Function: sd_wm_cache_constructor()
29199  *
29200  * Description: Cache Constructor for the wmap cache for the read/modify/write
29201  * 		devices.
29202  *
29203  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29204  *		un	- sd_lun structure for the device.
29205  *		flag	- the km flags passed to constructor
29206  *
29207  * Return Code: 0 on success.
29208  *		-1 on failure.
29209  */
29210 
29211 /*ARGSUSED*/
29212 static int
29213 sd_wm_cache_constructor(void *wm, void *un, int flags)
29214 {
29215 	bzero(wm, sizeof (struct sd_w_map));
29216 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
29217 	return (0);
29218 }
29219 
29220 
29221 /*
29222  *    Function: sd_wm_cache_destructor()
29223  *
29224  * Description: Cache destructor for the wmap cache for the read/modify/write
29225  * 		devices.
29226  *
29227  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29228  *		un	- sd_lun structure for the device.
29229  */
29230 /*ARGSUSED*/
29231 static void
29232 sd_wm_cache_destructor(void *wm, void *un)
29233 {
29234 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
29235 }
29236 
29237 
29238 /*
29239  *    Function: sd_range_lock()
29240  *
29241  * Description: Lock the range of blocks specified as parameter to ensure
29242  *		that read, modify write is atomic and no other i/o writes
29243  *		to the same location. The range is specified in terms
29244  *		of start and end blocks. Block numbers are the actual
29245  *		media block numbers and not system.
29246  *
29247  *   Arguments: un	- sd_lun structure for the device.
29248  *		startb - The starting block number
29249  *		endb - The end block number
29250  *		typ - type of i/o - simple/read_modify_write
29251  *
29252  * Return Code: wm  - pointer to the wmap structure.
29253  *
29254  *     Context: This routine can sleep.
29255  */
29256 
29257 static struct sd_w_map *
29258 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
29259 {
29260 	struct sd_w_map *wmp = NULL;
29261 	struct sd_w_map *sl_wmp = NULL;
29262 	struct sd_w_map *tmp_wmp;
29263 	wm_state state = SD_WM_CHK_LIST;
29264 
29265 
29266 	ASSERT(un != NULL);
29267 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29268 
29269 	mutex_enter(SD_MUTEX(un));
29270 
29271 	while (state != SD_WM_DONE) {
29272 
29273 		switch (state) {
29274 		case SD_WM_CHK_LIST:
29275 			/*
29276 			 * This is the starting state. Check the wmap list
29277 			 * to see if the range is currently available.
29278 			 */
29279 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
29280 				/*
29281 				 * If this is a simple write and no rmw
29282 				 * i/o is pending then try to lock the
29283 				 * range as the range should be available.
29284 				 */
29285 				state = SD_WM_LOCK_RANGE;
29286 			} else {
29287 				tmp_wmp = sd_get_range(un, startb, endb);
29288 				if (tmp_wmp != NULL) {
29289 					if ((wmp != NULL) && ONLIST(un, wmp)) {
29290 						/*
29291 						 * Should not keep onlist wmps
29292 						 * while waiting this macro
29293 						 * will also do wmp = NULL;
29294 						 */
29295 						FREE_ONLIST_WMAP(un, wmp);
29296 					}
29297 					/*
29298 					 * sl_wmp is the wmap on which wait
29299 					 * is done, since the tmp_wmp points
29300 					 * to the inuse wmap, set sl_wmp to
29301 					 * tmp_wmp and change the state to sleep
29302 					 */
29303 					sl_wmp = tmp_wmp;
29304 					state = SD_WM_WAIT_MAP;
29305 				} else {
29306 					state = SD_WM_LOCK_RANGE;
29307 				}
29308 
29309 			}
29310 			break;
29311 
29312 		case SD_WM_LOCK_RANGE:
29313 			ASSERT(un->un_wm_cache);
29314 			/*
29315 			 * The range need to be locked, try to get a wmap.
29316 			 * First attempt it with NO_SLEEP, want to avoid a sleep
29317 			 * if possible as we will have to release the sd mutex
29318 			 * if we have to sleep.
29319 			 */
29320 			if (wmp == NULL)
29321 				wmp = kmem_cache_alloc(un->un_wm_cache,
29322 				    KM_NOSLEEP);
29323 			if (wmp == NULL) {
29324 				mutex_exit(SD_MUTEX(un));
29325 				_NOTE(DATA_READABLE_WITHOUT_LOCK
29326 				    (sd_lun::un_wm_cache))
29327 				wmp = kmem_cache_alloc(un->un_wm_cache,
29328 				    KM_SLEEP);
29329 				mutex_enter(SD_MUTEX(un));
29330 				/*
29331 				 * we released the mutex so recheck and go to
29332 				 * check list state.
29333 				 */
29334 				state = SD_WM_CHK_LIST;
29335 			} else {
29336 				/*
29337 				 * We exit out of state machine since we
29338 				 * have the wmap. Do the housekeeping first.
29339 				 * place the wmap on the wmap list if it is not
29340 				 * on it already and then set the state to done.
29341 				 */
29342 				wmp->wm_start = startb;
29343 				wmp->wm_end = endb;
29344 				wmp->wm_flags = typ | SD_WM_BUSY;
29345 				if (typ & SD_WTYPE_RMW) {
29346 					un->un_rmw_count++;
29347 				}
29348 				/*
29349 				 * If not already on the list then link
29350 				 */
29351 				if (!ONLIST(un, wmp)) {
29352 					wmp->wm_next = un->un_wm;
29353 					wmp->wm_prev = NULL;
29354 					if (wmp->wm_next)
29355 						wmp->wm_next->wm_prev = wmp;
29356 					un->un_wm = wmp;
29357 				}
29358 				state = SD_WM_DONE;
29359 			}
29360 			break;
29361 
29362 		case SD_WM_WAIT_MAP:
29363 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
29364 			/*
29365 			 * Wait is done on sl_wmp, which is set in the
29366 			 * check_list state.
29367 			 */
29368 			sl_wmp->wm_wanted_count++;
29369 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
29370 			sl_wmp->wm_wanted_count--;
29371 			/*
29372 			 * We can reuse the memory from the completed sl_wmp
29373 			 * lock range for our new lock, but only if noone is
29374 			 * waiting for it.
29375 			 */
29376 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
29377 			if (sl_wmp->wm_wanted_count == 0) {
29378 				if (wmp != NULL)
29379 					CHK_N_FREEWMP(un, wmp);
29380 				wmp = sl_wmp;
29381 			}
29382 			sl_wmp = NULL;
29383 			/*
29384 			 * After waking up, need to recheck for availability of
29385 			 * range.
29386 			 */
29387 			state = SD_WM_CHK_LIST;
29388 			break;
29389 
29390 		default:
29391 			panic("sd_range_lock: "
29392 			    "Unknown state %d in sd_range_lock", state);
29393 			/*NOTREACHED*/
29394 		} /* switch(state) */
29395 
29396 	} /* while(state != SD_WM_DONE) */
29397 
29398 	mutex_exit(SD_MUTEX(un));
29399 
29400 	ASSERT(wmp != NULL);
29401 
29402 	return (wmp);
29403 }
29404 
29405 
29406 /*
29407  *    Function: sd_get_range()
29408  *
29409  * Description: Find if there any overlapping I/O to this one
29410  *		Returns the write-map of 1st such I/O, NULL otherwise.
29411  *
29412  *   Arguments: un	- sd_lun structure for the device.
29413  *		startb - The starting block number
29414  *		endb - The end block number
29415  *
29416  * Return Code: wm  - pointer to the wmap structure.
29417  */
29418 
29419 static struct sd_w_map *
29420 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
29421 {
29422 	struct sd_w_map *wmp;
29423 
29424 	ASSERT(un != NULL);
29425 
29426 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
29427 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
29428 			continue;
29429 		}
29430 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
29431 			break;
29432 		}
29433 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
29434 			break;
29435 		}
29436 	}
29437 
29438 	return (wmp);
29439 }
29440 
29441 
29442 /*
29443  *    Function: sd_free_inlist_wmap()
29444  *
29445  * Description: Unlink and free a write map struct.
29446  *
29447  *   Arguments: un      - sd_lun structure for the device.
29448  *		wmp	- sd_w_map which needs to be unlinked.
29449  */
29450 
29451 static void
29452 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
29453 {
29454 	ASSERT(un != NULL);
29455 
29456 	if (un->un_wm == wmp) {
29457 		un->un_wm = wmp->wm_next;
29458 	} else {
29459 		wmp->wm_prev->wm_next = wmp->wm_next;
29460 	}
29461 
29462 	if (wmp->wm_next) {
29463 		wmp->wm_next->wm_prev = wmp->wm_prev;
29464 	}
29465 
29466 	wmp->wm_next = wmp->wm_prev = NULL;
29467 
29468 	kmem_cache_free(un->un_wm_cache, wmp);
29469 }
29470 
29471 
29472 /*
29473  *    Function: sd_range_unlock()
29474  *
29475  * Description: Unlock the range locked by wm.
29476  *		Free write map if nobody else is waiting on it.
29477  *
29478  *   Arguments: un      - sd_lun structure for the device.
29479  *              wmp     - sd_w_map which needs to be unlinked.
29480  */
29481 
29482 static void
29483 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
29484 {
29485 	ASSERT(un != NULL);
29486 	ASSERT(wm != NULL);
29487 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29488 
29489 	mutex_enter(SD_MUTEX(un));
29490 
29491 	if (wm->wm_flags & SD_WTYPE_RMW) {
29492 		un->un_rmw_count--;
29493 	}
29494 
29495 	if (wm->wm_wanted_count) {
29496 		wm->wm_flags = 0;
29497 		/*
29498 		 * Broadcast that the wmap is available now.
29499 		 */
29500 		cv_broadcast(&wm->wm_avail);
29501 	} else {
29502 		/*
29503 		 * If no one is waiting on the map, it should be free'ed.
29504 		 */
29505 		sd_free_inlist_wmap(un, wm);
29506 	}
29507 
29508 	mutex_exit(SD_MUTEX(un));
29509 }
29510 
29511 
29512 /*
29513  *    Function: sd_read_modify_write_task
29514  *
29515  * Description: Called from a taskq thread to initiate the write phase of
29516  *		a read-modify-write request.  This is used for targets where
29517  *		un->un_sys_blocksize != un->un_tgt_blocksize.
29518  *
29519  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
29520  *
29521  *     Context: Called under taskq thread context.
29522  */
29523 
29524 static void
29525 sd_read_modify_write_task(void *arg)
29526 {
29527 	struct sd_mapblocksize_info	*bsp;
29528 	struct buf	*bp;
29529 	struct sd_xbuf	*xp;
29530 	struct sd_lun	*un;
29531 
29532 	bp = arg;	/* The bp is given in arg */
29533 	ASSERT(bp != NULL);
29534 
29535 	/* Get the pointer to the layer-private data struct */
29536 	xp = SD_GET_XBUF(bp);
29537 	ASSERT(xp != NULL);
29538 	bsp = xp->xb_private;
29539 	ASSERT(bsp != NULL);
29540 
29541 	un = SD_GET_UN(bp);
29542 	ASSERT(un != NULL);
29543 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29544 
29545 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29546 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
29547 
29548 	/*
29549 	 * This is the write phase of a read-modify-write request, called
29550 	 * under the context of a taskq thread in response to the completion
29551 	 * of the read portion of the rmw request completing under interrupt
29552 	 * context. The write request must be sent from here down the iostart
29553 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
29554 	 * we use the layer index saved in the layer-private data area.
29555 	 */
29556 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
29557 
29558 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29559 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
29560 }
29561 
29562 
29563 /*
29564  *    Function: sddump_do_read_of_rmw()
29565  *
29566  * Description: This routine will be called from sddump, If sddump is called
29567  *		with an I/O which not aligned on device blocksize boundary
29568  *		then the write has to be converted to read-modify-write.
29569  *		Do the read part here in order to keep sddump simple.
29570  *		Note - That the sd_mutex is held across the call to this
29571  *		routine.
29572  *
29573  *   Arguments: un	- sd_lun
29574  *		blkno	- block number in terms of media block size.
29575  *		nblk	- number of blocks.
29576  *		bpp	- pointer to pointer to the buf structure. On return
29577  *			from this function, *bpp points to the valid buffer
29578  *			to which the write has to be done.
29579  *
29580  * Return Code: 0 for success or errno-type return code
29581  */
29582 
29583 static int
29584 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
29585 	struct buf **bpp)
29586 {
29587 	int err;
29588 	int i;
29589 	int rval;
29590 	struct buf *bp;
29591 	struct scsi_pkt *pkt = NULL;
29592 	uint32_t target_blocksize;
29593 
29594 	ASSERT(un != NULL);
29595 	ASSERT(mutex_owned(SD_MUTEX(un)));
29596 
29597 	target_blocksize = un->un_tgt_blocksize;
29598 
29599 	mutex_exit(SD_MUTEX(un));
29600 
29601 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
29602 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
29603 	if (bp == NULL) {
29604 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29605 		    "no resources for dumping; giving up");
29606 		err = ENOMEM;
29607 		goto done;
29608 	}
29609 
29610 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
29611 	    blkno, nblk);
29612 	if (rval != 0) {
29613 		scsi_free_consistent_buf(bp);
29614 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29615 		    "no resources for dumping; giving up");
29616 		err = ENOMEM;
29617 		goto done;
29618 	}
29619 
29620 	pkt->pkt_flags |= FLAG_NOINTR;
29621 
29622 	err = EIO;
29623 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
29624 
29625 		/*
29626 		 * Scsi_poll returns 0 (success) if the command completes and
29627 		 * the status block is STATUS_GOOD.  We should only check
29628 		 * errors if this condition is not true.  Even then we should
29629 		 * send our own request sense packet only if we have a check
29630 		 * condition and auto request sense has not been performed by
29631 		 * the hba.
29632 		 */
29633 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
29634 
29635 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
29636 			err = 0;
29637 			break;
29638 		}
29639 
29640 		/*
29641 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
29642 		 * no need to read RQS data.
29643 		 */
29644 		if (pkt->pkt_reason == CMD_DEV_GONE) {
29645 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29646 			    "Error while dumping state with rmw..."
29647 			    "Device is gone\n");
29648 			break;
29649 		}
29650 
29651 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
29652 			SD_INFO(SD_LOG_DUMP, un,
29653 			    "sddump: read failed with CHECK, try # %d\n", i);
29654 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
29655 				(void) sd_send_polled_RQS(un);
29656 			}
29657 
29658 			continue;
29659 		}
29660 
29661 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
29662 			int reset_retval = 0;
29663 
29664 			SD_INFO(SD_LOG_DUMP, un,
29665 			    "sddump: read failed with BUSY, try # %d\n", i);
29666 
29667 			if (un->un_f_lun_reset_enabled == TRUE) {
29668 				reset_retval = scsi_reset(SD_ADDRESS(un),
29669 				    RESET_LUN);
29670 			}
29671 			if (reset_retval == 0) {
29672 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
29673 			}
29674 			(void) sd_send_polled_RQS(un);
29675 
29676 		} else {
29677 			SD_INFO(SD_LOG_DUMP, un,
29678 			    "sddump: read failed with 0x%x, try # %d\n",
29679 			    SD_GET_PKT_STATUS(pkt), i);
29680 			mutex_enter(SD_MUTEX(un));
29681 			sd_reset_target(un, pkt);
29682 			mutex_exit(SD_MUTEX(un));
29683 		}
29684 
29685 		/*
29686 		 * If we are not getting anywhere with lun/target resets,
29687 		 * let's reset the bus.
29688 		 */
29689 		if (i > SD_NDUMP_RETRIES/2) {
29690 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
29691 			(void) sd_send_polled_RQS(un);
29692 		}
29693 
29694 	}
29695 	scsi_destroy_pkt(pkt);
29696 
29697 	if (err != 0) {
29698 		scsi_free_consistent_buf(bp);
29699 		*bpp = NULL;
29700 	} else {
29701 		*bpp = bp;
29702 	}
29703 
29704 done:
29705 	mutex_enter(SD_MUTEX(un));
29706 	return (err);
29707 }
29708 
29709 
29710 /*
29711  *    Function: sd_failfast_flushq
29712  *
29713  * Description: Take all bp's on the wait queue that have B_FAILFAST set
29714  *		in b_flags and move them onto the failfast queue, then kick
29715  *		off a thread to return all bp's on the failfast queue to
29716  *		their owners with an error set.
29717  *
29718  *   Arguments: un - pointer to the soft state struct for the instance.
29719  *
29720  *     Context: may execute in interrupt context.
29721  */
29722 
29723 static void
29724 sd_failfast_flushq(struct sd_lun *un)
29725 {
29726 	struct buf *bp;
29727 	struct buf *next_waitq_bp;
29728 	struct buf *prev_waitq_bp = NULL;
29729 
29730 	ASSERT(un != NULL);
29731 	ASSERT(mutex_owned(SD_MUTEX(un)));
29732 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
29733 	ASSERT(un->un_failfast_bp == NULL);
29734 
29735 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29736 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
29737 
29738 	/*
29739 	 * Check if we should flush all bufs when entering failfast state, or
29740 	 * just those with B_FAILFAST set.
29741 	 */
29742 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
29743 		/*
29744 		 * Move *all* bp's on the wait queue to the failfast flush
29745 		 * queue, including those that do NOT have B_FAILFAST set.
29746 		 */
29747 		if (un->un_failfast_headp == NULL) {
29748 			ASSERT(un->un_failfast_tailp == NULL);
29749 			un->un_failfast_headp = un->un_waitq_headp;
29750 		} else {
29751 			ASSERT(un->un_failfast_tailp != NULL);
29752 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
29753 		}
29754 
29755 		un->un_failfast_tailp = un->un_waitq_tailp;
29756 
29757 		/* update kstat for each bp moved out of the waitq */
29758 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
29759 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29760 		}
29761 
29762 		/* empty the waitq */
29763 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
29764 
29765 	} else {
29766 		/*
29767 		 * Go thru the wait queue, pick off all entries with
29768 		 * B_FAILFAST set, and move these onto the failfast queue.
29769 		 */
29770 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
29771 			/*
29772 			 * Save the pointer to the next bp on the wait queue,
29773 			 * so we get to it on the next iteration of this loop.
29774 			 */
29775 			next_waitq_bp = bp->av_forw;
29776 
29777 			/*
29778 			 * If this bp from the wait queue does NOT have
29779 			 * B_FAILFAST set, just move on to the next element
29780 			 * in the wait queue. Note, this is the only place
29781 			 * where it is correct to set prev_waitq_bp.
29782 			 */
29783 			if ((bp->b_flags & B_FAILFAST) == 0) {
29784 				prev_waitq_bp = bp;
29785 				continue;
29786 			}
29787 
29788 			/*
29789 			 * Remove the bp from the wait queue.
29790 			 */
29791 			if (bp == un->un_waitq_headp) {
29792 				/* The bp is the first element of the waitq. */
29793 				un->un_waitq_headp = next_waitq_bp;
29794 				if (un->un_waitq_headp == NULL) {
29795 					/* The wait queue is now empty */
29796 					un->un_waitq_tailp = NULL;
29797 				}
29798 			} else {
29799 				/*
29800 				 * The bp is either somewhere in the middle
29801 				 * or at the end of the wait queue.
29802 				 */
29803 				ASSERT(un->un_waitq_headp != NULL);
29804 				ASSERT(prev_waitq_bp != NULL);
29805 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
29806 				    == 0);
29807 				if (bp == un->un_waitq_tailp) {
29808 					/* bp is the last entry on the waitq. */
29809 					ASSERT(next_waitq_bp == NULL);
29810 					un->un_waitq_tailp = prev_waitq_bp;
29811 				}
29812 				prev_waitq_bp->av_forw = next_waitq_bp;
29813 			}
29814 			bp->av_forw = NULL;
29815 
29816 			/*
29817 			 * update kstat since the bp is moved out of
29818 			 * the waitq
29819 			 */
29820 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29821 
29822 			/*
29823 			 * Now put the bp onto the failfast queue.
29824 			 */
29825 			if (un->un_failfast_headp == NULL) {
29826 				/* failfast queue is currently empty */
29827 				ASSERT(un->un_failfast_tailp == NULL);
29828 				un->un_failfast_headp =
29829 				    un->un_failfast_tailp = bp;
29830 			} else {
29831 				/* Add the bp to the end of the failfast q */
29832 				ASSERT(un->un_failfast_tailp != NULL);
29833 				ASSERT(un->un_failfast_tailp->b_flags &
29834 				    B_FAILFAST);
29835 				un->un_failfast_tailp->av_forw = bp;
29836 				un->un_failfast_tailp = bp;
29837 			}
29838 		}
29839 	}
29840 
29841 	/*
29842 	 * Now return all bp's on the failfast queue to their owners.
29843 	 */
29844 	while ((bp = un->un_failfast_headp) != NULL) {
29845 
29846 		un->un_failfast_headp = bp->av_forw;
29847 		if (un->un_failfast_headp == NULL) {
29848 			un->un_failfast_tailp = NULL;
29849 		}
29850 
29851 		/*
29852 		 * We want to return the bp with a failure error code, but
29853 		 * we do not want a call to sd_start_cmds() to occur here,
29854 		 * so use sd_return_failed_command_no_restart() instead of
29855 		 * sd_return_failed_command().
29856 		 */
29857 		sd_return_failed_command_no_restart(un, bp, EIO);
29858 	}
29859 
29860 	/* Flush the xbuf queues if required. */
29861 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
29862 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
29863 	}
29864 
29865 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29866 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
29867 }
29868 
29869 
29870 /*
29871  *    Function: sd_failfast_flushq_callback
29872  *
29873  * Description: Return TRUE if the given bp meets the criteria for failfast
29874  *		flushing. Used with ddi_xbuf_flushq(9F).
29875  *
29876  *   Arguments: bp - ptr to buf struct to be examined.
29877  *
29878  *     Context: Any
29879  */
29880 
29881 static int
29882 sd_failfast_flushq_callback(struct buf *bp)
29883 {
29884 	/*
29885 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
29886 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
29887 	 */
29888 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
29889 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
29890 }
29891 
29892 
29893 
29894 /*
29895  * Function: sd_setup_next_xfer
29896  *
29897  * Description: Prepare next I/O operation using DMA_PARTIAL
29898  *
29899  */
29900 
29901 static int
29902 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
29903     struct scsi_pkt *pkt, struct sd_xbuf *xp)
29904 {
29905 	ssize_t	num_blks_not_xfered;
29906 	daddr_t	strt_blk_num;
29907 	ssize_t	bytes_not_xfered;
29908 	int	rval;
29909 
29910 	ASSERT(pkt->pkt_resid == 0);
29911 
29912 	/*
29913 	 * Calculate next block number and amount to be transferred.
29914 	 *
29915 	 * How much data NOT transfered to the HBA yet.
29916 	 */
29917 	bytes_not_xfered = xp->xb_dma_resid;
29918 
29919 	/*
29920 	 * figure how many blocks NOT transfered to the HBA yet.
29921 	 */
29922 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
29923 
29924 	/*
29925 	 * set starting block number to the end of what WAS transfered.
29926 	 */
29927 	strt_blk_num = xp->xb_blkno +
29928 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
29929 
29930 	/*
29931 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
29932 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
29933 	 * the disk mutex here.
29934 	 */
29935 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
29936 	    strt_blk_num, num_blks_not_xfered);
29937 
29938 	if (rval == 0) {
29939 
29940 		/*
29941 		 * Success.
29942 		 *
29943 		 * Adjust things if there are still more blocks to be
29944 		 * transfered.
29945 		 */
29946 		xp->xb_dma_resid = pkt->pkt_resid;
29947 		pkt->pkt_resid = 0;
29948 
29949 		return (1);
29950 	}
29951 
29952 	/*
29953 	 * There's really only one possible return value from
29954 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
29955 	 * returns NULL.
29956 	 */
29957 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
29958 
29959 	bp->b_resid = bp->b_bcount;
29960 	bp->b_flags |= B_ERROR;
29961 
29962 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29963 	    "Error setting up next portion of DMA transfer\n");
29964 
29965 	return (0);
29966 }
29967 
29968 /*
29969  *    Function: sd_panic_for_res_conflict
29970  *
29971  * Description: Call panic with a string formatted with "Reservation Conflict"
29972  *		and a human readable identifier indicating the SD instance
29973  *		that experienced the reservation conflict.
29974  *
29975  *   Arguments: un - pointer to the soft state struct for the instance.
29976  *
29977  *     Context: may execute in interrupt context.
29978  */
29979 
29980 #define	SD_RESV_CONFLICT_FMT_LEN 40
29981 void
29982 sd_panic_for_res_conflict(struct sd_lun *un)
29983 {
29984 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
29985 	char path_str[MAXPATHLEN];
29986 
29987 	(void) snprintf(panic_str, sizeof (panic_str),
29988 	    "Reservation Conflict\nDisk: %s",
29989 	    ddi_pathname(SD_DEVINFO(un), path_str));
29990 
29991 	panic(panic_str);
29992 }
29993 
29994 /*
29995  * Note: The following sd_faultinjection_ioctl( ) routines implement
29996  * driver support for handling fault injection for error analysis
29997  * causing faults in multiple layers of the driver.
29998  *
29999  */
30000 
30001 #ifdef SD_FAULT_INJECTION
30002 static uint_t   sd_fault_injection_on = 0;
30003 
30004 /*
30005  *    Function: sd_faultinjection_ioctl()
30006  *
30007  * Description: This routine is the driver entry point for handling
30008  *              faultinjection ioctls to inject errors into the
30009  *              layer model
30010  *
30011  *   Arguments: cmd	- the ioctl cmd received
30012  *		arg	- the arguments from user and returns
30013  */
30014 
30015 static void
30016 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
30017 
30018 	uint_t i = 0;
30019 	uint_t rval;
30020 
30021 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
30022 
30023 	mutex_enter(SD_MUTEX(un));
30024 
30025 	switch (cmd) {
30026 	case SDIOCRUN:
30027 		/* Allow pushed faults to be injected */
30028 		SD_INFO(SD_LOG_SDTEST, un,
30029 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
30030 
30031 		sd_fault_injection_on = 1;
30032 
30033 		SD_INFO(SD_LOG_IOERR, un,
30034 		    "sd_faultinjection_ioctl: run finished\n");
30035 		break;
30036 
30037 	case SDIOCSTART:
30038 		/* Start Injection Session */
30039 		SD_INFO(SD_LOG_SDTEST, un,
30040 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
30041 
30042 		sd_fault_injection_on = 0;
30043 		un->sd_injection_mask = 0xFFFFFFFF;
30044 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30045 			un->sd_fi_fifo_pkt[i] = NULL;
30046 			un->sd_fi_fifo_xb[i] = NULL;
30047 			un->sd_fi_fifo_un[i] = NULL;
30048 			un->sd_fi_fifo_arq[i] = NULL;
30049 		}
30050 		un->sd_fi_fifo_start = 0;
30051 		un->sd_fi_fifo_end = 0;
30052 
30053 		mutex_enter(&(un->un_fi_mutex));
30054 		un->sd_fi_log[0] = '\0';
30055 		un->sd_fi_buf_len = 0;
30056 		mutex_exit(&(un->un_fi_mutex));
30057 
30058 		SD_INFO(SD_LOG_IOERR, un,
30059 		    "sd_faultinjection_ioctl: start finished\n");
30060 		break;
30061 
30062 	case SDIOCSTOP:
30063 		/* Stop Injection Session */
30064 		SD_INFO(SD_LOG_SDTEST, un,
30065 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
30066 		sd_fault_injection_on = 0;
30067 		un->sd_injection_mask = 0x0;
30068 
30069 		/* Empty stray or unuseds structs from fifo */
30070 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30071 			if (un->sd_fi_fifo_pkt[i] != NULL) {
30072 				kmem_free(un->sd_fi_fifo_pkt[i],
30073 				    sizeof (struct sd_fi_pkt));
30074 			}
30075 			if (un->sd_fi_fifo_xb[i] != NULL) {
30076 				kmem_free(un->sd_fi_fifo_xb[i],
30077 				    sizeof (struct sd_fi_xb));
30078 			}
30079 			if (un->sd_fi_fifo_un[i] != NULL) {
30080 				kmem_free(un->sd_fi_fifo_un[i],
30081 				    sizeof (struct sd_fi_un));
30082 			}
30083 			if (un->sd_fi_fifo_arq[i] != NULL) {
30084 				kmem_free(un->sd_fi_fifo_arq[i],
30085 				    sizeof (struct sd_fi_arq));
30086 			}
30087 			un->sd_fi_fifo_pkt[i] = NULL;
30088 			un->sd_fi_fifo_un[i] = NULL;
30089 			un->sd_fi_fifo_xb[i] = NULL;
30090 			un->sd_fi_fifo_arq[i] = NULL;
30091 		}
30092 		un->sd_fi_fifo_start = 0;
30093 		un->sd_fi_fifo_end = 0;
30094 
30095 		SD_INFO(SD_LOG_IOERR, un,
30096 		    "sd_faultinjection_ioctl: stop finished\n");
30097 		break;
30098 
30099 	case SDIOCINSERTPKT:
30100 		/* Store a packet struct to be pushed onto fifo */
30101 		SD_INFO(SD_LOG_SDTEST, un,
30102 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
30103 
30104 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30105 
30106 		sd_fault_injection_on = 0;
30107 
30108 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
30109 		if (un->sd_fi_fifo_pkt[i] != NULL) {
30110 			kmem_free(un->sd_fi_fifo_pkt[i],
30111 			    sizeof (struct sd_fi_pkt));
30112 		}
30113 		if (arg != NULL) {
30114 			un->sd_fi_fifo_pkt[i] =
30115 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
30116 			if (un->sd_fi_fifo_pkt[i] == NULL) {
30117 				/* Alloc failed don't store anything */
30118 				break;
30119 			}
30120 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
30121 			    sizeof (struct sd_fi_pkt), 0);
30122 			if (rval == -1) {
30123 				kmem_free(un->sd_fi_fifo_pkt[i],
30124 				    sizeof (struct sd_fi_pkt));
30125 				un->sd_fi_fifo_pkt[i] = NULL;
30126 			}
30127 		} else {
30128 			SD_INFO(SD_LOG_IOERR, un,
30129 			    "sd_faultinjection_ioctl: pkt null\n");
30130 		}
30131 		break;
30132 
30133 	case SDIOCINSERTXB:
30134 		/* Store a xb struct to be pushed onto fifo */
30135 		SD_INFO(SD_LOG_SDTEST, un,
30136 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
30137 
30138 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30139 
30140 		sd_fault_injection_on = 0;
30141 
30142 		if (un->sd_fi_fifo_xb[i] != NULL) {
30143 			kmem_free(un->sd_fi_fifo_xb[i],
30144 			    sizeof (struct sd_fi_xb));
30145 			un->sd_fi_fifo_xb[i] = NULL;
30146 		}
30147 		if (arg != NULL) {
30148 			un->sd_fi_fifo_xb[i] =
30149 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
30150 			if (un->sd_fi_fifo_xb[i] == NULL) {
30151 				/* Alloc failed don't store anything */
30152 				break;
30153 			}
30154 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
30155 			    sizeof (struct sd_fi_xb), 0);
30156 
30157 			if (rval == -1) {
30158 				kmem_free(un->sd_fi_fifo_xb[i],
30159 				    sizeof (struct sd_fi_xb));
30160 				un->sd_fi_fifo_xb[i] = NULL;
30161 			}
30162 		} else {
30163 			SD_INFO(SD_LOG_IOERR, un,
30164 			    "sd_faultinjection_ioctl: xb null\n");
30165 		}
30166 		break;
30167 
30168 	case SDIOCINSERTUN:
30169 		/* Store a un struct to be pushed onto fifo */
30170 		SD_INFO(SD_LOG_SDTEST, un,
30171 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
30172 
30173 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30174 
30175 		sd_fault_injection_on = 0;
30176 
30177 		if (un->sd_fi_fifo_un[i] != NULL) {
30178 			kmem_free(un->sd_fi_fifo_un[i],
30179 			    sizeof (struct sd_fi_un));
30180 			un->sd_fi_fifo_un[i] = NULL;
30181 		}
30182 		if (arg != NULL) {
30183 			un->sd_fi_fifo_un[i] =
30184 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
30185 			if (un->sd_fi_fifo_un[i] == NULL) {
30186 				/* Alloc failed don't store anything */
30187 				break;
30188 			}
30189 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
30190 			    sizeof (struct sd_fi_un), 0);
30191 			if (rval == -1) {
30192 				kmem_free(un->sd_fi_fifo_un[i],
30193 				    sizeof (struct sd_fi_un));
30194 				un->sd_fi_fifo_un[i] = NULL;
30195 			}
30196 
30197 		} else {
30198 			SD_INFO(SD_LOG_IOERR, un,
30199 			    "sd_faultinjection_ioctl: un null\n");
30200 		}
30201 
30202 		break;
30203 
30204 	case SDIOCINSERTARQ:
30205 		/* Store a arq struct to be pushed onto fifo */
30206 		SD_INFO(SD_LOG_SDTEST, un,
30207 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
30208 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30209 
30210 		sd_fault_injection_on = 0;
30211 
30212 		if (un->sd_fi_fifo_arq[i] != NULL) {
30213 			kmem_free(un->sd_fi_fifo_arq[i],
30214 			    sizeof (struct sd_fi_arq));
30215 			un->sd_fi_fifo_arq[i] = NULL;
30216 		}
30217 		if (arg != NULL) {
30218 			un->sd_fi_fifo_arq[i] =
30219 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
30220 			if (un->sd_fi_fifo_arq[i] == NULL) {
30221 				/* Alloc failed don't store anything */
30222 				break;
30223 			}
30224 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
30225 			    sizeof (struct sd_fi_arq), 0);
30226 			if (rval == -1) {
30227 				kmem_free(un->sd_fi_fifo_arq[i],
30228 				    sizeof (struct sd_fi_arq));
30229 				un->sd_fi_fifo_arq[i] = NULL;
30230 			}
30231 
30232 		} else {
30233 			SD_INFO(SD_LOG_IOERR, un,
30234 			    "sd_faultinjection_ioctl: arq null\n");
30235 		}
30236 
30237 		break;
30238 
30239 	case SDIOCPUSH:
30240 		/* Push stored xb, pkt, un, and arq onto fifo */
30241 		sd_fault_injection_on = 0;
30242 
30243 		if (arg != NULL) {
30244 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
30245 			if (rval != -1 &&
30246 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30247 				un->sd_fi_fifo_end += i;
30248 			}
30249 		} else {
30250 			SD_INFO(SD_LOG_IOERR, un,
30251 			    "sd_faultinjection_ioctl: push arg null\n");
30252 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30253 				un->sd_fi_fifo_end++;
30254 			}
30255 		}
30256 		SD_INFO(SD_LOG_IOERR, un,
30257 		    "sd_faultinjection_ioctl: push to end=%d\n",
30258 		    un->sd_fi_fifo_end);
30259 		break;
30260 
30261 	case SDIOCRETRIEVE:
30262 		/* Return buffer of log from Injection session */
30263 		SD_INFO(SD_LOG_SDTEST, un,
30264 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
30265 
30266 		sd_fault_injection_on = 0;
30267 
30268 		mutex_enter(&(un->un_fi_mutex));
30269 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
30270 		    un->sd_fi_buf_len+1, 0);
30271 		mutex_exit(&(un->un_fi_mutex));
30272 
30273 		if (rval == -1) {
30274 			/*
30275 			 * arg is possibly invalid setting
30276 			 * it to NULL for return
30277 			 */
30278 			arg = NULL;
30279 		}
30280 		break;
30281 	}
30282 
30283 	mutex_exit(SD_MUTEX(un));
30284 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
30285 			    " exit\n");
30286 }
30287 
30288 
30289 /*
30290  *    Function: sd_injection_log()
30291  *
30292  * Description: This routine adds buff to the already existing injection log
30293  *              for retrieval via faultinjection_ioctl for use in fault
30294  *              detection and recovery
30295  *
30296  *   Arguments: buf - the string to add to the log
30297  */
30298 
30299 static void
30300 sd_injection_log(char *buf, struct sd_lun *un)
30301 {
30302 	uint_t len;
30303 
30304 	ASSERT(un != NULL);
30305 	ASSERT(buf != NULL);
30306 
30307 	mutex_enter(&(un->un_fi_mutex));
30308 
30309 	len = min(strlen(buf), 255);
30310 	/* Add logged value to Injection log to be returned later */
30311 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
30312 		uint_t	offset = strlen((char *)un->sd_fi_log);
30313 		char *destp = (char *)un->sd_fi_log + offset;
30314 		int i;
30315 		for (i = 0; i < len; i++) {
30316 			*destp++ = *buf++;
30317 		}
30318 		un->sd_fi_buf_len += len;
30319 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
30320 	}
30321 
30322 	mutex_exit(&(un->un_fi_mutex));
30323 }
30324 
30325 
30326 /*
30327  *    Function: sd_faultinjection()
30328  *
30329  * Description: This routine takes the pkt and changes its
30330  *		content based on error injection scenerio.
30331  *
30332  *   Arguments: pktp	- packet to be changed
30333  */
30334 
30335 static void
30336 sd_faultinjection(struct scsi_pkt *pktp)
30337 {
30338 	uint_t i;
30339 	struct sd_fi_pkt *fi_pkt;
30340 	struct sd_fi_xb *fi_xb;
30341 	struct sd_fi_un *fi_un;
30342 	struct sd_fi_arq *fi_arq;
30343 	struct buf *bp;
30344 	struct sd_xbuf *xb;
30345 	struct sd_lun *un;
30346 
30347 	ASSERT(pktp != NULL);
30348 
30349 	/* pull bp xb and un from pktp */
30350 	bp = (struct buf *)pktp->pkt_private;
30351 	xb = SD_GET_XBUF(bp);
30352 	un = SD_GET_UN(bp);
30353 
30354 	ASSERT(un != NULL);
30355 
30356 	mutex_enter(SD_MUTEX(un));
30357 
30358 	SD_TRACE(SD_LOG_SDTEST, un,
30359 	    "sd_faultinjection: entry Injection from sdintr\n");
30360 
30361 	/* if injection is off return */
30362 	if (sd_fault_injection_on == 0 ||
30363 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
30364 		mutex_exit(SD_MUTEX(un));
30365 		return;
30366 	}
30367 
30368 	SD_INFO(SD_LOG_SDTEST, un,
30369 	    "sd_faultinjection: is working for copying\n");
30370 
30371 	/* take next set off fifo */
30372 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
30373 
30374 	fi_pkt = un->sd_fi_fifo_pkt[i];
30375 	fi_xb = un->sd_fi_fifo_xb[i];
30376 	fi_un = un->sd_fi_fifo_un[i];
30377 	fi_arq = un->sd_fi_fifo_arq[i];
30378 
30379 
30380 	/* set variables accordingly */
30381 	/* set pkt if it was on fifo */
30382 	if (fi_pkt != NULL) {
30383 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
30384 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
30385 		if (fi_pkt->pkt_cdbp != 0xff)
30386 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
30387 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
30388 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
30389 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
30390 
30391 	}
30392 	/* set xb if it was on fifo */
30393 	if (fi_xb != NULL) {
30394 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
30395 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
30396 		if (fi_xb->xb_retry_count != 0)
30397 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
30398 		SD_CONDSET(xb, xb, xb_victim_retry_count,
30399 		    "xb_victim_retry_count");
30400 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
30401 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
30402 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
30403 
30404 		/* copy in block data from sense */
30405 		/*
30406 		 * if (fi_xb->xb_sense_data[0] != -1) {
30407 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
30408 		 *	SENSE_LENGTH);
30409 		 * }
30410 		 */
30411 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
30412 
30413 		/* copy in extended sense codes */
30414 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30415 		    xb, es_code, "es_code");
30416 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30417 		    xb, es_key, "es_key");
30418 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30419 		    xb, es_add_code, "es_add_code");
30420 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30421 		    xb, es_qual_code, "es_qual_code");
30422 		struct scsi_extended_sense *esp;
30423 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
30424 		esp->es_class = CLASS_EXTENDED_SENSE;
30425 	}
30426 
30427 	/* set un if it was on fifo */
30428 	if (fi_un != NULL) {
30429 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
30430 		SD_CONDSET(un, un, un_ctype, "un_ctype");
30431 		SD_CONDSET(un, un, un_reset_retry_count,
30432 		    "un_reset_retry_count");
30433 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
30434 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
30435 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
30436 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
30437 		    "un_f_allow_bus_device_reset");
30438 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
30439 
30440 	}
30441 
30442 	/* copy in auto request sense if it was on fifo */
30443 	if (fi_arq != NULL) {
30444 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
30445 	}
30446 
30447 	/* free structs */
30448 	if (un->sd_fi_fifo_pkt[i] != NULL) {
30449 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
30450 	}
30451 	if (un->sd_fi_fifo_xb[i] != NULL) {
30452 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
30453 	}
30454 	if (un->sd_fi_fifo_un[i] != NULL) {
30455 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
30456 	}
30457 	if (un->sd_fi_fifo_arq[i] != NULL) {
30458 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
30459 	}
30460 
30461 	/*
30462 	 * kmem_free does not gurantee to set to NULL
30463 	 * since we uses these to determine if we set
30464 	 * values or not lets confirm they are always
30465 	 * NULL after free
30466 	 */
30467 	un->sd_fi_fifo_pkt[i] = NULL;
30468 	un->sd_fi_fifo_un[i] = NULL;
30469 	un->sd_fi_fifo_xb[i] = NULL;
30470 	un->sd_fi_fifo_arq[i] = NULL;
30471 
30472 	un->sd_fi_fifo_start++;
30473 
30474 	mutex_exit(SD_MUTEX(un));
30475 
30476 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
30477 }
30478 
30479 #endif /* SD_FAULT_INJECTION */
30480 
30481 /*
30482  * This routine is invoked in sd_unit_attach(). Before calling it, the
30483  * properties in conf file should be processed already, and "hotpluggable"
30484  * property was processed also.
30485  *
30486  * The sd driver distinguishes 3 different type of devices: removable media,
30487  * non-removable media, and hotpluggable. Below the differences are defined:
30488  *
30489  * 1. Device ID
30490  *
30491  *     The device ID of a device is used to identify this device. Refer to
30492  *     ddi_devid_register(9F).
30493  *
30494  *     For a non-removable media disk device which can provide 0x80 or 0x83
30495  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
30496  *     device ID is created to identify this device. For other non-removable
30497  *     media devices, a default device ID is created only if this device has
30498  *     at least 2 alter cylinders. Otherwise, this device has no devid.
30499  *
30500  *     -------------------------------------------------------
30501  *     removable media   hotpluggable  | Can Have Device ID
30502  *     -------------------------------------------------------
30503  *         false             false     |     Yes
30504  *         false             true      |     Yes
30505  *         true                x       |     No
30506  *     ------------------------------------------------------
30507  *
30508  *
30509  * 2. SCSI group 4 commands
30510  *
30511  *     In SCSI specs, only some commands in group 4 command set can use
30512  *     8-byte addresses that can be used to access >2TB storage spaces.
30513  *     Other commands have no such capability. Without supporting group4,
30514  *     it is impossible to make full use of storage spaces of a disk with
30515  *     capacity larger than 2TB.
30516  *
30517  *     -----------------------------------------------
30518  *     removable media   hotpluggable   LP64  |  Group
30519  *     -----------------------------------------------
30520  *           false          false       false |   1
30521  *           false          false       true  |   4
30522  *           false          true        false |   1
30523  *           false          true        true  |   4
30524  *           true             x           x   |   5
30525  *     -----------------------------------------------
30526  *
30527  *
30528  * 3. Check for VTOC Label
30529  *
30530  *     If a direct-access disk has no EFI label, sd will check if it has a
30531  *     valid VTOC label. Now, sd also does that check for removable media
30532  *     and hotpluggable devices.
30533  *
30534  *     --------------------------------------------------------------
30535  *     Direct-Access   removable media    hotpluggable |  Check Label
30536  *     -------------------------------------------------------------
30537  *         false          false           false        |   No
30538  *         false          false           true         |   No
30539  *         false          true            false        |   Yes
30540  *         false          true            true         |   Yes
30541  *         true            x                x          |   Yes
30542  *     --------------------------------------------------------------
30543  *
30544  *
30545  * 4. Building default VTOC label
30546  *
30547  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
30548  *     If those devices have no valid VTOC label, sd(7d) will attempt to
30549  *     create default VTOC for them. Currently sd creates default VTOC label
30550  *     for all devices on x86 platform (VTOC_16), but only for removable
30551  *     media devices on SPARC (VTOC_8).
30552  *
30553  *     -----------------------------------------------------------
30554  *       removable media hotpluggable platform   |   Default Label
30555  *     -----------------------------------------------------------
30556  *             false          false    sparc     |     No
30557  *             false          true      x86      |     Yes
30558  *             false          true     sparc     |     Yes
30559  *             true             x        x       |     Yes
30560  *     ----------------------------------------------------------
30561  *
30562  *
30563  * 5. Supported blocksizes of target devices
30564  *
30565  *     Sd supports non-512-byte blocksize for removable media devices only.
30566  *     For other devices, only 512-byte blocksize is supported. This may be
30567  *     changed in near future because some RAID devices require non-512-byte
30568  *     blocksize
30569  *
30570  *     -----------------------------------------------------------
30571  *     removable media    hotpluggable    | non-512-byte blocksize
30572  *     -----------------------------------------------------------
30573  *           false          false         |   No
30574  *           false          true          |   No
30575  *           true             x           |   Yes
30576  *     -----------------------------------------------------------
30577  *
30578  *
30579  * 6. Automatic mount & unmount
30580  *
30581  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
30582  *     if a device is removable media device. It return 1 for removable media
30583  *     devices, and 0 for others.
30584  *
30585  *     The automatic mounting subsystem should distinguish between the types
30586  *     of devices and apply automounting policies to each.
30587  *
30588  *
30589  * 7. fdisk partition management
30590  *
30591  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
30592  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
30593  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
30594  *     fdisk partitions on both x86 and SPARC platform.
30595  *
30596  *     -----------------------------------------------------------
30597  *       platform   removable media  USB/1394  |  fdisk supported
30598  *     -----------------------------------------------------------
30599  *        x86         X               X        |       true
30600  *     ------------------------------------------------------------
30601  *        sparc       X               X        |       false
30602  *     ------------------------------------------------------------
30603  *
30604  *
30605  * 8. MBOOT/MBR
30606  *
30607  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
30608  *     read/write mboot for removable media devices on sparc platform.
30609  *
30610  *     -----------------------------------------------------------
30611  *       platform   removable media  USB/1394  |  mboot supported
30612  *     -----------------------------------------------------------
30613  *        x86         X               X        |       true
30614  *     ------------------------------------------------------------
30615  *        sparc      false           false     |       false
30616  *        sparc      false           true      |       true
30617  *        sparc      true            false     |       true
30618  *        sparc      true            true      |       true
30619  *     ------------------------------------------------------------
30620  *
30621  *
30622  * 9.  error handling during opening device
30623  *
30624  *     If failed to open a disk device, an errno is returned. For some kinds
30625  *     of errors, different errno is returned depending on if this device is
30626  *     a removable media device. This brings USB/1394 hard disks in line with
30627  *     expected hard disk behavior. It is not expected that this breaks any
30628  *     application.
30629  *
30630  *     ------------------------------------------------------
30631  *       removable media    hotpluggable   |  errno
30632  *     ------------------------------------------------------
30633  *             false          false        |   EIO
30634  *             false          true         |   EIO
30635  *             true             x          |   ENXIO
30636  *     ------------------------------------------------------
30637  *
30638  *
30639  * 11. ioctls: DKIOCEJECT, CDROMEJECT
30640  *
30641  *     These IOCTLs are applicable only to removable media devices.
30642  *
30643  *     -----------------------------------------------------------
30644  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
30645  *     -----------------------------------------------------------
30646  *             false          false        |     No
30647  *             false          true         |     No
30648  *             true            x           |     Yes
30649  *     -----------------------------------------------------------
30650  *
30651  *
30652  * 12. Kstats for partitions
30653  *
30654  *     sd creates partition kstat for non-removable media devices. USB and
30655  *     Firewire hard disks now have partition kstats
30656  *
30657  *      ------------------------------------------------------
30658  *       removable media    hotpluggable   |   kstat
30659  *      ------------------------------------------------------
30660  *             false          false        |    Yes
30661  *             false          true         |    Yes
30662  *             true             x          |    No
30663  *       ------------------------------------------------------
30664  *
30665  *
30666  * 13. Removable media & hotpluggable properties
30667  *
30668  *     Sd driver creates a "removable-media" property for removable media
30669  *     devices. Parent nexus drivers create a "hotpluggable" property if
30670  *     it supports hotplugging.
30671  *
30672  *     ---------------------------------------------------------------------
30673  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
30674  *     ---------------------------------------------------------------------
30675  *       false            false       |    No                   No
30676  *       false            true        |    No                   Yes
30677  *       true             false       |    Yes                  No
30678  *       true             true        |    Yes                  Yes
30679  *     ---------------------------------------------------------------------
30680  *
30681  *
30682  * 14. Power Management
30683  *
30684  *     sd only power manages removable media devices or devices that support
30685  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
30686  *
30687  *     A parent nexus that supports hotplugging can also set "pm-capable"
30688  *     if the disk can be power managed.
30689  *
30690  *     ------------------------------------------------------------
30691  *       removable media hotpluggable pm-capable  |   power manage
30692  *     ------------------------------------------------------------
30693  *             false          false     false     |     No
30694  *             false          false     true      |     Yes
30695  *             false          true      false     |     No
30696  *             false          true      true      |     Yes
30697  *             true             x        x        |     Yes
30698  *     ------------------------------------------------------------
30699  *
30700  *      USB and firewire hard disks can now be power managed independently
30701  *      of the framebuffer
30702  *
30703  *
30704  * 15. Support for USB disks with capacity larger than 1TB
30705  *
30706  *     Currently, sd doesn't permit a fixed disk device with capacity
30707  *     larger than 1TB to be used in a 32-bit operating system environment.
30708  *     However, sd doesn't do that for removable media devices. Instead, it
30709  *     assumes that removable media devices cannot have a capacity larger
30710  *     than 1TB. Therefore, using those devices on 32-bit system is partially
30711  *     supported, which can cause some unexpected results.
30712  *
30713  *     ---------------------------------------------------------------------
30714  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
30715  *     ---------------------------------------------------------------------
30716  *             false          false  |   true         |     no
30717  *             false          true   |   true         |     no
30718  *             true           false  |   true         |     Yes
30719  *             true           true   |   true         |     Yes
30720  *     ---------------------------------------------------------------------
30721  *
30722  *
30723  * 16. Check write-protection at open time
30724  *
30725  *     When a removable media device is being opened for writing without NDELAY
30726  *     flag, sd will check if this device is writable. If attempting to open
30727  *     without NDELAY flag a write-protected device, this operation will abort.
30728  *
30729  *     ------------------------------------------------------------
30730  *       removable media    USB/1394   |   WP Check
30731  *     ------------------------------------------------------------
30732  *             false          false    |     No
30733  *             false          true     |     No
30734  *             true           false    |     Yes
30735  *             true           true     |     Yes
30736  *     ------------------------------------------------------------
30737  *
30738  *
30739  * 17. syslog when corrupted VTOC is encountered
30740  *
30741  *      Currently, if an invalid VTOC is encountered, sd only print syslog
30742  *      for fixed SCSI disks.
30743  *     ------------------------------------------------------------
30744  *       removable media    USB/1394   |   print syslog
30745  *     ------------------------------------------------------------
30746  *             false          false    |     Yes
30747  *             false          true     |     No
30748  *             true           false    |     No
30749  *             true           true     |     No
30750  *     ------------------------------------------------------------
30751  */
30752 static void
30753 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
30754 {
30755 	int	pm_cap;
30756 
30757 	ASSERT(un->un_sd);
30758 	ASSERT(un->un_sd->sd_inq);
30759 
30760 	/*
30761 	 * Enable SYNC CACHE support for all devices.
30762 	 */
30763 	un->un_f_sync_cache_supported = TRUE;
30764 
30765 	/*
30766 	 * Set the sync cache required flag to false.
30767 	 * This would ensure that there is no SYNC CACHE
30768 	 * sent when there are no writes
30769 	 */
30770 	un->un_f_sync_cache_required = FALSE;
30771 
30772 	if (un->un_sd->sd_inq->inq_rmb) {
30773 		/*
30774 		 * The media of this device is removable. And for this kind
30775 		 * of devices, it is possible to change medium after opening
30776 		 * devices. Thus we should support this operation.
30777 		 */
30778 		un->un_f_has_removable_media = TRUE;
30779 
30780 		/*
30781 		 * support non-512-byte blocksize of removable media devices
30782 		 */
30783 		un->un_f_non_devbsize_supported = TRUE;
30784 
30785 		/*
30786 		 * Assume that all removable media devices support DOOR_LOCK
30787 		 */
30788 		un->un_f_doorlock_supported = TRUE;
30789 
30790 		/*
30791 		 * For a removable media device, it is possible to be opened
30792 		 * with NDELAY flag when there is no media in drive, in this
30793 		 * case we don't care if device is writable. But if without
30794 		 * NDELAY flag, we need to check if media is write-protected.
30795 		 */
30796 		un->un_f_chk_wp_open = TRUE;
30797 
30798 		/*
30799 		 * need to start a SCSI watch thread to monitor media state,
30800 		 * when media is being inserted or ejected, notify syseventd.
30801 		 */
30802 		un->un_f_monitor_media_state = TRUE;
30803 
30804 		/*
30805 		 * Some devices don't support START_STOP_UNIT command.
30806 		 * Therefore, we'd better check if a device supports it
30807 		 * before sending it.
30808 		 */
30809 		un->un_f_check_start_stop = TRUE;
30810 
30811 		/*
30812 		 * support eject media ioctl:
30813 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
30814 		 */
30815 		un->un_f_eject_media_supported = TRUE;
30816 
30817 		/*
30818 		 * Because many removable-media devices don't support
30819 		 * LOG_SENSE, we couldn't use this command to check if
30820 		 * a removable media device support power-management.
30821 		 * We assume that they support power-management via
30822 		 * START_STOP_UNIT command and can be spun up and down
30823 		 * without limitations.
30824 		 */
30825 		un->un_f_pm_supported = TRUE;
30826 
30827 		/*
30828 		 * Need to create a zero length (Boolean) property
30829 		 * removable-media for the removable media devices.
30830 		 * Note that the return value of the property is not being
30831 		 * checked, since if unable to create the property
30832 		 * then do not want the attach to fail altogether. Consistent
30833 		 * with other property creation in attach.
30834 		 */
30835 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
30836 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
30837 
30838 	} else {
30839 		/*
30840 		 * create device ID for device
30841 		 */
30842 		un->un_f_devid_supported = TRUE;
30843 
30844 		/*
30845 		 * Spin up non-removable-media devices once it is attached
30846 		 */
30847 		un->un_f_attach_spinup = TRUE;
30848 
30849 		/*
30850 		 * According to SCSI specification, Sense data has two kinds of
30851 		 * format: fixed format, and descriptor format. At present, we
30852 		 * don't support descriptor format sense data for removable
30853 		 * media.
30854 		 */
30855 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
30856 			un->un_f_descr_format_supported = TRUE;
30857 		}
30858 
30859 		/*
30860 		 * kstats are created only for non-removable media devices.
30861 		 *
30862 		 * Set this in sd.conf to 0 in order to disable kstats.  The
30863 		 * default is 1, so they are enabled by default.
30864 		 */
30865 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
30866 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
30867 		    "enable-partition-kstats", 1));
30868 
30869 		/*
30870 		 * Check if HBA has set the "pm-capable" property.
30871 		 * If "pm-capable" exists and is non-zero then we can
30872 		 * power manage the device without checking the start/stop
30873 		 * cycle count log sense page.
30874 		 *
30875 		 * If "pm-capable" exists and is set to be false (0),
30876 		 * then we should not power manage the device.
30877 		 *
30878 		 * If "pm-capable" doesn't exist then pm_cap will
30879 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
30880 		 * sd will check the start/stop cycle count log sense page
30881 		 * and power manage the device if the cycle count limit has
30882 		 * not been exceeded.
30883 		 */
30884 		pm_cap = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
30885 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
30886 		if (SD_PM_CAPABLE_IS_UNDEFINED(pm_cap)) {
30887 			un->un_f_log_sense_supported = TRUE;
30888 			if (!un->un_f_power_condition_disabled &&
30889 			    SD_INQUIRY(un)->inq_ansi == 6) {
30890 				un->un_f_power_condition_supported = TRUE;
30891 			}
30892 		} else {
30893 			/*
30894 			 * pm-capable property exists.
30895 			 *
30896 			 * Convert "TRUE" values for pm_cap to
30897 			 * SD_PM_CAPABLE_IS_TRUE to make it easier to check
30898 			 * later. "TRUE" values are any values defined in
30899 			 * inquiry.h.
30900 			 */
30901 			if (SD_PM_CAPABLE_IS_FALSE(pm_cap)) {
30902 				un->un_f_log_sense_supported = FALSE;
30903 			} else {
30904 				/* SD_PM_CAPABLE_IS_TRUE case */
30905 				un->un_f_pm_supported = TRUE;
30906 				if (!un->un_f_power_condition_disabled &&
30907 				    SD_PM_CAPABLE_IS_SPC_4(pm_cap)) {
30908 					un->un_f_power_condition_supported =
30909 					    TRUE;
30910 				}
30911 				if (SD_PM_CAP_LOG_SUPPORTED(pm_cap)) {
30912 					un->un_f_log_sense_supported = TRUE;
30913 					un->un_f_pm_log_sense_smart =
30914 					    SD_PM_CAP_SMART_LOG(pm_cap);
30915 				}
30916 			}
30917 
30918 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
30919 			    "sd_unit_attach: un:0x%p pm-capable "
30920 			    "property set to %d.\n", un, un->un_f_pm_supported);
30921 		}
30922 	}
30923 
30924 	if (un->un_f_is_hotpluggable) {
30925 
30926 		/*
30927 		 * Have to watch hotpluggable devices as well, since
30928 		 * that's the only way for userland applications to
30929 		 * detect hot removal while device is busy/mounted.
30930 		 */
30931 		un->un_f_monitor_media_state = TRUE;
30932 
30933 		un->un_f_check_start_stop = TRUE;
30934 
30935 	}
30936 }
30937 
30938 /*
30939  * sd_tg_rdwr:
30940  * Provides rdwr access for cmlb via sd_tgops. The start_block is
30941  * in sys block size, req_length in bytes.
30942  *
30943  */
30944 static int
30945 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
30946     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
30947 {
30948 	struct sd_lun *un;
30949 	int path_flag = (int)(uintptr_t)tg_cookie;
30950 	char *dkl = NULL;
30951 	diskaddr_t real_addr = start_block;
30952 	diskaddr_t first_byte, end_block;
30953 
30954 	size_t	buffer_size = reqlength;
30955 	int rval = 0;
30956 	diskaddr_t	cap;
30957 	uint32_t	lbasize;
30958 	sd_ssc_t	*ssc;
30959 
30960 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
30961 	if (un == NULL)
30962 		return (ENXIO);
30963 
30964 	if (cmd != TG_READ && cmd != TG_WRITE)
30965 		return (EINVAL);
30966 
30967 	ssc = sd_ssc_init(un);
30968 	mutex_enter(SD_MUTEX(un));
30969 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
30970 		mutex_exit(SD_MUTEX(un));
30971 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
30972 		    &lbasize, path_flag);
30973 		if (rval != 0)
30974 			goto done1;
30975 		mutex_enter(SD_MUTEX(un));
30976 		sd_update_block_info(un, lbasize, cap);
30977 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
30978 			mutex_exit(SD_MUTEX(un));
30979 			rval = EIO;
30980 			goto done;
30981 		}
30982 	}
30983 
30984 	if (NOT_DEVBSIZE(un)) {
30985 		/*
30986 		 * sys_blocksize != tgt_blocksize, need to re-adjust
30987 		 * blkno and save the index to beginning of dk_label
30988 		 */
30989 		first_byte  = SD_SYSBLOCKS2BYTES(start_block);
30990 		real_addr = first_byte / un->un_tgt_blocksize;
30991 
30992 		end_block = (first_byte + reqlength +
30993 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
30994 
30995 		/* round up buffer size to multiple of target block size */
30996 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
30997 
30998 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
30999 		    "label_addr: 0x%x allocation size: 0x%x\n",
31000 		    real_addr, buffer_size);
31001 
31002 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
31003 		    (reqlength % un->un_tgt_blocksize) != 0)
31004 			/* the request is not aligned */
31005 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
31006 	}
31007 
31008 	/*
31009 	 * The MMC standard allows READ CAPACITY to be
31010 	 * inaccurate by a bounded amount (in the interest of
31011 	 * response latency).  As a result, failed READs are
31012 	 * commonplace (due to the reading of metadata and not
31013 	 * data). Depending on the per-Vendor/drive Sense data,
31014 	 * the failed READ can cause many (unnecessary) retries.
31015 	 */
31016 
31017 	if (ISCD(un) && (cmd == TG_READ) &&
31018 	    (un->un_f_blockcount_is_valid == TRUE) &&
31019 	    ((start_block == (un->un_blockcount - 1))||
31020 	    (start_block == (un->un_blockcount - 2)))) {
31021 			path_flag = SD_PATH_DIRECT_PRIORITY;
31022 	}
31023 
31024 	mutex_exit(SD_MUTEX(un));
31025 	if (cmd == TG_READ) {
31026 		rval = sd_send_scsi_READ(ssc, (dkl != NULL)? dkl: bufaddr,
31027 		    buffer_size, real_addr, path_flag);
31028 		if (dkl != NULL)
31029 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
31030 			    real_addr), bufaddr, reqlength);
31031 	} else {
31032 		if (dkl) {
31033 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
31034 			    real_addr, path_flag);
31035 			if (rval) {
31036 				goto done1;
31037 			}
31038 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
31039 			    real_addr), reqlength);
31040 		}
31041 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL)? dkl: bufaddr,
31042 		    buffer_size, real_addr, path_flag);
31043 	}
31044 
31045 done1:
31046 	if (dkl != NULL)
31047 		kmem_free(dkl, buffer_size);
31048 
31049 	if (rval != 0) {
31050 		if (rval == EIO)
31051 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
31052 		else
31053 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31054 	}
31055 done:
31056 	sd_ssc_fini(ssc);
31057 	return (rval);
31058 }
31059 
31060 
31061 static int
31062 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
31063 {
31064 
31065 	struct sd_lun *un;
31066 	diskaddr_t	cap;
31067 	uint32_t	lbasize;
31068 	int		path_flag = (int)(uintptr_t)tg_cookie;
31069 	int		ret = 0;
31070 
31071 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31072 	if (un == NULL)
31073 		return (ENXIO);
31074 
31075 	switch (cmd) {
31076 	case TG_GETPHYGEOM:
31077 	case TG_GETVIRTGEOM:
31078 	case TG_GETCAPACITY:
31079 	case TG_GETBLOCKSIZE:
31080 		mutex_enter(SD_MUTEX(un));
31081 
31082 		if ((un->un_f_blockcount_is_valid == TRUE) &&
31083 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
31084 			cap = un->un_blockcount;
31085 			lbasize = un->un_tgt_blocksize;
31086 			mutex_exit(SD_MUTEX(un));
31087 		} else {
31088 			sd_ssc_t	*ssc;
31089 			mutex_exit(SD_MUTEX(un));
31090 			ssc = sd_ssc_init(un);
31091 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31092 			    &lbasize, path_flag);
31093 			if (ret != 0) {
31094 				if (ret == EIO)
31095 					sd_ssc_assessment(ssc,
31096 					    SD_FMT_STATUS_CHECK);
31097 				else
31098 					sd_ssc_assessment(ssc,
31099 					    SD_FMT_IGNORE);
31100 				sd_ssc_fini(ssc);
31101 				return (ret);
31102 			}
31103 			sd_ssc_fini(ssc);
31104 			mutex_enter(SD_MUTEX(un));
31105 			sd_update_block_info(un, lbasize, cap);
31106 			if ((un->un_f_blockcount_is_valid == FALSE) ||
31107 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
31108 				mutex_exit(SD_MUTEX(un));
31109 				return (EIO);
31110 			}
31111 			mutex_exit(SD_MUTEX(un));
31112 		}
31113 
31114 		if (cmd == TG_GETCAPACITY) {
31115 			*(diskaddr_t *)arg = cap;
31116 			return (0);
31117 		}
31118 
31119 		if (cmd == TG_GETBLOCKSIZE) {
31120 			*(uint32_t *)arg = lbasize;
31121 			return (0);
31122 		}
31123 
31124 		if (cmd == TG_GETPHYGEOM)
31125 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
31126 			    cap, lbasize, path_flag);
31127 		else
31128 			/* TG_GETVIRTGEOM */
31129 			ret = sd_get_virtual_geometry(un,
31130 			    (cmlb_geom_t *)arg, cap, lbasize);
31131 
31132 		return (ret);
31133 
31134 	case TG_GETATTR:
31135 		mutex_enter(SD_MUTEX(un));
31136 		((tg_attribute_t *)arg)->media_is_writable =
31137 		    un->un_f_mmc_writable_media;
31138 		((tg_attribute_t *)arg)->media_is_solid_state =
31139 		    un->un_f_is_solid_state;
31140 		mutex_exit(SD_MUTEX(un));
31141 		return (0);
31142 	default:
31143 		return (ENOTTY);
31144 
31145 	}
31146 }
31147 
31148 /*
31149  *    Function: sd_ssc_ereport_post
31150  *
31151  * Description: Will be called when SD driver need to post an ereport.
31152  *
31153  *    Context: Kernel thread or interrupt context.
31154  */
31155 
31156 #define	DEVID_IF_KNOWN(d) "devid", DATA_TYPE_STRING, (d) ? (d) : "unknown"
31157 
31158 static void
31159 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
31160 {
31161 	int uscsi_path_instance = 0;
31162 	uchar_t	uscsi_pkt_reason;
31163 	uint32_t uscsi_pkt_state;
31164 	uint32_t uscsi_pkt_statistics;
31165 	uint64_t uscsi_ena;
31166 	uchar_t op_code;
31167 	uint8_t *sensep;
31168 	union scsi_cdb *cdbp;
31169 	uint_t cdblen = 0;
31170 	uint_t senlen = 0;
31171 	struct sd_lun *un;
31172 	dev_info_t *dip;
31173 	char *devid;
31174 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
31175 	    SSC_FLAGS_INVALID_STATUS |
31176 	    SSC_FLAGS_INVALID_SENSE |
31177 	    SSC_FLAGS_INVALID_DATA;
31178 	char assessment[16];
31179 
31180 	ASSERT(ssc != NULL);
31181 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
31182 	ASSERT(ssc->ssc_uscsi_info != NULL);
31183 
31184 	un = ssc->ssc_un;
31185 	ASSERT(un != NULL);
31186 
31187 	dip = un->un_sd->sd_dev;
31188 
31189 	/*
31190 	 * Get the devid:
31191 	 *	devid will only be passed to non-transport error reports.
31192 	 */
31193 	devid = DEVI(dip)->devi_devid_str;
31194 
31195 	/*
31196 	 * If we are syncing or dumping, the command will not be executed
31197 	 * so we bypass this situation.
31198 	 */
31199 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
31200 	    (un->un_state == SD_STATE_DUMPING))
31201 		return;
31202 
31203 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
31204 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
31205 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
31206 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
31207 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
31208 
31209 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
31210 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
31211 
31212 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
31213 	if (cdbp == NULL) {
31214 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
31215 		    "sd_ssc_ereport_post meet empty cdb\n");
31216 		return;
31217 	}
31218 
31219 	op_code = cdbp->scc_cmd;
31220 
31221 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
31222 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
31223 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
31224 
31225 	if (senlen > 0)
31226 		ASSERT(sensep != NULL);
31227 
31228 	/*
31229 	 * Initialize drv_assess to corresponding values.
31230 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
31231 	 * on the sense-key returned back.
31232 	 */
31233 	switch (drv_assess) {
31234 		case SD_FM_DRV_RECOVERY:
31235 			(void) sprintf(assessment, "%s", "recovered");
31236 			break;
31237 		case SD_FM_DRV_RETRY:
31238 			(void) sprintf(assessment, "%s", "retry");
31239 			break;
31240 		case SD_FM_DRV_NOTICE:
31241 			(void) sprintf(assessment, "%s", "info");
31242 			break;
31243 		case SD_FM_DRV_FATAL:
31244 		default:
31245 			(void) sprintf(assessment, "%s", "unknown");
31246 	}
31247 	/*
31248 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
31249 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
31250 	 * driver-assessment will always be "recovered" here.
31251 	 */
31252 	if (drv_assess == SD_FM_DRV_RECOVERY) {
31253 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31254 		    "cmd.disk.recovered", uscsi_ena, devid, NULL,
31255 		    DDI_NOSLEEP, NULL,
31256 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31257 		    DEVID_IF_KNOWN(devid),
31258 		    "driver-assessment", DATA_TYPE_STRING, assessment,
31259 		    "op-code", DATA_TYPE_UINT8, op_code,
31260 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31261 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31262 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31263 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31264 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31265 		    NULL);
31266 		return;
31267 	}
31268 
31269 	/*
31270 	 * If there is un-expected/un-decodable data, we should post
31271 	 * ereport.io.scsi.cmd.disk.dev.uderr.
31272 	 * driver-assessment will be set based on parameter drv_assess.
31273 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
31274 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
31275 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
31276 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
31277 	 */
31278 	if (ssc->ssc_flags & ssc_invalid_flags) {
31279 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
31280 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31281 			    NULL, "cmd.disk.dev.uderr", uscsi_ena, devid,
31282 			    NULL, DDI_NOSLEEP, NULL,
31283 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31284 			    DEVID_IF_KNOWN(devid),
31285 			    "driver-assessment", DATA_TYPE_STRING,
31286 			    drv_assess == SD_FM_DRV_FATAL ?
31287 			    "fail" : assessment,
31288 			    "op-code", DATA_TYPE_UINT8, op_code,
31289 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31290 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31291 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31292 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31293 			    "pkt-stats", DATA_TYPE_UINT32,
31294 			    uscsi_pkt_statistics,
31295 			    "stat-code", DATA_TYPE_UINT8,
31296 			    ssc->ssc_uscsi_cmd->uscsi_status,
31297 			    "un-decode-info", DATA_TYPE_STRING,
31298 			    ssc->ssc_info,
31299 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31300 			    senlen, sensep,
31301 			    NULL);
31302 		} else {
31303 			/*
31304 			 * For other type of invalid data, the
31305 			 * un-decode-value field would be empty because the
31306 			 * un-decodable content could be seen from upper
31307 			 * level payload or inside un-decode-info.
31308 			 */
31309 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31310 			    NULL,
31311 			    "cmd.disk.dev.uderr", uscsi_ena, devid,
31312 			    NULL, DDI_NOSLEEP, NULL,
31313 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31314 			    DEVID_IF_KNOWN(devid),
31315 			    "driver-assessment", DATA_TYPE_STRING,
31316 			    drv_assess == SD_FM_DRV_FATAL ?
31317 			    "fail" : assessment,
31318 			    "op-code", DATA_TYPE_UINT8, op_code,
31319 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31320 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31321 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31322 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31323 			    "pkt-stats", DATA_TYPE_UINT32,
31324 			    uscsi_pkt_statistics,
31325 			    "stat-code", DATA_TYPE_UINT8,
31326 			    ssc->ssc_uscsi_cmd->uscsi_status,
31327 			    "un-decode-info", DATA_TYPE_STRING,
31328 			    ssc->ssc_info,
31329 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31330 			    0, NULL,
31331 			    NULL);
31332 		}
31333 		ssc->ssc_flags &= ~ssc_invalid_flags;
31334 		return;
31335 	}
31336 
31337 	if (uscsi_pkt_reason != CMD_CMPLT ||
31338 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
31339 		/*
31340 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
31341 		 * set inside sd_start_cmds due to errors(bad packet or
31342 		 * fatal transport error), we should take it as a
31343 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
31344 		 * driver-assessment will be set based on drv_assess.
31345 		 * We will set devid to NULL because it is a transport
31346 		 * error.
31347 		 */
31348 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
31349 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
31350 
31351 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31352 		    "cmd.disk.tran", uscsi_ena, NULL, NULL, DDI_NOSLEEP, NULL,
31353 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31354 		    DEVID_IF_KNOWN(devid),
31355 		    "driver-assessment", DATA_TYPE_STRING,
31356 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31357 		    "op-code", DATA_TYPE_UINT8, op_code,
31358 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31359 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31360 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31361 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
31362 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31363 		    NULL);
31364 	} else {
31365 		/*
31366 		 * If we got here, we have a completed command, and we need
31367 		 * to further investigate the sense data to see what kind
31368 		 * of ereport we should post.
31369 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr
31370 		 * if sense-key == 0x3.
31371 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
31372 		 * driver-assessment will be set based on the parameter
31373 		 * drv_assess.
31374 		 */
31375 		if (senlen > 0) {
31376 			/*
31377 			 * Here we have sense data available.
31378 			 */
31379 			uint8_t sense_key;
31380 			sense_key = scsi_sense_key(sensep);
31381 			if (sense_key == 0x3) {
31382 				/*
31383 				 * sense-key == 0x3(medium error),
31384 				 * driver-assessment should be "fatal" if
31385 				 * drv_assess is SD_FM_DRV_FATAL.
31386 				 */
31387 				scsi_fm_ereport_post(un->un_sd,
31388 				    uscsi_path_instance, NULL,
31389 				    "cmd.disk.dev.rqs.merr",
31390 				    uscsi_ena, devid, NULL, DDI_NOSLEEP, NULL,
31391 				    FM_VERSION, DATA_TYPE_UINT8,
31392 				    FM_EREPORT_VERS0,
31393 				    DEVID_IF_KNOWN(devid),
31394 				    "driver-assessment",
31395 				    DATA_TYPE_STRING,
31396 				    drv_assess == SD_FM_DRV_FATAL ?
31397 				    "fatal" : assessment,
31398 				    "op-code",
31399 				    DATA_TYPE_UINT8, op_code,
31400 				    "cdb",
31401 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31402 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31403 				    "pkt-reason",
31404 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31405 				    "pkt-state",
31406 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31407 				    "pkt-stats",
31408 				    DATA_TYPE_UINT32,
31409 				    uscsi_pkt_statistics,
31410 				    "stat-code",
31411 				    DATA_TYPE_UINT8,
31412 				    ssc->ssc_uscsi_cmd->uscsi_status,
31413 				    "key",
31414 				    DATA_TYPE_UINT8,
31415 				    scsi_sense_key(sensep),
31416 				    "asc",
31417 				    DATA_TYPE_UINT8,
31418 				    scsi_sense_asc(sensep),
31419 				    "ascq",
31420 				    DATA_TYPE_UINT8,
31421 				    scsi_sense_ascq(sensep),
31422 				    "sense-data",
31423 				    DATA_TYPE_UINT8_ARRAY,
31424 				    senlen, sensep,
31425 				    "lba",
31426 				    DATA_TYPE_UINT64,
31427 				    ssc->ssc_uscsi_info->ui_lba,
31428 				    NULL);
31429 				} else {
31430 					/*
31431 					 * if sense-key == 0x4(hardware
31432 					 * error), driver-assessment should
31433 					 * be "fatal" if drv_assess is
31434 					 * SD_FM_DRV_FATAL.
31435 					 */
31436 					scsi_fm_ereport_post(un->un_sd,
31437 					    uscsi_path_instance, NULL,
31438 					    "cmd.disk.dev.rqs.derr",
31439 					    uscsi_ena, devid,
31440 					    NULL, DDI_NOSLEEP, NULL,
31441 					    FM_VERSION,
31442 					    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31443 					    DEVID_IF_KNOWN(devid),
31444 					    "driver-assessment",
31445 					    DATA_TYPE_STRING,
31446 					    drv_assess == SD_FM_DRV_FATAL ?
31447 					    (sense_key == 0x4 ?
31448 					    "fatal" : "fail") : assessment,
31449 					    "op-code",
31450 					    DATA_TYPE_UINT8, op_code,
31451 					    "cdb",
31452 					    DATA_TYPE_UINT8_ARRAY, cdblen,
31453 					    ssc->ssc_uscsi_cmd->uscsi_cdb,
31454 					    "pkt-reason",
31455 					    DATA_TYPE_UINT8, uscsi_pkt_reason,
31456 					    "pkt-state",
31457 					    DATA_TYPE_UINT8, uscsi_pkt_state,
31458 					    "pkt-stats",
31459 					    DATA_TYPE_UINT32,
31460 					    uscsi_pkt_statistics,
31461 					    "stat-code",
31462 					    DATA_TYPE_UINT8,
31463 					    ssc->ssc_uscsi_cmd->uscsi_status,
31464 					    "key",
31465 					    DATA_TYPE_UINT8,
31466 					    scsi_sense_key(sensep),
31467 					    "asc",
31468 					    DATA_TYPE_UINT8,
31469 					    scsi_sense_asc(sensep),
31470 					    "ascq",
31471 					    DATA_TYPE_UINT8,
31472 					    scsi_sense_ascq(sensep),
31473 					    "sense-data",
31474 					    DATA_TYPE_UINT8_ARRAY,
31475 					    senlen, sensep,
31476 					    NULL);
31477 				}
31478 		} else {
31479 			/*
31480 			 * For stat_code == STATUS_GOOD, this is not a
31481 			 * hardware error.
31482 			 */
31483 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
31484 				return;
31485 
31486 			/*
31487 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
31488 			 * stat-code but with sense data unavailable.
31489 			 * driver-assessment will be set based on parameter
31490 			 * drv_assess.
31491 			 */
31492 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31493 			    NULL,
31494 			    "cmd.disk.dev.serr", uscsi_ena,
31495 			    devid, NULL, DDI_NOSLEEP, NULL,
31496 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31497 			    DEVID_IF_KNOWN(devid),
31498 			    "driver-assessment", DATA_TYPE_STRING,
31499 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31500 			    "op-code", DATA_TYPE_UINT8, op_code,
31501 			    "cdb",
31502 			    DATA_TYPE_UINT8_ARRAY,
31503 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31504 			    "pkt-reason",
31505 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
31506 			    "pkt-state",
31507 			    DATA_TYPE_UINT8, uscsi_pkt_state,
31508 			    "pkt-stats",
31509 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
31510 			    "stat-code",
31511 			    DATA_TYPE_UINT8,
31512 			    ssc->ssc_uscsi_cmd->uscsi_status,
31513 			    NULL);
31514 		}
31515 	}
31516 }
31517 
31518 /*
31519  *     Function: sd_ssc_extract_info
31520  *
31521  * Description: Extract information available to help generate ereport.
31522  *
31523  *     Context: Kernel thread or interrupt context.
31524  */
31525 static void
31526 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
31527     struct buf *bp, struct sd_xbuf *xp)
31528 {
31529 	size_t senlen = 0;
31530 	union scsi_cdb *cdbp;
31531 	int path_instance;
31532 	/*
31533 	 * Need scsi_cdb_size array to determine the cdb length.
31534 	 */
31535 	extern uchar_t	scsi_cdb_size[];
31536 
31537 	ASSERT(un != NULL);
31538 	ASSERT(pktp != NULL);
31539 	ASSERT(bp != NULL);
31540 	ASSERT(xp != NULL);
31541 	ASSERT(ssc != NULL);
31542 	ASSERT(mutex_owned(SD_MUTEX(un)));
31543 
31544 	/*
31545 	 * Transfer the cdb buffer pointer here.
31546 	 */
31547 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
31548 
31549 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
31550 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
31551 
31552 	/*
31553 	 * Transfer the sense data buffer pointer if sense data is available,
31554 	 * calculate the sense data length first.
31555 	 */
31556 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
31557 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
31558 		/*
31559 		 * For arq case, we will enter here.
31560 		 */
31561 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
31562 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
31563 		} else {
31564 			senlen = SENSE_LENGTH;
31565 		}
31566 	} else {
31567 		/*
31568 		 * For non-arq case, we will enter this branch.
31569 		 */
31570 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
31571 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
31572 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
31573 		}
31574 
31575 	}
31576 
31577 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
31578 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
31579 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
31580 
31581 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
31582 
31583 	/*
31584 	 * Only transfer path_instance when scsi_pkt was properly allocated.
31585 	 */
31586 	path_instance = pktp->pkt_path_instance;
31587 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
31588 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
31589 	else
31590 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
31591 
31592 	/*
31593 	 * Copy in the other fields we may need when posting ereport.
31594 	 */
31595 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
31596 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
31597 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
31598 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
31599 
31600 	/*
31601 	 * For partially read/write command, we will not create ena
31602 	 * in case of a successful command be reconized as recovered.
31603 	 */
31604 	if ((pktp->pkt_reason == CMD_CMPLT) &&
31605 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
31606 	    (senlen == 0)) {
31607 		return;
31608 	}
31609 
31610 	/*
31611 	 * To associate ereports of a single command execution flow, we
31612 	 * need a shared ena for a specific command.
31613 	 */
31614 	if (xp->xb_ena == 0)
31615 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
31616 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
31617 }
31618 
31619 
31620 /*
31621  *     Function: sd_check_solid_state
31622  *
31623  * Description: Query the optional INQUIRY VPD page 0xb1. If the device
31624  *              supports VPD page 0xb1, sd examines the MEDIUM ROTATION
31625  *              RATE. If the MEDIUM ROTATION RATE is 1, sd assumes the
31626  *              device is a solid state drive.
31627  *
31628  *     Context: Kernel thread or interrupt context.
31629  */
31630 
31631 static void
31632 sd_check_solid_state(sd_ssc_t *ssc)
31633 {
31634 	int		rval		= 0;
31635 	uchar_t		*inqb1		= NULL;
31636 	size_t		inqb1_len	= MAX_INQUIRY_SIZE;
31637 	size_t		inqb1_resid	= 0;
31638 	struct sd_lun	*un;
31639 
31640 	ASSERT(ssc != NULL);
31641 	un = ssc->ssc_un;
31642 	ASSERT(un != NULL);
31643 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31644 
31645 	mutex_enter(SD_MUTEX(un));
31646 	un->un_f_is_solid_state = FALSE;
31647 
31648 	if (ISCD(un)) {
31649 		mutex_exit(SD_MUTEX(un));
31650 		return;
31651 	}
31652 
31653 	if (sd_check_vpd_page_support(ssc) == 0 &&
31654 	    un->un_vpd_page_mask & SD_VPD_DEV_CHARACTER_PG) {
31655 		mutex_exit(SD_MUTEX(un));
31656 		/* collect page b1 data */
31657 		inqb1 = kmem_zalloc(inqb1_len, KM_SLEEP);
31658 
31659 		rval = sd_send_scsi_INQUIRY(ssc, inqb1, inqb1_len,
31660 		    0x01, 0xB1, &inqb1_resid);
31661 
31662 		if (rval == 0 && (inqb1_len - inqb1_resid > 5)) {
31663 			SD_TRACE(SD_LOG_COMMON, un,
31664 			    "sd_check_solid_state: \
31665 			    successfully get VPD page: %x \
31666 			    PAGE LENGTH: %x BYTE 4: %x \
31667 			    BYTE 5: %x", inqb1[1], inqb1[3], inqb1[4],
31668 			    inqb1[5]);
31669 
31670 			mutex_enter(SD_MUTEX(un));
31671 			/*
31672 			 * Check the MEDIUM ROTATION RATE. If it is set
31673 			 * to 1, the device is a solid state drive.
31674 			 */
31675 			if (inqb1[4] == 0 && inqb1[5] == 1) {
31676 				un->un_f_is_solid_state = TRUE;
31677 				/* solid state drives don't need disksort */
31678 				un->un_f_disksort_disabled = TRUE;
31679 			}
31680 			mutex_exit(SD_MUTEX(un));
31681 		} else if (rval != 0) {
31682 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31683 		}
31684 
31685 		kmem_free(inqb1, inqb1_len);
31686 	} else {
31687 		mutex_exit(SD_MUTEX(un));
31688 	}
31689 }
31690 
31691 /*
31692  *	Function: sd_check_emulation_mode
31693  *
31694  *   Description: Check whether the SSD is at emulation mode
31695  *		  by issuing READ_CAPACITY_16 to see whether
31696  *		  we can get physical block size of the drive.
31697  *
31698  *	 Context: Kernel thread or interrupt context.
31699  */
31700 
31701 static void
31702 sd_check_emulation_mode(sd_ssc_t *ssc)
31703 {
31704 	int		rval = 0;
31705 	uint64_t	capacity;
31706 	uint_t		lbasize;
31707 	uint_t		pbsize;
31708 	int		i;
31709 	int		devid_len;
31710 	struct sd_lun	*un;
31711 
31712 	ASSERT(ssc != NULL);
31713 	un = ssc->ssc_un;
31714 	ASSERT(un != NULL);
31715 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31716 
31717 	mutex_enter(SD_MUTEX(un));
31718 	if (ISCD(un)) {
31719 		mutex_exit(SD_MUTEX(un));
31720 		return;
31721 	}
31722 
31723 	if (un->un_f_descr_format_supported) {
31724 		mutex_exit(SD_MUTEX(un));
31725 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
31726 		    &pbsize, SD_PATH_DIRECT);
31727 		mutex_enter(SD_MUTEX(un));
31728 
31729 		if (rval != 0) {
31730 			un->un_phy_blocksize = DEV_BSIZE;
31731 		} else {
31732 			if (!ISP2(pbsize % DEV_BSIZE) || pbsize == 0) {
31733 				un->un_phy_blocksize = DEV_BSIZE;
31734 			} else {
31735 				un->un_phy_blocksize = pbsize;
31736 			}
31737 		}
31738 	}
31739 
31740 	for (i = 0; i < sd_flash_dev_table_size; i++) {
31741 		devid_len = (int)strlen(sd_flash_dev_table[i]);
31742 		if (sd_sdconf_id_match(un, sd_flash_dev_table[i], devid_len)
31743 		    == SD_SUCCESS) {
31744 			un->un_phy_blocksize = SSD_SECSIZE;
31745 			if (un->un_f_is_solid_state &&
31746 			    un->un_phy_blocksize != un->un_tgt_blocksize)
31747 				un->un_f_enable_rmw = TRUE;
31748 		}
31749 	}
31750 
31751 	mutex_exit(SD_MUTEX(un));
31752 }
31753