xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 22e991d5bb9d07bf7dd2a65bc080922753a3100b)
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 (c) 2011 Bayard G. Bell.  All rights reserved.
27  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
28  * Copyright 2012 DEY Storage Systems, Inc.  All rights reserved.
29  * Copyright 2019 Joyent, Inc.
30  * Copyright 2019 Racktop Systems
31  * Copyright 2022 OmniOS Community Edition (OmniOSce) Association.
32  * Copyright 2022 Tintri by DDN, Inc. All rights reserved.
33  */
34 /*
35  * Copyright 2011 cyril.galibern@opensvc.com
36  */
37 
38 /*
39  * SCSI disk target driver.
40  */
41 #include <sys/scsi/scsi.h>
42 #include <sys/dkbad.h>
43 #include <sys/dklabel.h>
44 #include <sys/dkio.h>
45 #include <sys/fdio.h>
46 #include <sys/cdio.h>
47 #include <sys/mhd.h>
48 #include <sys/vtoc.h>
49 #include <sys/dktp/fdisk.h>
50 #include <sys/kstat.h>
51 #include <sys/vtrace.h>
52 #include <sys/note.h>
53 #include <sys/thread.h>
54 #include <sys/proc.h>
55 #include <sys/efi_partition.h>
56 #include <sys/var.h>
57 #include <sys/aio_req.h>
58 #include <sys/dkioc_free_util.h>
59 
60 #ifdef __lock_lint
61 #define	_LP64
62 #define	__amd64
63 #endif
64 
65 #if (defined(__fibre))
66 /* Note: is there a leadville version of the following? */
67 #include <sys/fc4/fcal_linkapp.h>
68 #endif
69 #include <sys/taskq.h>
70 #include <sys/uuid.h>
71 #include <sys/byteorder.h>
72 #include <sys/sdt.h>
73 
74 #include "sd_xbuf.h"
75 
76 #include <sys/scsi/targets/sddef.h>
77 #include <sys/cmlb.h>
78 #include <sys/sysevent/eventdefs.h>
79 #include <sys/sysevent/dev.h>
80 
81 #include <sys/fm/protocol.h>
82 
83 /*
84  * Loadable module info.
85  */
86 #if (defined(__fibre))
87 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver"
88 #else /* !__fibre */
89 #define	SD_MODULE_NAME	"SCSI Disk Driver"
90 #endif /* !__fibre */
91 
92 /*
93  * Define the interconnect type, to allow the driver to distinguish
94  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
95  *
96  * This is really for backward compatibility. In the future, the driver
97  * should actually check the "interconnect-type" property as reported by
98  * the HBA; however at present this property is not defined by all HBAs,
99  * so we will use this #define (1) to permit the driver to run in
100  * backward-compatibility mode; and (2) to print a notification message
101  * if an FC HBA does not support the "interconnect-type" property.  The
102  * behavior of the driver will be to assume parallel SCSI behaviors unless
103  * the "interconnect-type" property is defined by the HBA **AND** has a
104  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
105  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
106  * Channel behaviors (as per the old ssd).  (Note that the
107  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
108  * will result in the driver assuming parallel SCSI behaviors.)
109  *
110  * (see common/sys/scsi/impl/services.h)
111  *
112  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
113  * since some FC HBAs may already support that, and there is some code in
114  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
115  * default would confuse that code, and besides things should work fine
116  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
117  * "interconnect_type" property.
118  *
119  */
120 #if (defined(__fibre))
121 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
122 #else
123 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
124 #endif
125 
126 /*
127  * The name of the driver, established from the module name in _init.
128  */
129 static	char *sd_label			= NULL;
130 
131 /*
132  * Driver name is unfortunately prefixed on some driver.conf properties.
133  */
134 #if (defined(__fibre))
135 #define	sd_max_xfer_size		ssd_max_xfer_size
136 #define	sd_config_list			ssd_config_list
137 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
138 static	char *sd_config_list		= "ssd-config-list";
139 #else
140 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
141 static	char *sd_config_list		= "sd-config-list";
142 #endif
143 
144 /*
145  * Driver global variables
146  */
147 
148 #if (defined(__fibre))
149 /*
150  * These #defines are to avoid namespace collisions that occur because this
151  * code is currently used to compile two separate driver modules: sd and ssd.
152  * All global variables need to be treated this way (even if declared static)
153  * in order to allow the debugger to resolve the names properly.
154  * It is anticipated that in the near future the ssd module will be obsoleted,
155  * at which time this namespace issue should go away.
156  */
157 #define	sd_state			ssd_state
158 #define	sd_io_time			ssd_io_time
159 #define	sd_failfast_enable		ssd_failfast_enable
160 #define	sd_ua_retry_count		ssd_ua_retry_count
161 #define	sd_report_pfa			ssd_report_pfa
162 #define	sd_max_throttle			ssd_max_throttle
163 #define	sd_min_throttle			ssd_min_throttle
164 #define	sd_rot_delay			ssd_rot_delay
165 
166 #define	sd_retry_on_reservation_conflict	\
167 					ssd_retry_on_reservation_conflict
168 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
169 #define	sd_resv_conflict_name		ssd_resv_conflict_name
170 
171 #define	sd_component_mask		ssd_component_mask
172 #define	sd_level_mask			ssd_level_mask
173 #define	sd_debug_un			ssd_debug_un
174 #define	sd_error_level			ssd_error_level
175 
176 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
177 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
178 
179 #define	sd_tr				ssd_tr
180 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
181 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
182 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
183 #define	sd_check_media_time		ssd_check_media_time
184 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
185 #define	sd_label_mutex			ssd_label_mutex
186 #define	sd_detach_mutex			ssd_detach_mutex
187 #define	sd_log_buf			ssd_log_buf
188 #define	sd_log_mutex			ssd_log_mutex
189 
190 #define	sd_disk_table			ssd_disk_table
191 #define	sd_disk_table_size		ssd_disk_table_size
192 #define	sd_sense_mutex			ssd_sense_mutex
193 #define	sd_cdbtab			ssd_cdbtab
194 
195 #define	sd_cb_ops			ssd_cb_ops
196 #define	sd_ops				ssd_ops
197 #define	sd_additional_codes		ssd_additional_codes
198 #define	sd_tgops			ssd_tgops
199 
200 #define	sd_minor_data			ssd_minor_data
201 #define	sd_minor_data_efi		ssd_minor_data_efi
202 
203 #define	sd_tq				ssd_tq
204 #define	sd_wmr_tq			ssd_wmr_tq
205 #define	sd_taskq_name			ssd_taskq_name
206 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
207 #define	sd_taskq_minalloc		ssd_taskq_minalloc
208 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
209 
210 #define	sd_dump_format_string		ssd_dump_format_string
211 
212 #define	sd_iostart_chain		ssd_iostart_chain
213 #define	sd_iodone_chain			ssd_iodone_chain
214 
215 #define	sd_pm_idletime			ssd_pm_idletime
216 
217 #define	sd_force_pm_supported		ssd_force_pm_supported
218 
219 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
220 
221 #define	sd_ssc_init			ssd_ssc_init
222 #define	sd_ssc_send			ssd_ssc_send
223 #define	sd_ssc_fini			ssd_ssc_fini
224 #define	sd_ssc_assessment		ssd_ssc_assessment
225 #define	sd_ssc_post			ssd_ssc_post
226 #define	sd_ssc_print			ssd_ssc_print
227 #define	sd_ssc_ereport_post		ssd_ssc_ereport_post
228 #define	sd_ssc_set_info			ssd_ssc_set_info
229 #define	sd_ssc_extract_info		ssd_ssc_extract_info
230 
231 #endif
232 
233 #ifdef	SDDEBUG
234 int	sd_force_pm_supported		= 0;
235 #endif	/* SDDEBUG */
236 
237 void *sd_state				= NULL;
238 int sd_io_time				= SD_IO_TIME;
239 int sd_failfast_enable			= 1;
240 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
241 int sd_report_pfa			= 1;
242 int sd_max_throttle			= SD_MAX_THROTTLE;
243 int sd_min_throttle			= SD_MIN_THROTTLE;
244 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
245 int sd_qfull_throttle_enable		= TRUE;
246 
247 int sd_retry_on_reservation_conflict	= 1;
248 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
249 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
250 
251 static int sd_dtype_optical_bind	= -1;
252 
253 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
254 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
255 
256 /*
257  * Global data for debug logging. To enable debug printing, sd_component_mask
258  * and sd_level_mask should be set to the desired bit patterns as outlined in
259  * sddef.h.
260  */
261 uint_t	sd_component_mask		= 0x0;
262 uint_t	sd_level_mask			= 0x0;
263 struct	sd_lun *sd_debug_un		= NULL;
264 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
265 
266 /* Note: these may go away in the future... */
267 static uint32_t	sd_xbuf_active_limit	= 512;
268 static uint32_t sd_xbuf_reserve_limit	= 16;
269 
270 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
271 
272 /*
273  * Timer value used to reset the throttle after it has been reduced
274  * (typically in response to TRAN_BUSY or STATUS_QFULL)
275  */
276 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
277 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
278 
279 /*
280  * Interval value associated with the media change scsi watch.
281  */
282 static int sd_check_media_time		= 3000000;
283 
284 /*
285  * Wait value used for in progress operations during a DDI_SUSPEND
286  */
287 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
288 
289 /*
290  * sd_label_mutex protects a static buffer used in the disk label
291  * component of the driver
292  */
293 static kmutex_t sd_label_mutex;
294 
295 /*
296  * sd_detach_mutex protects un_layer_count, un_detach_count, and
297  * un_opens_in_progress in the sd_lun structure.
298  */
299 static kmutex_t sd_detach_mutex;
300 
301 _NOTE(MUTEX_PROTECTS_DATA(sd_detach_mutex,
302 	sd_lun::{un_layer_count un_detach_count un_opens_in_progress}))
303 
304 /*
305  * Global buffer and mutex for debug logging
306  */
307 static char	sd_log_buf[1024];
308 static kmutex_t	sd_log_mutex;
309 
310 /*
311  * Structs and globals for recording attached lun information.
312  * This maintains a chain. Each node in the chain represents a SCSI controller.
313  * The structure records the number of luns attached to each target connected
314  * with the controller.
315  * For parallel scsi device only.
316  */
317 struct sd_scsi_hba_tgt_lun {
318 	struct sd_scsi_hba_tgt_lun	*next;
319 	dev_info_t			*pdip;
320 	int				nlun[NTARGETS_WIDE];
321 };
322 
323 /*
324  * Flag to indicate the lun is attached or detached
325  */
326 #define	SD_SCSI_LUN_ATTACH	0
327 #define	SD_SCSI_LUN_DETACH	1
328 
329 static kmutex_t	sd_scsi_target_lun_mutex;
330 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
331 
332 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
333     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
334 
335 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
336     sd_scsi_target_lun_head))
337 
338 /*
339  * "Smart" Probe Caching structs, globals, #defines, etc.
340  * For parallel scsi and non-self-identify device only.
341  */
342 
343 /*
344  * The following resources and routines are implemented to support
345  * "smart" probing, which caches the scsi_probe() results in an array,
346  * in order to help avoid long probe times.
347  */
348 struct sd_scsi_probe_cache {
349 	struct	sd_scsi_probe_cache	*next;
350 	dev_info_t	*pdip;
351 	int		cache[NTARGETS_WIDE];
352 };
353 
354 static kmutex_t	sd_scsi_probe_cache_mutex;
355 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
356 
357 /*
358  * Really we only need protection on the head of the linked list, but
359  * better safe than sorry.
360  */
361 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
362     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
363 
364 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
365     sd_scsi_probe_cache_head))
366 
367 /*
368  * Power attribute table
369  */
370 static sd_power_attr_ss sd_pwr_ss = {
371 	{ "NAME=spindle-motor", "0=off", "1=on", NULL },
372 	{0, 100},
373 	{30, 0},
374 	{20000, 0}
375 };
376 
377 static sd_power_attr_pc sd_pwr_pc = {
378 	{ "NAME=spindle-motor", "0=stopped", "1=standby", "2=idle",
379 		"3=active", NULL },
380 	{0, 0, 0, 100},
381 	{90, 90, 20, 0},
382 	{15000, 15000, 1000, 0}
383 };
384 
385 /*
386  * Power level to power condition
387  */
388 static int sd_pl2pc[] = {
389 	SD_TARGET_START_VALID,
390 	SD_TARGET_STANDBY,
391 	SD_TARGET_IDLE,
392 	SD_TARGET_ACTIVE
393 };
394 
395 /*
396  * Vendor specific data name property declarations
397  */
398 
399 #if defined(__fibre) || defined(__x86)
400 
401 static sd_tunables seagate_properties = {
402 	SEAGATE_THROTTLE_VALUE,
403 	0,
404 	0,
405 	0,
406 	0,
407 	0,
408 	0,
409 	0,
410 	0
411 };
412 
413 
414 static sd_tunables fujitsu_properties = {
415 	FUJITSU_THROTTLE_VALUE,
416 	0,
417 	0,
418 	0,
419 	0,
420 	0,
421 	0,
422 	0,
423 	0
424 };
425 
426 static sd_tunables ibm_properties = {
427 	IBM_THROTTLE_VALUE,
428 	0,
429 	0,
430 	0,
431 	0,
432 	0,
433 	0,
434 	0,
435 	0
436 };
437 
438 static sd_tunables sve_properties = {
439 	SVE_THROTTLE_VALUE,
440 	0,
441 	0,
442 	SVE_BUSY_RETRIES,
443 	SVE_RESET_RETRY_COUNT,
444 	SVE_RESERVE_RELEASE_TIME,
445 	SVE_MIN_THROTTLE_VALUE,
446 	SVE_DISKSORT_DISABLED_FLAG,
447 	0
448 };
449 
450 static sd_tunables maserati_properties = {
451 	0,
452 	0,
453 	0,
454 	0,
455 	0,
456 	0,
457 	0,
458 	MASERATI_DISKSORT_DISABLED_FLAG,
459 	MASERATI_LUN_RESET_ENABLED_FLAG
460 };
461 
462 static sd_tunables pirus_properties = {
463 	PIRUS_THROTTLE_VALUE,
464 	0,
465 	PIRUS_NRR_COUNT,
466 	PIRUS_BUSY_RETRIES,
467 	PIRUS_RESET_RETRY_COUNT,
468 	0,
469 	PIRUS_MIN_THROTTLE_VALUE,
470 	PIRUS_DISKSORT_DISABLED_FLAG,
471 	PIRUS_LUN_RESET_ENABLED_FLAG
472 };
473 
474 #endif
475 
476 #if (defined(__sparc) && !defined(__fibre)) || \
477 	(defined(__x86))
478 
479 
480 static sd_tunables elite_properties = {
481 	ELITE_THROTTLE_VALUE,
482 	0,
483 	0,
484 	0,
485 	0,
486 	0,
487 	0,
488 	0,
489 	0
490 };
491 
492 static sd_tunables st31200n_properties = {
493 	ST31200N_THROTTLE_VALUE,
494 	0,
495 	0,
496 	0,
497 	0,
498 	0,
499 	0,
500 	0,
501 	0
502 };
503 
504 #endif /* Fibre or not */
505 
506 static sd_tunables lsi_properties_scsi = {
507 	LSI_THROTTLE_VALUE,
508 	0,
509 	LSI_NOTREADY_RETRIES,
510 	0,
511 	0,
512 	0,
513 	0,
514 	0,
515 	0
516 };
517 
518 static sd_tunables symbios_properties = {
519 	SYMBIOS_THROTTLE_VALUE,
520 	0,
521 	SYMBIOS_NOTREADY_RETRIES,
522 	0,
523 	0,
524 	0,
525 	0,
526 	0,
527 	0
528 };
529 
530 static sd_tunables lsi_properties = {
531 	0,
532 	0,
533 	LSI_NOTREADY_RETRIES,
534 	0,
535 	0,
536 	0,
537 	0,
538 	0,
539 	0
540 };
541 
542 static sd_tunables lsi_oem_properties = {
543 	0,
544 	0,
545 	LSI_OEM_NOTREADY_RETRIES,
546 	0,
547 	0,
548 	0,
549 	0,
550 	0,
551 	0,
552 	1
553 };
554 
555 
556 
557 #if (defined(SD_PROP_TST))
558 
559 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
560 #define	SD_TST_THROTTLE_VAL	16
561 #define	SD_TST_NOTREADY_VAL	12
562 #define	SD_TST_BUSY_VAL		60
563 #define	SD_TST_RST_RETRY_VAL	36
564 #define	SD_TST_RSV_REL_TIME	60
565 
566 static sd_tunables tst_properties = {
567 	SD_TST_THROTTLE_VAL,
568 	SD_TST_CTYPE_VAL,
569 	SD_TST_NOTREADY_VAL,
570 	SD_TST_BUSY_VAL,
571 	SD_TST_RST_RETRY_VAL,
572 	SD_TST_RSV_REL_TIME,
573 	0,
574 	0,
575 	0
576 };
577 #endif
578 
579 /* This is similar to the ANSI toupper implementation */
580 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
581 
582 /*
583  * Static Driver Configuration Table
584  *
585  * This is the table of disks which need throttle adjustment (or, perhaps
586  * something else as defined by the flags at a future time.)  device_id
587  * is a string consisting of concatenated vid (vendor), pid (product/model)
588  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
589  * the parts of the string are as defined by the sizes in the scsi_inquiry
590  * structure.  Device type is searched as far as the device_id string is
591  * defined.  Flags defines which values are to be set in the driver from the
592  * properties list.
593  *
594  * Entries below which begin and end with a "*" are a special case.
595  * These do not have a specific vendor, and the string which follows
596  * can appear anywhere in the 16 byte PID portion of the inquiry data.
597  *
598  * Entries below which begin and end with a " " (blank) are a special
599  * case. The comparison function will treat multiple consecutive blanks
600  * as equivalent to a single blank. For example, this causes a
601  * sd_disk_table entry of " NEC CDROM " to match a device's id string
602  * of  "NEC       CDROM".
603  *
604  * Note: The MD21 controller type has been obsoleted.
605  *	 ST318202F is a Legacy device
606  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
607  *	 made with an FC connection. The entries here are a legacy.
608  */
609 static sd_disk_config_t sd_disk_table[] = {
610 #if defined(__fibre) || defined(__x86)
611 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
612 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
613 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
614 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
615 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
616 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
617 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
618 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
619 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
620 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
621 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
622 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
623 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
624 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
625 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
626 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
627 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
628 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
629 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
630 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
631 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
632 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
633 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
634 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
635 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
636 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
637 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
638 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
639 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
640 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
641 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
642 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
643 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
644 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
645 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
646 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
647 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
648 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
649 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
650 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
651 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
652 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
653 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
654 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
655 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
656 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
657 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
658 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
659 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
660 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
661 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
662 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
663 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
664 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
665 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
666 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
667 		SD_CONF_BSET_BSY_RETRY_COUNT|
668 		SD_CONF_BSET_RST_RETRIES|
669 		SD_CONF_BSET_RSV_REL_TIME|
670 		SD_CONF_BSET_MIN_THROTTLE|
671 		SD_CONF_BSET_DISKSORT_DISABLED,
672 		&sve_properties },
673 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
674 		SD_CONF_BSET_LUN_RESET_ENABLED,
675 		&maserati_properties },
676 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
677 		SD_CONF_BSET_NRR_COUNT|
678 		SD_CONF_BSET_BSY_RETRY_COUNT|
679 		SD_CONF_BSET_RST_RETRIES|
680 		SD_CONF_BSET_MIN_THROTTLE|
681 		SD_CONF_BSET_DISKSORT_DISABLED|
682 		SD_CONF_BSET_LUN_RESET_ENABLED,
683 		&pirus_properties },
684 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
685 		SD_CONF_BSET_NRR_COUNT|
686 		SD_CONF_BSET_BSY_RETRY_COUNT|
687 		SD_CONF_BSET_RST_RETRIES|
688 		SD_CONF_BSET_MIN_THROTTLE|
689 		SD_CONF_BSET_DISKSORT_DISABLED|
690 		SD_CONF_BSET_LUN_RESET_ENABLED,
691 		&pirus_properties },
692 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
693 		SD_CONF_BSET_NRR_COUNT|
694 		SD_CONF_BSET_BSY_RETRY_COUNT|
695 		SD_CONF_BSET_RST_RETRIES|
696 		SD_CONF_BSET_MIN_THROTTLE|
697 		SD_CONF_BSET_DISKSORT_DISABLED|
698 		SD_CONF_BSET_LUN_RESET_ENABLED,
699 		&pirus_properties },
700 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
701 		SD_CONF_BSET_NRR_COUNT|
702 		SD_CONF_BSET_BSY_RETRY_COUNT|
703 		SD_CONF_BSET_RST_RETRIES|
704 		SD_CONF_BSET_MIN_THROTTLE|
705 		SD_CONF_BSET_DISKSORT_DISABLED|
706 		SD_CONF_BSET_LUN_RESET_ENABLED,
707 		&pirus_properties },
708 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
709 		SD_CONF_BSET_NRR_COUNT|
710 		SD_CONF_BSET_BSY_RETRY_COUNT|
711 		SD_CONF_BSET_RST_RETRIES|
712 		SD_CONF_BSET_MIN_THROTTLE|
713 		SD_CONF_BSET_DISKSORT_DISABLED|
714 		SD_CONF_BSET_LUN_RESET_ENABLED,
715 		&pirus_properties },
716 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
717 		SD_CONF_BSET_NRR_COUNT|
718 		SD_CONF_BSET_BSY_RETRY_COUNT|
719 		SD_CONF_BSET_RST_RETRIES|
720 		SD_CONF_BSET_MIN_THROTTLE|
721 		SD_CONF_BSET_DISKSORT_DISABLED|
722 		SD_CONF_BSET_LUN_RESET_ENABLED,
723 		&pirus_properties },
724 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
725 	{ "SUN     SUN_6180", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
726 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
727 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
728 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
729 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
730 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
731 #endif /* fibre or NON-sparc platforms */
732 #if ((defined(__sparc) && !defined(__fibre)) ||\
733 	(defined(__x86)))
734 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
735 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
736 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
737 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
738 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
739 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
740 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
741 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
742 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
743 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
744 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
745 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
746 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
747 	    &symbios_properties },
748 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
749 	    &lsi_properties_scsi },
750 #if defined(__x86)
751 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
752 				    | SD_CONF_BSET_READSUB_BCD
753 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
754 				    | SD_CONF_BSET_NO_READ_HEADER
755 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
756 
757 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
758 				    | SD_CONF_BSET_READSUB_BCD
759 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
760 				    | SD_CONF_BSET_NO_READ_HEADER
761 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
762 #endif /* __x86 */
763 #endif /* sparc NON-fibre or NON-sparc platforms */
764 
765 #if (defined(SD_PROP_TST))
766 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
767 				| SD_CONF_BSET_CTYPE
768 				| SD_CONF_BSET_NRR_COUNT
769 				| SD_CONF_BSET_FAB_DEVID
770 				| SD_CONF_BSET_NOCACHE
771 				| SD_CONF_BSET_BSY_RETRY_COUNT
772 				| SD_CONF_BSET_PLAYMSF_BCD
773 				| SD_CONF_BSET_READSUB_BCD
774 				| SD_CONF_BSET_READ_TOC_TRK_BCD
775 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
776 				| SD_CONF_BSET_NO_READ_HEADER
777 				| SD_CONF_BSET_READ_CD_XD4
778 				| SD_CONF_BSET_RST_RETRIES
779 				| SD_CONF_BSET_RSV_REL_TIME
780 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
781 #endif
782 };
783 
784 static const int sd_disk_table_size =
785 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
786 
787 /*
788  * Emulation mode disk drive VID/PID table
789  */
790 static char sd_flash_dev_table[][25] = {
791 	"ATA     MARVELL SD88SA02",
792 	"MARVELL SD88SA02",
793 	"TOSHIBA THNSNV05",
794 };
795 
796 static const int sd_flash_dev_table_size =
797 	sizeof (sd_flash_dev_table) / sizeof (sd_flash_dev_table[0]);
798 
799 #define	SD_INTERCONNECT_PARALLEL	0
800 #define	SD_INTERCONNECT_FABRIC		1
801 #define	SD_INTERCONNECT_FIBRE		2
802 #define	SD_INTERCONNECT_SSA		3
803 #define	SD_INTERCONNECT_SATA		4
804 #define	SD_INTERCONNECT_SAS		5
805 
806 #define	SD_IS_PARALLEL_SCSI(un)		\
807 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
808 #define	SD_IS_SERIAL(un)		\
809 	(((un)->un_interconnect_type == SD_INTERCONNECT_SATA) ||\
810 	((un)->un_interconnect_type == SD_INTERCONNECT_SAS))
811 
812 /*
813  * Definitions used by device id registration routines
814  */
815 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
816 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
817 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
818 
819 static kmutex_t sd_sense_mutex = {0};
820 
821 /*
822  * Macros for updates of the driver state
823  */
824 #define	New_state(un, s)        \
825 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
826 #define	Restore_state(un)	\
827 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
828 
829 static struct sd_cdbinfo sd_cdbtab[] = {
830 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
831 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
832 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
833 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
834 };
835 
836 /*
837  * Specifies the number of seconds that must have elapsed since the last
838  * cmd. has completed for a device to be declared idle to the PM framework.
839  */
840 static int sd_pm_idletime = 1;
841 
842 /*
843  * Internal function prototypes
844  */
845 
846 #if (defined(__fibre))
847 /*
848  * These #defines are to avoid namespace collisions that occur because this
849  * code is currently used to compile two separate driver modules: sd and ssd.
850  * All function names need to be treated this way (even if declared static)
851  * in order to allow the debugger to resolve the names properly.
852  * It is anticipated that in the near future the ssd module will be obsoleted,
853  * at which time this ugliness should go away.
854  */
855 #define	sd_log_trace			ssd_log_trace
856 #define	sd_log_info			ssd_log_info
857 #define	sd_log_err			ssd_log_err
858 #define	sdprobe				ssdprobe
859 #define	sdinfo				ssdinfo
860 #define	sd_prop_op			ssd_prop_op
861 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
862 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
863 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
864 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
865 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
866 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
867 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
868 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
869 #define	sd_spin_up_unit			ssd_spin_up_unit
870 #define	sd_enable_descr_sense		ssd_enable_descr_sense
871 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
872 #define	sd_set_mmc_caps			ssd_set_mmc_caps
873 #define	sd_read_unit_properties		ssd_read_unit_properties
874 #define	sd_process_sdconf_file		ssd_process_sdconf_file
875 #define	sd_process_sdconf_table		ssd_process_sdconf_table
876 #define	sd_sdconf_id_match		ssd_sdconf_id_match
877 #define	sd_blank_cmp			ssd_blank_cmp
878 #define	sd_chk_vers1_data		ssd_chk_vers1_data
879 #define	sd_set_vers1_properties		ssd_set_vers1_properties
880 #define	sd_check_bdc_vpd		ssd_check_bdc_vpd
881 #define	sd_check_emulation_mode		ssd_check_emulation_mode
882 
883 #define	sd_get_physical_geometry	ssd_get_physical_geometry
884 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
885 #define	sd_update_block_info		ssd_update_block_info
886 #define	sd_register_devid		ssd_register_devid
887 #define	sd_get_devid			ssd_get_devid
888 #define	sd_create_devid			ssd_create_devid
889 #define	sd_write_deviceid		ssd_write_deviceid
890 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
891 #define	sd_setup_pm			ssd_setup_pm
892 #define	sd_create_pm_components		ssd_create_pm_components
893 #define	sd_ddi_suspend			ssd_ddi_suspend
894 #define	sd_ddi_resume			ssd_ddi_resume
895 #define	sd_pm_state_change		ssd_pm_state_change
896 #define	sdpower				ssdpower
897 #define	sdattach			ssdattach
898 #define	sddetach			ssddetach
899 #define	sd_unit_attach			ssd_unit_attach
900 #define	sd_unit_detach			ssd_unit_detach
901 #define	sd_set_unit_attributes		ssd_set_unit_attributes
902 #define	sd_create_errstats		ssd_create_errstats
903 #define	sd_set_errstats			ssd_set_errstats
904 #define	sd_set_pstats			ssd_set_pstats
905 #define	sddump				ssddump
906 #define	sd_scsi_poll			ssd_scsi_poll
907 #define	sd_send_polled_RQS		ssd_send_polled_RQS
908 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
909 #define	sd_init_event_callbacks		ssd_init_event_callbacks
910 #define	sd_event_callback		ssd_event_callback
911 #define	sd_cache_control		ssd_cache_control
912 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
913 #define	sd_get_write_cache_changeable	ssd_get_write_cache_changeable
914 #define	sd_get_nv_sup			ssd_get_nv_sup
915 #define	sd_make_device			ssd_make_device
916 #define	sdopen				ssdopen
917 #define	sdclose				ssdclose
918 #define	sd_ready_and_valid		ssd_ready_and_valid
919 #define	sdmin				ssdmin
920 #define	sdread				ssdread
921 #define	sdwrite				ssdwrite
922 #define	sdaread				ssdaread
923 #define	sdawrite			ssdawrite
924 #define	sdstrategy			ssdstrategy
925 #define	sdioctl				ssdioctl
926 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
927 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
928 #define	sd_checksum_iostart		ssd_checksum_iostart
929 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
930 #define	sd_pm_iostart			ssd_pm_iostart
931 #define	sd_core_iostart			ssd_core_iostart
932 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
933 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
934 #define	sd_checksum_iodone		ssd_checksum_iodone
935 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
936 #define	sd_pm_iodone			ssd_pm_iodone
937 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
938 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
939 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
940 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
941 #define	sd_buf_iodone			ssd_buf_iodone
942 #define	sd_uscsi_strategy		ssd_uscsi_strategy
943 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
944 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
945 #define	sd_uscsi_iodone			ssd_uscsi_iodone
946 #define	sd_xbuf_strategy		ssd_xbuf_strategy
947 #define	sd_xbuf_init			ssd_xbuf_init
948 #define	sd_pm_entry			ssd_pm_entry
949 #define	sd_pm_exit			ssd_pm_exit
950 
951 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
952 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
953 
954 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
955 #define	sdintr				ssdintr
956 #define	sd_start_cmds			ssd_start_cmds
957 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
958 #define	sd_bioclone_alloc		ssd_bioclone_alloc
959 #define	sd_bioclone_free		ssd_bioclone_free
960 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
961 #define	sd_shadow_buf_free		ssd_shadow_buf_free
962 #define	sd_print_transport_rejected_message	\
963 					ssd_print_transport_rejected_message
964 #define	sd_retry_command		ssd_retry_command
965 #define	sd_set_retry_bp			ssd_set_retry_bp
966 #define	sd_send_request_sense_command	ssd_send_request_sense_command
967 #define	sd_start_retry_command		ssd_start_retry_command
968 #define	sd_start_direct_priority_command	\
969 					ssd_start_direct_priority_command
970 #define	sd_return_failed_command	ssd_return_failed_command
971 #define	sd_return_failed_command_no_restart	\
972 					ssd_return_failed_command_no_restart
973 #define	sd_return_command		ssd_return_command
974 #define	sd_sync_with_callback		ssd_sync_with_callback
975 #define	sdrunout			ssdrunout
976 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
977 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
978 #define	sd_reduce_throttle		ssd_reduce_throttle
979 #define	sd_restore_throttle		ssd_restore_throttle
980 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
981 #define	sd_init_cdb_limits		ssd_init_cdb_limits
982 #define	sd_pkt_status_good		ssd_pkt_status_good
983 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
984 #define	sd_pkt_status_busy		ssd_pkt_status_busy
985 #define	sd_pkt_status_reservation_conflict	\
986 					ssd_pkt_status_reservation_conflict
987 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
988 #define	sd_handle_request_sense		ssd_handle_request_sense
989 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
990 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
991 #define	sd_validate_sense_data		ssd_validate_sense_data
992 #define	sd_decode_sense			ssd_decode_sense
993 #define	sd_print_sense_msg		ssd_print_sense_msg
994 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
995 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
996 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
997 #define	sd_sense_key_medium_or_hardware_error	\
998 					ssd_sense_key_medium_or_hardware_error
999 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
1000 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
1001 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
1002 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
1003 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
1004 #define	sd_sense_key_default		ssd_sense_key_default
1005 #define	sd_print_retry_msg		ssd_print_retry_msg
1006 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
1007 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
1008 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
1009 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
1010 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
1011 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
1012 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
1013 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
1014 #define	sd_pkt_reason_default		ssd_pkt_reason_default
1015 #define	sd_reset_target			ssd_reset_target
1016 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
1017 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
1018 #define	sd_taskq_create			ssd_taskq_create
1019 #define	sd_taskq_delete			ssd_taskq_delete
1020 #define	sd_target_change_task		ssd_target_change_task
1021 #define	sd_log_dev_status_event		ssd_log_dev_status_event
1022 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
1023 #define	sd_log_eject_request_event	ssd_log_eject_request_event
1024 #define	sd_media_change_task		ssd_media_change_task
1025 #define	sd_handle_mchange		ssd_handle_mchange
1026 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
1027 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
1028 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
1029 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
1030 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
1031 					sd_send_scsi_feature_GET_CONFIGURATION
1032 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
1033 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
1034 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
1035 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
1036 					ssd_send_scsi_PERSISTENT_RESERVE_IN
1037 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
1038 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
1039 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
1040 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
1041 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1042 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1043 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1044 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1045 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1046 #define	sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION	\
1047 				ssd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
1048 #define	sd_gesn_media_data_valid	ssd_gesn_media_data_valid
1049 #define	sd_alloc_rqs			ssd_alloc_rqs
1050 #define	sd_free_rqs			ssd_free_rqs
1051 #define	sd_dump_memory			ssd_dump_memory
1052 #define	sd_get_media_info_com		ssd_get_media_info_com
1053 #define	sd_get_media_info		ssd_get_media_info
1054 #define	sd_get_media_info_ext		ssd_get_media_info_ext
1055 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1056 #define	sd_nvpair_str_decode		ssd_nvpair_str_decode
1057 #define	sd_set_properties		ssd_set_properties
1058 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1059 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1060 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1061 #define	sd_check_mhd			ssd_check_mhd
1062 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1063 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1064 #define	sd_sname			ssd_sname
1065 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1066 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1067 #define	sd_take_ownership		ssd_take_ownership
1068 #define	sd_reserve_release		ssd_reserve_release
1069 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1070 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1071 #define	sd_persistent_reservation_in_read_keys	\
1072 					ssd_persistent_reservation_in_read_keys
1073 #define	sd_persistent_reservation_in_read_resv	\
1074 					ssd_persistent_reservation_in_read_resv
1075 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1076 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1077 #define	sd_mhdioc_release		ssd_mhdioc_release
1078 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1079 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1080 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1081 #define	sr_change_blkmode		ssr_change_blkmode
1082 #define	sr_change_speed			ssr_change_speed
1083 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1084 #define	sr_pause_resume			ssr_pause_resume
1085 #define	sr_play_msf			ssr_play_msf
1086 #define	sr_play_trkind			ssr_play_trkind
1087 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1088 #define	sr_read_subchannel		ssr_read_subchannel
1089 #define	sr_read_tocentry		ssr_read_tocentry
1090 #define	sr_read_tochdr			ssr_read_tochdr
1091 #define	sr_read_cdda			ssr_read_cdda
1092 #define	sr_read_cdxa			ssr_read_cdxa
1093 #define	sr_read_mode1			ssr_read_mode1
1094 #define	sr_read_mode2			ssr_read_mode2
1095 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1096 #define	sr_sector_mode			ssr_sector_mode
1097 #define	sr_eject			ssr_eject
1098 #define	sr_ejected			ssr_ejected
1099 #define	sr_check_wp			ssr_check_wp
1100 #define	sd_watch_request_submit		ssd_watch_request_submit
1101 #define	sd_check_media			ssd_check_media
1102 #define	sd_media_watch_cb		ssd_media_watch_cb
1103 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1104 #define	sr_volume_ctrl			ssr_volume_ctrl
1105 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1106 #define	sd_log_page_supported		ssd_log_page_supported
1107 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1108 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1109 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1110 #define	sd_range_lock			ssd_range_lock
1111 #define	sd_get_range			ssd_get_range
1112 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1113 #define	sd_range_unlock			ssd_range_unlock
1114 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1115 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1116 
1117 #define	sd_iostart_chain		ssd_iostart_chain
1118 #define	sd_iodone_chain			ssd_iodone_chain
1119 #define	sd_initpkt_map			ssd_initpkt_map
1120 #define	sd_destroypkt_map		ssd_destroypkt_map
1121 #define	sd_chain_type_map		ssd_chain_type_map
1122 #define	sd_chain_index_map		ssd_chain_index_map
1123 
1124 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1125 #define	sd_failfast_flushq		ssd_failfast_flushq
1126 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1127 
1128 #define	sd_is_lsi			ssd_is_lsi
1129 #define	sd_tg_rdwr			ssd_tg_rdwr
1130 #define	sd_tg_getinfo			ssd_tg_getinfo
1131 #define	sd_rmw_msg_print_handler	ssd_rmw_msg_print_handler
1132 
1133 #endif	/* #if (defined(__fibre)) */
1134 
1135 typedef struct unmap_param_hdr_s {
1136 	uint16_t	uph_data_len;
1137 	uint16_t	uph_descr_data_len;
1138 	uint32_t	uph_reserved;
1139 } unmap_param_hdr_t;
1140 
1141 typedef struct unmap_blk_descr_s {
1142 	uint64_t	ubd_lba;
1143 	uint32_t	ubd_lba_cnt;
1144 	uint32_t	ubd_reserved;
1145 } unmap_blk_descr_t;
1146 
1147 /* Max number of block descriptors in UNMAP command */
1148 #define	SD_UNMAP_MAX_DESCR \
1149 	((UINT16_MAX - sizeof (unmap_param_hdr_t)) / sizeof (unmap_blk_descr_t))
1150 /* Max size of the UNMAP parameter list in bytes */
1151 #define	SD_UNMAP_PARAM_LIST_MAXSZ	(sizeof (unmap_param_hdr_t) + \
1152 	SD_UNMAP_MAX_DESCR * sizeof (unmap_blk_descr_t))
1153 
1154 int _init(void);
1155 int _fini(void);
1156 int _info(struct modinfo *modinfop);
1157 
1158 /*PRINTFLIKE3*/
1159 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1160 /*PRINTFLIKE3*/
1161 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1162 /*PRINTFLIKE3*/
1163 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1164 
1165 static int sdprobe(dev_info_t *devi);
1166 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1167     void **result);
1168 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1169     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1170 
1171 /*
1172  * Smart probe for parallel scsi
1173  */
1174 static void sd_scsi_probe_cache_init(void);
1175 static void sd_scsi_probe_cache_fini(void);
1176 static void sd_scsi_clear_probe_cache(void);
1177 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1178 
1179 /*
1180  * Attached luns on target for parallel scsi
1181  */
1182 static void sd_scsi_target_lun_init(void);
1183 static void sd_scsi_target_lun_fini(void);
1184 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1185 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1186 
1187 static int sd_spin_up_unit(sd_ssc_t *ssc);
1188 
1189 /*
1190  * Using sd_ssc_init to establish sd_ssc_t struct
1191  * Using sd_ssc_send to send uscsi internal command
1192  * Using sd_ssc_fini to free sd_ssc_t struct
1193  */
1194 static sd_ssc_t *sd_ssc_init(struct sd_lun *un);
1195 static int sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd,
1196     int flag, enum uio_seg dataspace, int path_flag);
1197 static void sd_ssc_fini(sd_ssc_t *ssc);
1198 
1199 /*
1200  * Using sd_ssc_assessment to set correct type-of-assessment
1201  * Using sd_ssc_post to post ereport & system log
1202  *       sd_ssc_post will call sd_ssc_print to print system log
1203  *       sd_ssc_post will call sd_ssd_ereport_post to post ereport
1204  */
1205 static void sd_ssc_assessment(sd_ssc_t *ssc,
1206     enum sd_type_assessment tp_assess);
1207 
1208 static void sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess);
1209 static void sd_ssc_print(sd_ssc_t *ssc, int sd_severity);
1210 static void sd_ssc_ereport_post(sd_ssc_t *ssc,
1211     enum sd_driver_assessment drv_assess);
1212 
1213 /*
1214  * Using sd_ssc_set_info to mark an un-decodable-data error.
1215  * Using sd_ssc_extract_info to transfer information from internal
1216  *       data structures to sd_ssc_t.
1217  */
1218 static void sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp,
1219     const char *fmt, ...);
1220 static void sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un,
1221     struct scsi_pkt *pktp, struct buf *bp, struct sd_xbuf *xp);
1222 
1223 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1224     enum uio_seg dataspace, int path_flag);
1225 
1226 #ifdef _LP64
1227 static void	sd_enable_descr_sense(sd_ssc_t *ssc);
1228 static void	sd_reenable_dsense_task(void *arg);
1229 #endif /* _LP64 */
1230 
1231 static void	sd_set_mmc_caps(sd_ssc_t *ssc);
1232 
1233 static void sd_read_unit_properties(struct sd_lun *un);
1234 static int  sd_process_sdconf_file(struct sd_lun *un);
1235 static void sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str);
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_check_vpd_page_support(sd_ssc_t *ssc);
1253 
1254 static void sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi);
1255 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1256 
1257 static int  sd_ddi_suspend(dev_info_t *devi);
1258 static int  sd_ddi_resume(dev_info_t *devi);
1259 static int  sd_pm_state_change(struct sd_lun *un, int level, int flag);
1260 static int  sdpower(dev_info_t *devi, int component, int level);
1261 
1262 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1263 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1264 static int  sd_unit_attach(dev_info_t *devi);
1265 static int  sd_unit_detach(dev_info_t *devi);
1266 
1267 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1268 static void sd_create_errstats(struct sd_lun *un, int instance);
1269 static void sd_set_errstats(struct sd_lun *un);
1270 static void sd_set_pstats(struct sd_lun *un);
1271 
1272 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1273 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1274 static int  sd_send_polled_RQS(struct sd_lun *un);
1275 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1276 
1277 #if (defined(__fibre))
1278 /*
1279  * Event callbacks (photon)
1280  */
1281 static void sd_init_event_callbacks(struct sd_lun *un);
1282 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1283 #endif
1284 
1285 /*
1286  * Defines for sd_cache_control
1287  */
1288 
1289 #define	SD_CACHE_ENABLE		1
1290 #define	SD_CACHE_DISABLE	0
1291 #define	SD_CACHE_NOCHANGE	-1
1292 
1293 static int   sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag);
1294 static int   sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled);
1295 static void  sd_get_write_cache_changeable(sd_ssc_t *ssc, int *is_changeable);
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_bdc_vpd(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, int c),
1403     void *user_arg, int failure_code,  clock_t retry_delay,
1404     void (*statp)(kstat_io_t *));
1405 
1406 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1407     clock_t retry_delay, void (*statp)(kstat_io_t *));
1408 
1409 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1410     struct scsi_pkt *pktp);
1411 static void sd_start_retry_command(void *arg);
1412 static void sd_start_direct_priority_command(void *arg);
1413 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1414     int errcode);
1415 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1416     struct buf *bp, int errcode);
1417 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1418 static void sd_sync_with_callback(struct sd_lun *un);
1419 static int sdrunout(caddr_t arg);
1420 
1421 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1422 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1423 
1424 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1425 static void sd_restore_throttle(void *arg);
1426 
1427 static void sd_init_cdb_limits(struct sd_lun *un);
1428 
1429 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1430     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1431 
1432 /*
1433  * Error handling functions
1434  */
1435 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1436     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1437 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1438     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1439 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1440     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1441 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1442     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1443 
1444 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1445     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1446 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1447     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1448 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1449     struct sd_xbuf *xp, size_t actual_len);
1450 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1451     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1452 
1453 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1454     void *arg, int code);
1455 
1456 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1457     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1458 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1459     uint8_t *sense_datap,
1460     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1461 static void sd_sense_key_not_ready(struct sd_lun *un,
1462     uint8_t *sense_datap,
1463     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1464 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1465     uint8_t *sense_datap,
1466     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1467 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1468     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1469 static void sd_sense_key_unit_attention(struct sd_lun *un,
1470     uint8_t *sense_datap,
1471     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1472 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1473     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1474 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1475     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1476 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1477     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1478 static void sd_sense_key_default(struct sd_lun *un,
1479     uint8_t *sense_datap,
1480     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1481 
1482 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1483     void *arg, int flag);
1484 
1485 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1486     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1487 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1488     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1489 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1490     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1491 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1492     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1493 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1494     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1495 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1496     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1497 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1498     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1499 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1500     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1501 
1502 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1503 
1504 static void sd_start_stop_unit_callback(void *arg);
1505 static void sd_start_stop_unit_task(void *arg);
1506 
1507 static void sd_taskq_create(void);
1508 static void sd_taskq_delete(void);
1509 static void sd_target_change_task(void *arg);
1510 static void sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag);
1511 static void sd_log_lun_expansion_event(struct sd_lun *un, int km_flag);
1512 static void sd_log_eject_request_event(struct sd_lun *un, int km_flag);
1513 static void sd_media_change_task(void *arg);
1514 
1515 static int sd_handle_mchange(struct sd_lun *un);
1516 static int sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag);
1517 static int sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp,
1518     uint32_t *lbap, int path_flag);
1519 static int sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
1520     uint32_t *lbap, uint32_t *psp, int path_flag);
1521 static int sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag,
1522     int flag, int path_flag);
1523 static int sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr,
1524     size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1525 static int sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag);
1526 static int sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc,
1527     uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1528 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc,
1529     uchar_t usr_cmd, uchar_t *usr_bufp);
1530 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1531     struct dk_callback *dkc);
1532 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1533 static int sd_send_scsi_UNMAP(dev_t dev, sd_ssc_t *ssc, dkioc_free_list_t *dfl,
1534     int flag);
1535 static int sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc,
1536     struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1537     uchar_t *bufaddr, uint_t buflen, int path_flag);
1538 static int sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
1539     struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1540     uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1541 static int sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize,
1542     uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1543 static int sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize,
1544     uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1545 static int sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
1546     size_t buflen, daddr_t start_block, int path_flag);
1547 #define	sd_send_scsi_READ(ssc, bufaddr, buflen, start_block, path_flag)	\
1548     sd_send_scsi_RDWR(ssc, SCMD_READ, bufaddr, buflen, start_block, \
1549     path_flag)
1550 #define	sd_send_scsi_WRITE(ssc, bufaddr, buflen, start_block, path_flag)\
1551     sd_send_scsi_RDWR(ssc, SCMD_WRITE, bufaddr, buflen, start_block,\
1552     path_flag)
1553 
1554 static int sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr,
1555     uint16_t buflen, uchar_t page_code, uchar_t page_control,
1556     uint16_t param_ptr, int path_flag);
1557 static int sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc,
1558     uchar_t *bufaddr, size_t buflen, uchar_t class_req);
1559 static boolean_t sd_gesn_media_data_valid(uchar_t *data);
1560 
1561 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1562 static void sd_free_rqs(struct sd_lun *un);
1563 
1564 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1565     uchar_t *data, int len, int fmt);
1566 static void sd_panic_for_res_conflict(struct sd_lun *un);
1567 
1568 /*
1569  * Disk Ioctl Function Prototypes
1570  */
1571 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1572 static int sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag);
1573 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1574 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1575 
1576 /*
1577  * Multi-host Ioctl Prototypes
1578  */
1579 static int sd_check_mhd(dev_t dev, int interval);
1580 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1581 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1582 static char *sd_sname(uchar_t status);
1583 static void sd_mhd_resvd_recover(void *arg);
1584 static void sd_resv_reclaim_thread();
1585 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1586 static int sd_reserve_release(dev_t dev, int cmd);
1587 static void sd_rmv_resv_reclaim_req(dev_t dev);
1588 static void sd_mhd_reset_notify_cb(caddr_t arg);
1589 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1590     mhioc_inkeys_t *usrp, int flag);
1591 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1592     mhioc_inresvs_t *usrp, int flag);
1593 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1594 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1595 static int sd_mhdioc_release(dev_t dev);
1596 static int sd_mhdioc_register_devid(dev_t dev);
1597 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1598 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1599 
1600 /*
1601  * SCSI removable prototypes
1602  */
1603 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1604 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1605 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1606 static int sr_pause_resume(dev_t dev, int mode);
1607 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1608 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1609 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1610 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1611 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1612 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1613 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1614 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1615 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1616 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1617 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1618 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1619 static int sr_eject(dev_t dev);
1620 static void sr_ejected(register struct sd_lun *un);
1621 static int sr_check_wp(dev_t dev);
1622 static opaque_t sd_watch_request_submit(struct sd_lun *un);
1623 static int sd_check_media(dev_t dev, enum dkio_state state);
1624 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1625 static void sd_delayed_cv_broadcast(void *arg);
1626 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1627 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1628 
1629 static int sd_log_page_supported(sd_ssc_t *ssc, int log_page);
1630 
1631 /*
1632  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1633  */
1634 static void sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag);
1635 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1636 static void sd_wm_cache_destructor(void *wm, void *un);
1637 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1638     daddr_t endb, ushort_t typ);
1639 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1640     daddr_t endb);
1641 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1642 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1643 static void sd_read_modify_write_task(void * arg);
1644 static int
1645 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1646     struct buf **bpp);
1647 
1648 
1649 /*
1650  * Function prototypes for failfast support.
1651  */
1652 static void sd_failfast_flushq(struct sd_lun *un);
1653 static int sd_failfast_flushq_callback(struct buf *bp);
1654 
1655 /*
1656  * Function prototypes to check for lsi devices
1657  */
1658 static void sd_is_lsi(struct sd_lun *un);
1659 
1660 /*
1661  * Function prototypes for partial DMA support
1662  */
1663 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1664 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1665 
1666 
1667 /* Function prototypes for cmlb */
1668 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1669     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1670 
1671 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1672 
1673 /*
1674  * For printing RMW warning message timely
1675  */
1676 static void sd_rmw_msg_print_handler(void *arg);
1677 
1678 /*
1679  * Constants for failfast support:
1680  *
1681  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1682  * failfast processing being performed.
1683  *
1684  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1685  * failfast processing on all bufs with B_FAILFAST set.
1686  */
1687 
1688 #define	SD_FAILFAST_INACTIVE		0
1689 #define	SD_FAILFAST_ACTIVE		1
1690 
1691 /*
1692  * Bitmask to control behavior of buf(9S) flushes when a transition to
1693  * the failfast state occurs. Optional bits include:
1694  *
1695  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1696  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1697  * be flushed.
1698  *
1699  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1700  * driver, in addition to the regular wait queue. This includes the xbuf
1701  * queues. When clear, only the driver's wait queue will be flushed.
1702  */
1703 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1704 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1705 
1706 /*
1707  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1708  * to flush all queues within the driver.
1709  */
1710 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1711 
1712 
1713 /*
1714  * SD Testing Fault Injection
1715  */
1716 #ifdef SD_FAULT_INJECTION
1717 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1718 static void sd_faultinjection(struct scsi_pkt *pktp);
1719 static void sd_injection_log(char *buf, struct sd_lun *un);
1720 #endif
1721 
1722 /*
1723  * Device driver ops vector
1724  */
1725 static struct cb_ops sd_cb_ops = {
1726 	sdopen,			/* open */
1727 	sdclose,		/* close */
1728 	sdstrategy,		/* strategy */
1729 	nodev,			/* print */
1730 	sddump,			/* dump */
1731 	sdread,			/* read */
1732 	sdwrite,		/* write */
1733 	sdioctl,		/* ioctl */
1734 	nodev,			/* devmap */
1735 	nodev,			/* mmap */
1736 	nodev,			/* segmap */
1737 	nochpoll,		/* poll */
1738 	sd_prop_op,		/* cb_prop_op */
1739 	0,			/* streamtab  */
1740 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1741 	CB_REV,			/* cb_rev */
1742 	sdaread,		/* async I/O read entry point */
1743 	sdawrite		/* async I/O write entry point */
1744 };
1745 
1746 struct dev_ops sd_ops = {
1747 	DEVO_REV,		/* devo_rev, */
1748 	0,			/* refcnt  */
1749 	sdinfo,			/* info */
1750 	nulldev,		/* identify */
1751 	sdprobe,		/* probe */
1752 	sdattach,		/* attach */
1753 	sddetach,		/* detach */
1754 	nodev,			/* reset */
1755 	&sd_cb_ops,		/* driver operations */
1756 	NULL,			/* bus operations */
1757 	sdpower,		/* power */
1758 	ddi_quiesce_not_needed,		/* quiesce */
1759 };
1760 
1761 /*
1762  * This is the loadable module wrapper.
1763  */
1764 #include <sys/modctl.h>
1765 
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 static cmlb_tg_ops_t sd_tgops = {
1777 	TG_DK_OPS_VERSION_1,
1778 	sd_tg_rdwr,
1779 	sd_tg_getinfo
1780 };
1781 
1782 static struct scsi_asq_key_strings sd_additional_codes[] = {
1783 	0x81, 0, "Logical Unit is Reserved",
1784 	0x85, 0, "Audio Address Not Valid",
1785 	0xb6, 0, "Media Load Mechanism Failed",
1786 	0xB9, 0, "Audio Play Operation Aborted",
1787 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1788 	0x53, 2, "Medium removal prevented",
1789 	0x6f, 0, "Authentication failed during key exchange",
1790 	0x6f, 1, "Key not present",
1791 	0x6f, 2, "Key not established",
1792 	0x6f, 3, "Read without proper authentication",
1793 	0x6f, 4, "Mismatched region to this logical unit",
1794 	0x6f, 5, "Region reset count error",
1795 	0xffff, 0x0, NULL
1796 };
1797 
1798 
1799 /*
1800  * Struct for passing printing information for sense data messages
1801  */
1802 struct sd_sense_info {
1803 	int	ssi_severity;
1804 	int	ssi_pfa_flag;
1805 };
1806 
1807 /*
1808  * Table of function pointers for iostart-side routines. Separate "chains"
1809  * of layered function calls are formed by placing the function pointers
1810  * sequentially in the desired order. Functions are called according to an
1811  * incrementing table index ordering. The last function in each chain must
1812  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1813  * in the sd_iodone_chain[] array.
1814  *
1815  * Note: It may seem more natural to organize both the iostart and iodone
1816  * functions together, into an array of structures (or some similar
1817  * organization) with a common index, rather than two separate arrays which
1818  * must be maintained in synchronization. The purpose of this division is
1819  * to achieve improved performance: individual arrays allows for more
1820  * effective cache line utilization on certain platforms.
1821  */
1822 
1823 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1824 
1825 
1826 static sd_chain_t sd_iostart_chain[] = {
1827 
1828 	/* Chain for buf IO for disk drive targets (PM enabled) */
1829 	sd_mapblockaddr_iostart,	/* Index: 0 */
1830 	sd_pm_iostart,			/* Index: 1 */
1831 	sd_core_iostart,		/* Index: 2 */
1832 
1833 	/* Chain for buf IO for disk drive targets (PM disabled) */
1834 	sd_mapblockaddr_iostart,	/* Index: 3 */
1835 	sd_core_iostart,		/* Index: 4 */
1836 
1837 	/*
1838 	 * Chain for buf IO for removable-media or large sector size
1839 	 * disk drive targets with RMW needed (PM enabled)
1840 	 */
1841 	sd_mapblockaddr_iostart,	/* Index: 5 */
1842 	sd_mapblocksize_iostart,	/* Index: 6 */
1843 	sd_pm_iostart,			/* Index: 7 */
1844 	sd_core_iostart,		/* Index: 8 */
1845 
1846 	/*
1847 	 * Chain for buf IO for removable-media or large sector size
1848 	 * disk drive targets with RMW needed (PM disabled)
1849 	 */
1850 	sd_mapblockaddr_iostart,	/* Index: 9 */
1851 	sd_mapblocksize_iostart,	/* Index: 10 */
1852 	sd_core_iostart,		/* Index: 11 */
1853 
1854 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1855 	sd_mapblockaddr_iostart,	/* Index: 12 */
1856 	sd_checksum_iostart,		/* Index: 13 */
1857 	sd_pm_iostart,			/* Index: 14 */
1858 	sd_core_iostart,		/* Index: 15 */
1859 
1860 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1861 	sd_mapblockaddr_iostart,	/* Index: 16 */
1862 	sd_checksum_iostart,		/* Index: 17 */
1863 	sd_core_iostart,		/* Index: 18 */
1864 
1865 	/* Chain for USCSI commands (all targets) */
1866 	sd_pm_iostart,			/* Index: 19 */
1867 	sd_core_iostart,		/* Index: 20 */
1868 
1869 	/* Chain for checksumming USCSI commands (all targets) */
1870 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1871 	sd_pm_iostart,			/* Index: 22 */
1872 	sd_core_iostart,		/* Index: 23 */
1873 
1874 	/* Chain for "direct" USCSI commands (all targets) */
1875 	sd_core_iostart,		/* Index: 24 */
1876 
1877 	/* Chain for "direct priority" USCSI commands (all targets) */
1878 	sd_core_iostart,		/* Index: 25 */
1879 
1880 	/*
1881 	 * Chain for buf IO for large sector size disk drive targets
1882 	 * with RMW needed with checksumming (PM enabled)
1883 	 */
1884 	sd_mapblockaddr_iostart,	/* Index: 26 */
1885 	sd_mapblocksize_iostart,	/* Index: 27 */
1886 	sd_checksum_iostart,		/* Index: 28 */
1887 	sd_pm_iostart,			/* Index: 29 */
1888 	sd_core_iostart,		/* Index: 30 */
1889 
1890 	/*
1891 	 * Chain for buf IO for large sector size disk drive targets
1892 	 * with RMW needed with checksumming (PM disabled)
1893 	 */
1894 	sd_mapblockaddr_iostart,	/* Index: 31 */
1895 	sd_mapblocksize_iostart,	/* Index: 32 */
1896 	sd_checksum_iostart,		/* Index: 33 */
1897 	sd_core_iostart,		/* Index: 34 */
1898 
1899 };
1900 
1901 /*
1902  * Macros to locate the first function of each iostart chain in the
1903  * sd_iostart_chain[] array. These are located by the index in the array.
1904  */
1905 #define	SD_CHAIN_DISK_IOSTART			0
1906 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1907 #define	SD_CHAIN_MSS_DISK_IOSTART		5
1908 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1909 #define	SD_CHAIN_MSS_DISK_IOSTART_NO_PM		9
1910 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1911 #define	SD_CHAIN_CHKSUM_IOSTART			12
1912 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1913 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1914 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1915 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1916 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1917 #define	SD_CHAIN_MSS_CHKSUM_IOSTART		26
1918 #define	SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM	31
1919 
1920 
1921 /*
1922  * Table of function pointers for the iodone-side routines for the driver-
1923  * internal layering mechanism.  The calling sequence for iodone routines
1924  * uses a decrementing table index, so the last routine called in a chain
1925  * must be at the lowest array index location for that chain.  The last
1926  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1927  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1928  * of the functions in an iodone side chain must correspond to the ordering
1929  * of the iostart routines for that chain.  Note that there is no iodone
1930  * side routine that corresponds to sd_core_iostart(), so there is no
1931  * entry in the table for this.
1932  */
1933 
1934 static sd_chain_t sd_iodone_chain[] = {
1935 
1936 	/* Chain for buf IO for disk drive targets (PM enabled) */
1937 	sd_buf_iodone,			/* Index: 0 */
1938 	sd_mapblockaddr_iodone,		/* Index: 1 */
1939 	sd_pm_iodone,			/* Index: 2 */
1940 
1941 	/* Chain for buf IO for disk drive targets (PM disabled) */
1942 	sd_buf_iodone,			/* Index: 3 */
1943 	sd_mapblockaddr_iodone,		/* Index: 4 */
1944 
1945 	/*
1946 	 * Chain for buf IO for removable-media or large sector size
1947 	 * disk drive targets with RMW needed (PM enabled)
1948 	 */
1949 	sd_buf_iodone,			/* Index: 5 */
1950 	sd_mapblockaddr_iodone,		/* Index: 6 */
1951 	sd_mapblocksize_iodone,		/* Index: 7 */
1952 	sd_pm_iodone,			/* Index: 8 */
1953 
1954 	/*
1955 	 * Chain for buf IO for removable-media or large sector size
1956 	 * disk drive targets with RMW needed (PM disabled)
1957 	 */
1958 	sd_buf_iodone,			/* Index: 9 */
1959 	sd_mapblockaddr_iodone,		/* Index: 10 */
1960 	sd_mapblocksize_iodone,		/* Index: 11 */
1961 
1962 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1963 	sd_buf_iodone,			/* Index: 12 */
1964 	sd_mapblockaddr_iodone,		/* Index: 13 */
1965 	sd_checksum_iodone,		/* Index: 14 */
1966 	sd_pm_iodone,			/* Index: 15 */
1967 
1968 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1969 	sd_buf_iodone,			/* Index: 16 */
1970 	sd_mapblockaddr_iodone,		/* Index: 17 */
1971 	sd_checksum_iodone,		/* Index: 18 */
1972 
1973 	/* Chain for USCSI commands (non-checksum targets) */
1974 	sd_uscsi_iodone,		/* Index: 19 */
1975 	sd_pm_iodone,			/* Index: 20 */
1976 
1977 	/* Chain for USCSI commands (checksum targets) */
1978 	sd_uscsi_iodone,		/* Index: 21 */
1979 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1980 	sd_pm_iodone,			/* Index: 22 */
1981 
1982 	/* Chain for "direct" USCSI commands (all targets) */
1983 	sd_uscsi_iodone,		/* Index: 24 */
1984 
1985 	/* Chain for "direct priority" USCSI commands (all targets) */
1986 	sd_uscsi_iodone,		/* Index: 25 */
1987 
1988 	/*
1989 	 * Chain for buf IO for large sector size disk drive targets
1990 	 * with checksumming (PM enabled)
1991 	 */
1992 	sd_buf_iodone,			/* Index: 26 */
1993 	sd_mapblockaddr_iodone,		/* Index: 27 */
1994 	sd_mapblocksize_iodone,		/* Index: 28 */
1995 	sd_checksum_iodone,		/* Index: 29 */
1996 	sd_pm_iodone,			/* Index: 30 */
1997 
1998 	/*
1999 	 * Chain for buf IO for large sector size disk drive targets
2000 	 * with checksumming (PM disabled)
2001 	 */
2002 	sd_buf_iodone,			/* Index: 31 */
2003 	sd_mapblockaddr_iodone,		/* Index: 32 */
2004 	sd_mapblocksize_iodone,		/* Index: 33 */
2005 	sd_checksum_iodone,		/* Index: 34 */
2006 };
2007 
2008 
2009 /*
2010  * Macros to locate the "first" function in the sd_iodone_chain[] array for
2011  * each iodone-side chain. These are located by the array index, but as the
2012  * iodone side functions are called in a decrementing-index order, the
2013  * highest index number in each chain must be specified (as these correspond
2014  * to the first function in the iodone chain that will be called by the core
2015  * at IO completion time).
2016  */
2017 
2018 #define	SD_CHAIN_DISK_IODONE			2
2019 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
2020 #define	SD_CHAIN_RMMEDIA_IODONE			8
2021 #define	SD_CHAIN_MSS_DISK_IODONE		8
2022 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
2023 #define	SD_CHAIN_MSS_DISK_IODONE_NO_PM		11
2024 #define	SD_CHAIN_CHKSUM_IODONE			15
2025 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
2026 #define	SD_CHAIN_USCSI_CMD_IODONE		20
2027 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
2028 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
2029 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
2030 #define	SD_CHAIN_MSS_CHKSUM_IODONE		30
2031 #define	SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM	34
2032 
2033 
2034 
2035 /*
2036  * Array to map a layering chain index to the appropriate initpkt routine.
2037  * The redundant entries are present so that the index used for accessing
2038  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2039  * with this table as well.
2040  */
2041 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
2042 
2043 static sd_initpkt_t	sd_initpkt_map[] = {
2044 
2045 	/* Chain for buf IO for disk drive targets (PM enabled) */
2046 	sd_initpkt_for_buf,		/* Index: 0 */
2047 	sd_initpkt_for_buf,		/* Index: 1 */
2048 	sd_initpkt_for_buf,		/* Index: 2 */
2049 
2050 	/* Chain for buf IO for disk drive targets (PM disabled) */
2051 	sd_initpkt_for_buf,		/* Index: 3 */
2052 	sd_initpkt_for_buf,		/* Index: 4 */
2053 
2054 	/*
2055 	 * Chain for buf IO for removable-media or large sector size
2056 	 * disk drive targets (PM enabled)
2057 	 */
2058 	sd_initpkt_for_buf,		/* Index: 5 */
2059 	sd_initpkt_for_buf,		/* Index: 6 */
2060 	sd_initpkt_for_buf,		/* Index: 7 */
2061 	sd_initpkt_for_buf,		/* Index: 8 */
2062 
2063 	/*
2064 	 * Chain for buf IO for removable-media or large sector size
2065 	 * disk drive targets (PM disabled)
2066 	 */
2067 	sd_initpkt_for_buf,		/* Index: 9 */
2068 	sd_initpkt_for_buf,		/* Index: 10 */
2069 	sd_initpkt_for_buf,		/* Index: 11 */
2070 
2071 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2072 	sd_initpkt_for_buf,		/* Index: 12 */
2073 	sd_initpkt_for_buf,		/* Index: 13 */
2074 	sd_initpkt_for_buf,		/* Index: 14 */
2075 	sd_initpkt_for_buf,		/* Index: 15 */
2076 
2077 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2078 	sd_initpkt_for_buf,		/* Index: 16 */
2079 	sd_initpkt_for_buf,		/* Index: 17 */
2080 	sd_initpkt_for_buf,		/* Index: 18 */
2081 
2082 	/* Chain for USCSI commands (non-checksum targets) */
2083 	sd_initpkt_for_uscsi,		/* Index: 19 */
2084 	sd_initpkt_for_uscsi,		/* Index: 20 */
2085 
2086 	/* Chain for USCSI commands (checksum targets) */
2087 	sd_initpkt_for_uscsi,		/* Index: 21 */
2088 	sd_initpkt_for_uscsi,		/* Index: 22 */
2089 	sd_initpkt_for_uscsi,		/* Index: 22 */
2090 
2091 	/* Chain for "direct" USCSI commands (all targets) */
2092 	sd_initpkt_for_uscsi,		/* Index: 24 */
2093 
2094 	/* Chain for "direct priority" USCSI commands (all targets) */
2095 	sd_initpkt_for_uscsi,		/* Index: 25 */
2096 
2097 	/*
2098 	 * Chain for buf IO for large sector size disk drive targets
2099 	 * with checksumming (PM enabled)
2100 	 */
2101 	sd_initpkt_for_buf,		/* Index: 26 */
2102 	sd_initpkt_for_buf,		/* Index: 27 */
2103 	sd_initpkt_for_buf,		/* Index: 28 */
2104 	sd_initpkt_for_buf,		/* Index: 29 */
2105 	sd_initpkt_for_buf,		/* Index: 30 */
2106 
2107 	/*
2108 	 * Chain for buf IO for large sector size disk drive targets
2109 	 * with checksumming (PM disabled)
2110 	 */
2111 	sd_initpkt_for_buf,		/* Index: 31 */
2112 	sd_initpkt_for_buf,		/* Index: 32 */
2113 	sd_initpkt_for_buf,		/* Index: 33 */
2114 	sd_initpkt_for_buf,		/* Index: 34 */
2115 };
2116 
2117 
2118 /*
2119  * Array to map a layering chain index to the appropriate destroypktpkt routine.
2120  * The redundant entries are present so that the index used for accessing
2121  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2122  * with this table as well.
2123  */
2124 typedef void (*sd_destroypkt_t)(struct buf *);
2125 
2126 static sd_destroypkt_t	sd_destroypkt_map[] = {
2127 
2128 	/* Chain for buf IO for disk drive targets (PM enabled) */
2129 	sd_destroypkt_for_buf,		/* Index: 0 */
2130 	sd_destroypkt_for_buf,		/* Index: 1 */
2131 	sd_destroypkt_for_buf,		/* Index: 2 */
2132 
2133 	/* Chain for buf IO for disk drive targets (PM disabled) */
2134 	sd_destroypkt_for_buf,		/* Index: 3 */
2135 	sd_destroypkt_for_buf,		/* Index: 4 */
2136 
2137 	/*
2138 	 * Chain for buf IO for removable-media or large sector size
2139 	 * disk drive targets (PM enabled)
2140 	 */
2141 	sd_destroypkt_for_buf,		/* Index: 5 */
2142 	sd_destroypkt_for_buf,		/* Index: 6 */
2143 	sd_destroypkt_for_buf,		/* Index: 7 */
2144 	sd_destroypkt_for_buf,		/* Index: 8 */
2145 
2146 	/*
2147 	 * Chain for buf IO for removable-media or large sector size
2148 	 * disk drive targets (PM disabled)
2149 	 */
2150 	sd_destroypkt_for_buf,		/* Index: 9 */
2151 	sd_destroypkt_for_buf,		/* Index: 10 */
2152 	sd_destroypkt_for_buf,		/* Index: 11 */
2153 
2154 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2155 	sd_destroypkt_for_buf,		/* Index: 12 */
2156 	sd_destroypkt_for_buf,		/* Index: 13 */
2157 	sd_destroypkt_for_buf,		/* Index: 14 */
2158 	sd_destroypkt_for_buf,		/* Index: 15 */
2159 
2160 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2161 	sd_destroypkt_for_buf,		/* Index: 16 */
2162 	sd_destroypkt_for_buf,		/* Index: 17 */
2163 	sd_destroypkt_for_buf,		/* Index: 18 */
2164 
2165 	/* Chain for USCSI commands (non-checksum targets) */
2166 	sd_destroypkt_for_uscsi,	/* Index: 19 */
2167 	sd_destroypkt_for_uscsi,	/* Index: 20 */
2168 
2169 	/* Chain for USCSI commands (checksum targets) */
2170 	sd_destroypkt_for_uscsi,	/* Index: 21 */
2171 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2172 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2173 
2174 	/* Chain for "direct" USCSI commands (all targets) */
2175 	sd_destroypkt_for_uscsi,	/* Index: 24 */
2176 
2177 	/* Chain for "direct priority" USCSI commands (all targets) */
2178 	sd_destroypkt_for_uscsi,	/* Index: 25 */
2179 
2180 	/*
2181 	 * Chain for buf IO for large sector size disk drive targets
2182 	 * with checksumming (PM disabled)
2183 	 */
2184 	sd_destroypkt_for_buf,		/* Index: 26 */
2185 	sd_destroypkt_for_buf,		/* Index: 27 */
2186 	sd_destroypkt_for_buf,		/* Index: 28 */
2187 	sd_destroypkt_for_buf,		/* Index: 29 */
2188 	sd_destroypkt_for_buf,		/* Index: 30 */
2189 
2190 	/*
2191 	 * Chain for buf IO for large sector size disk drive targets
2192 	 * with checksumming (PM enabled)
2193 	 */
2194 	sd_destroypkt_for_buf,		/* Index: 31 */
2195 	sd_destroypkt_for_buf,		/* Index: 32 */
2196 	sd_destroypkt_for_buf,		/* Index: 33 */
2197 	sd_destroypkt_for_buf,		/* Index: 34 */
2198 };
2199 
2200 
2201 
2202 /*
2203  * Array to map a layering chain index to the appropriate chain "type".
2204  * The chain type indicates a specific property/usage of the chain.
2205  * The redundant entries are present so that the index used for accessing
2206  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2207  * with this table as well.
2208  */
2209 
2210 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2211 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2212 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2213 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2214 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2215 						/* (for error recovery) */
2216 
2217 static int sd_chain_type_map[] = {
2218 
2219 	/* Chain for buf IO for disk drive targets (PM enabled) */
2220 	SD_CHAIN_BUFIO,			/* Index: 0 */
2221 	SD_CHAIN_BUFIO,			/* Index: 1 */
2222 	SD_CHAIN_BUFIO,			/* Index: 2 */
2223 
2224 	/* Chain for buf IO for disk drive targets (PM disabled) */
2225 	SD_CHAIN_BUFIO,			/* Index: 3 */
2226 	SD_CHAIN_BUFIO,			/* Index: 4 */
2227 
2228 	/*
2229 	 * Chain for buf IO for removable-media or large sector size
2230 	 * disk drive targets (PM enabled)
2231 	 */
2232 	SD_CHAIN_BUFIO,			/* Index: 5 */
2233 	SD_CHAIN_BUFIO,			/* Index: 6 */
2234 	SD_CHAIN_BUFIO,			/* Index: 7 */
2235 	SD_CHAIN_BUFIO,			/* Index: 8 */
2236 
2237 	/*
2238 	 * Chain for buf IO for removable-media or large sector size
2239 	 * disk drive targets (PM disabled)
2240 	 */
2241 	SD_CHAIN_BUFIO,			/* Index: 9 */
2242 	SD_CHAIN_BUFIO,			/* Index: 10 */
2243 	SD_CHAIN_BUFIO,			/* Index: 11 */
2244 
2245 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2246 	SD_CHAIN_BUFIO,			/* Index: 12 */
2247 	SD_CHAIN_BUFIO,			/* Index: 13 */
2248 	SD_CHAIN_BUFIO,			/* Index: 14 */
2249 	SD_CHAIN_BUFIO,			/* Index: 15 */
2250 
2251 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2252 	SD_CHAIN_BUFIO,			/* Index: 16 */
2253 	SD_CHAIN_BUFIO,			/* Index: 17 */
2254 	SD_CHAIN_BUFIO,			/* Index: 18 */
2255 
2256 	/* Chain for USCSI commands (non-checksum targets) */
2257 	SD_CHAIN_USCSI,			/* Index: 19 */
2258 	SD_CHAIN_USCSI,			/* Index: 20 */
2259 
2260 	/* Chain for USCSI commands (checksum targets) */
2261 	SD_CHAIN_USCSI,			/* Index: 21 */
2262 	SD_CHAIN_USCSI,			/* Index: 22 */
2263 	SD_CHAIN_USCSI,			/* Index: 23 */
2264 
2265 	/* Chain for "direct" USCSI commands (all targets) */
2266 	SD_CHAIN_DIRECT,		/* Index: 24 */
2267 
2268 	/* Chain for "direct priority" USCSI commands (all targets) */
2269 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2270 
2271 	/*
2272 	 * Chain for buf IO for large sector size disk drive targets
2273 	 * with checksumming (PM enabled)
2274 	 */
2275 	SD_CHAIN_BUFIO,			/* Index: 26 */
2276 	SD_CHAIN_BUFIO,			/* Index: 27 */
2277 	SD_CHAIN_BUFIO,			/* Index: 28 */
2278 	SD_CHAIN_BUFIO,			/* Index: 29 */
2279 	SD_CHAIN_BUFIO,			/* Index: 30 */
2280 
2281 	/*
2282 	 * Chain for buf IO for large sector size disk drive targets
2283 	 * with checksumming (PM disabled)
2284 	 */
2285 	SD_CHAIN_BUFIO,			/* Index: 31 */
2286 	SD_CHAIN_BUFIO,			/* Index: 32 */
2287 	SD_CHAIN_BUFIO,			/* Index: 33 */
2288 	SD_CHAIN_BUFIO,			/* Index: 34 */
2289 };
2290 
2291 
2292 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2293 #define	SD_IS_BUFIO(xp)			\
2294 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2295 
2296 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2297 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2298 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2299 
2300 
2301 
2302 /*
2303  * Struct, array, and macros to map a specific chain to the appropriate
2304  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2305  *
2306  * The sd_chain_index_map[] array is used at attach time to set the various
2307  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2308  * chain to be used with the instance. This allows different instances to use
2309  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2310  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2311  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2312  * dynamically & without the use of locking; and (2) a layer may update the
2313  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2314  * to allow for deferred processing of an IO within the same chain from a
2315  * different execution context.
2316  */
2317 
2318 struct sd_chain_index {
2319 	int	sci_iostart_index;
2320 	int	sci_iodone_index;
2321 };
2322 
2323 static struct sd_chain_index	sd_chain_index_map[] = {
2324 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2325 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2326 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2327 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2328 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2329 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2330 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2331 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2332 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2333 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2334 	{ SD_CHAIN_MSS_CHKSUM_IOSTART,		SD_CHAIN_MSS_CHKSUM_IODONE },
2335 	{ SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM, SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM },
2336 
2337 };
2338 
2339 
2340 /*
2341  * The following are indexes into the sd_chain_index_map[] array.
2342  */
2343 
2344 /* un->un_buf_chain_type must be set to one of these */
2345 #define	SD_CHAIN_INFO_DISK		0
2346 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2347 #define	SD_CHAIN_INFO_RMMEDIA		2
2348 #define	SD_CHAIN_INFO_MSS_DISK		2
2349 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2350 #define	SD_CHAIN_INFO_MSS_DSK_NO_PM	3
2351 #define	SD_CHAIN_INFO_CHKSUM		4
2352 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2353 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM	10
2354 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM_NO_PM	11
2355 
2356 /* un->un_uscsi_chain_type must be set to one of these */
2357 #define	SD_CHAIN_INFO_USCSI_CMD		6
2358 /* USCSI with PM disabled is the same as DIRECT */
2359 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2360 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2361 
2362 /* un->un_direct_chain_type must be set to one of these */
2363 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2364 
2365 /* un->un_priority_chain_type must be set to one of these */
2366 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2367 
2368 /* size for devid inquiries */
2369 #define	MAX_INQUIRY_SIZE		0xF0
2370 
2371 /*
2372  * Macros used by functions to pass a given buf(9S) struct along to the
2373  * next function in the layering chain for further processing.
2374  *
2375  * In the following macros, passing more than three arguments to the called
2376  * routines causes the optimizer for the SPARC compiler to stop doing tail
2377  * call elimination which results in significant performance degradation.
2378  */
2379 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2380 	((*(sd_iostart_chain[index]))(index, un, bp))
2381 
2382 #define	SD_BEGIN_IODONE(index, un, bp)	\
2383 	((*(sd_iodone_chain[index]))(index, un, bp))
2384 
2385 #define	SD_NEXT_IOSTART(index, un, bp)				\
2386 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2387 
2388 #define	SD_NEXT_IODONE(index, un, bp)				\
2389 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2390 
2391 /*
2392  *    Function: _init
2393  *
2394  * Description: This is the driver _init(9E) entry point.
2395  *
2396  * Return Code: Returns the value from mod_install(9F) or
2397  *		ddi_soft_state_init(9F) as appropriate.
2398  *
2399  *     Context: Called when driver module loaded.
2400  */
2401 
2402 int
2403 _init(void)
2404 {
2405 	int	err;
2406 
2407 	/* establish driver name from module name */
2408 	sd_label = (char *)mod_modname(&modlinkage);
2409 
2410 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2411 	    SD_MAXUNIT);
2412 	if (err != 0) {
2413 		return (err);
2414 	}
2415 
2416 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2417 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2418 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2419 
2420 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2421 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2422 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2423 
2424 	/*
2425 	 * it's ok to init here even for fibre device
2426 	 */
2427 	sd_scsi_probe_cache_init();
2428 
2429 	sd_scsi_target_lun_init();
2430 
2431 	/*
2432 	 * Creating taskq before mod_install ensures that all callers (threads)
2433 	 * that enter the module after a successful mod_install encounter
2434 	 * a valid taskq.
2435 	 */
2436 	sd_taskq_create();
2437 
2438 	err = mod_install(&modlinkage);
2439 	if (err != 0) {
2440 		/* delete taskq if install fails */
2441 		sd_taskq_delete();
2442 
2443 		mutex_destroy(&sd_detach_mutex);
2444 		mutex_destroy(&sd_log_mutex);
2445 		mutex_destroy(&sd_label_mutex);
2446 
2447 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2448 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2449 		cv_destroy(&sd_tr.srq_inprocess_cv);
2450 
2451 		sd_scsi_probe_cache_fini();
2452 
2453 		sd_scsi_target_lun_fini();
2454 
2455 		ddi_soft_state_fini(&sd_state);
2456 
2457 		return (err);
2458 	}
2459 
2460 	return (err);
2461 }
2462 
2463 
2464 /*
2465  *    Function: _fini
2466  *
2467  * Description: This is the driver _fini(9E) entry point.
2468  *
2469  * Return Code: Returns the value from mod_remove(9F)
2470  *
2471  *     Context: Called when driver module is unloaded.
2472  */
2473 
2474 int
2475 _fini(void)
2476 {
2477 	int err;
2478 
2479 	if ((err = mod_remove(&modlinkage)) != 0) {
2480 		return (err);
2481 	}
2482 
2483 	sd_taskq_delete();
2484 
2485 	mutex_destroy(&sd_detach_mutex);
2486 	mutex_destroy(&sd_log_mutex);
2487 	mutex_destroy(&sd_label_mutex);
2488 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2489 
2490 	sd_scsi_probe_cache_fini();
2491 
2492 	sd_scsi_target_lun_fini();
2493 
2494 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2495 	cv_destroy(&sd_tr.srq_inprocess_cv);
2496 
2497 	ddi_soft_state_fini(&sd_state);
2498 
2499 	return (err);
2500 }
2501 
2502 
2503 /*
2504  *    Function: _info
2505  *
2506  * Description: This is the driver _info(9E) entry point.
2507  *
2508  *   Arguments: modinfop - pointer to the driver modinfo structure
2509  *
2510  * Return Code: Returns the value from mod_info(9F).
2511  *
2512  *     Context: Kernel thread context
2513  */
2514 
2515 int
2516 _info(struct modinfo *modinfop)
2517 {
2518 	return (mod_info(&modlinkage, modinfop));
2519 }
2520 
2521 
2522 /*
2523  * The following routines implement the driver message logging facility.
2524  * They provide component- and level- based debug output filtering.
2525  * Output may also be restricted to messages for a single instance by
2526  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2527  * to NULL, then messages for all instances are printed.
2528  *
2529  * These routines have been cloned from each other due to the language
2530  * constraints of macros and variable argument list processing.
2531  */
2532 
2533 
2534 /*
2535  *    Function: sd_log_err
2536  *
2537  * Description: This routine is called by the SD_ERROR macro for debug
2538  *		logging of error conditions.
2539  *
2540  *   Arguments: comp - driver component being logged
2541  *		dev  - pointer to driver info structure
2542  *		fmt  - error string and format to be logged
2543  */
2544 
2545 static void
2546 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2547 {
2548 	va_list		ap;
2549 	dev_info_t	*dev;
2550 
2551 	ASSERT(un != NULL);
2552 	dev = SD_DEVINFO(un);
2553 	ASSERT(dev != NULL);
2554 
2555 	/*
2556 	 * Filter messages based on the global component and level masks.
2557 	 * Also print if un matches the value of sd_debug_un, or if
2558 	 * sd_debug_un is set to NULL.
2559 	 */
2560 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2561 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2562 		mutex_enter(&sd_log_mutex);
2563 		va_start(ap, fmt);
2564 		(void) vsprintf(sd_log_buf, fmt, ap);
2565 		va_end(ap);
2566 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2567 		mutex_exit(&sd_log_mutex);
2568 	}
2569 #ifdef SD_FAULT_INJECTION
2570 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2571 	if (un->sd_injection_mask & comp) {
2572 		mutex_enter(&sd_log_mutex);
2573 		va_start(ap, fmt);
2574 		(void) vsprintf(sd_log_buf, fmt, ap);
2575 		va_end(ap);
2576 		sd_injection_log(sd_log_buf, un);
2577 		mutex_exit(&sd_log_mutex);
2578 	}
2579 #endif
2580 }
2581 
2582 
2583 /*
2584  *    Function: sd_log_info
2585  *
2586  * Description: This routine is called by the SD_INFO macro for debug
2587  *		logging of general purpose informational conditions.
2588  *
2589  *   Arguments: comp - driver component being logged
2590  *		dev  - pointer to driver info structure
2591  *		fmt  - info string and format to be logged
2592  */
2593 
2594 static void
2595 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2596 {
2597 	va_list		ap;
2598 	dev_info_t	*dev;
2599 
2600 	ASSERT(un != NULL);
2601 	dev = SD_DEVINFO(un);
2602 	ASSERT(dev != NULL);
2603 
2604 	/*
2605 	 * Filter messages based on the global component and level masks.
2606 	 * Also print if un matches the value of sd_debug_un, or if
2607 	 * sd_debug_un is set to NULL.
2608 	 */
2609 	if ((sd_component_mask & component) &&
2610 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2611 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2612 		mutex_enter(&sd_log_mutex);
2613 		va_start(ap, fmt);
2614 		(void) vsprintf(sd_log_buf, fmt, ap);
2615 		va_end(ap);
2616 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2617 		mutex_exit(&sd_log_mutex);
2618 	}
2619 #ifdef SD_FAULT_INJECTION
2620 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2621 	if (un->sd_injection_mask & component) {
2622 		mutex_enter(&sd_log_mutex);
2623 		va_start(ap, fmt);
2624 		(void) vsprintf(sd_log_buf, fmt, ap);
2625 		va_end(ap);
2626 		sd_injection_log(sd_log_buf, un);
2627 		mutex_exit(&sd_log_mutex);
2628 	}
2629 #endif
2630 }
2631 
2632 
2633 /*
2634  *    Function: sd_log_trace
2635  *
2636  * Description: This routine is called by the SD_TRACE macro for debug
2637  *		logging of trace conditions (i.e. function entry/exit).
2638  *
2639  *   Arguments: comp - driver component being logged
2640  *		dev  - pointer to driver info structure
2641  *		fmt  - trace string and format to be logged
2642  */
2643 
2644 static void
2645 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2646 {
2647 	va_list		ap;
2648 	dev_info_t	*dev;
2649 
2650 	ASSERT(un != NULL);
2651 	dev = SD_DEVINFO(un);
2652 	ASSERT(dev != NULL);
2653 
2654 	/*
2655 	 * Filter messages based on the global component and level masks.
2656 	 * Also print if un matches the value of sd_debug_un, or if
2657 	 * sd_debug_un is set to NULL.
2658 	 */
2659 	if ((sd_component_mask & component) &&
2660 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2661 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2662 		mutex_enter(&sd_log_mutex);
2663 		va_start(ap, fmt);
2664 		(void) vsprintf(sd_log_buf, fmt, ap);
2665 		va_end(ap);
2666 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2667 		mutex_exit(&sd_log_mutex);
2668 	}
2669 #ifdef SD_FAULT_INJECTION
2670 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2671 	if (un->sd_injection_mask & component) {
2672 		mutex_enter(&sd_log_mutex);
2673 		va_start(ap, fmt);
2674 		(void) vsprintf(sd_log_buf, fmt, ap);
2675 		va_end(ap);
2676 		sd_injection_log(sd_log_buf, un);
2677 		mutex_exit(&sd_log_mutex);
2678 	}
2679 #endif
2680 }
2681 
2682 
2683 /*
2684  *    Function: sdprobe
2685  *
2686  * Description: This is the driver probe(9e) entry point function.
2687  *
2688  *   Arguments: devi - opaque device info handle
2689  *
2690  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2691  *              DDI_PROBE_FAILURE: If the probe failed.
2692  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2693  *				   but may be present in the future.
2694  */
2695 
2696 static int
2697 sdprobe(dev_info_t *devi)
2698 {
2699 	struct scsi_device	*devp;
2700 	int			rval;
2701 	int			instance = ddi_get_instance(devi);
2702 
2703 	/*
2704 	 * if it wasn't for pln, sdprobe could actually be nulldev
2705 	 * in the "__fibre" case.
2706 	 */
2707 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2708 		return (DDI_PROBE_DONTCARE);
2709 	}
2710 
2711 	devp = ddi_get_driver_private(devi);
2712 
2713 	if (devp == NULL) {
2714 		/* Ooops... nexus driver is mis-configured... */
2715 		return (DDI_PROBE_FAILURE);
2716 	}
2717 
2718 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2719 		return (DDI_PROBE_PARTIAL);
2720 	}
2721 
2722 	/*
2723 	 * Call the SCSA utility probe routine to see if we actually
2724 	 * have a target at this SCSI nexus.
2725 	 */
2726 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2727 	case SCSIPROBE_EXISTS:
2728 		switch (devp->sd_inq->inq_dtype) {
2729 		case DTYPE_DIRECT:
2730 			rval = DDI_PROBE_SUCCESS;
2731 			break;
2732 		case DTYPE_RODIRECT:
2733 			/* CDs etc. Can be removable media */
2734 			rval = DDI_PROBE_SUCCESS;
2735 			break;
2736 		case DTYPE_OPTICAL:
2737 			/*
2738 			 * Rewritable optical driver HP115AA
2739 			 * Can also be removable media
2740 			 */
2741 
2742 			/*
2743 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2744 			 * pre solaris 9 sparc sd behavior is required
2745 			 *
2746 			 * If first time through and sd_dtype_optical_bind
2747 			 * has not been set in /etc/system check properties
2748 			 */
2749 
2750 			if (sd_dtype_optical_bind  < 0) {
2751 				sd_dtype_optical_bind = ddi_prop_get_int
2752 				    (DDI_DEV_T_ANY, devi, 0,
2753 				    "optical-device-bind", 1);
2754 			}
2755 
2756 			if (sd_dtype_optical_bind == 0) {
2757 				rval = DDI_PROBE_FAILURE;
2758 			} else {
2759 				rval = DDI_PROBE_SUCCESS;
2760 			}
2761 			break;
2762 
2763 		case DTYPE_NOTPRESENT:
2764 		default:
2765 			rval = DDI_PROBE_FAILURE;
2766 			break;
2767 		}
2768 		break;
2769 	default:
2770 		rval = DDI_PROBE_PARTIAL;
2771 		break;
2772 	}
2773 
2774 	/*
2775 	 * This routine checks for resource allocation prior to freeing,
2776 	 * so it will take care of the "smart probing" case where a
2777 	 * scsi_probe() may or may not have been issued and will *not*
2778 	 * free previously-freed resources.
2779 	 */
2780 	scsi_unprobe(devp);
2781 	return (rval);
2782 }
2783 
2784 
2785 /*
2786  *    Function: sdinfo
2787  *
2788  * Description: This is the driver getinfo(9e) entry point function.
2789  *		Given the device number, return the devinfo pointer from
2790  *		the scsi_device structure or the instance number
2791  *		associated with the dev_t.
2792  *
2793  *   Arguments: dip     - pointer to device info structure
2794  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2795  *			  DDI_INFO_DEVT2INSTANCE)
2796  *		arg     - driver dev_t
2797  *		resultp - user buffer for request response
2798  *
2799  * Return Code: DDI_SUCCESS
2800  *              DDI_FAILURE
2801  */
2802 /* ARGSUSED */
2803 static int
2804 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2805 {
2806 	struct sd_lun	*un;
2807 	dev_t		dev;
2808 	int		instance;
2809 	int		error;
2810 
2811 	switch (infocmd) {
2812 	case DDI_INFO_DEVT2DEVINFO:
2813 		dev = (dev_t)arg;
2814 		instance = SDUNIT(dev);
2815 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2816 			return (DDI_FAILURE);
2817 		}
2818 		*result = (void *) SD_DEVINFO(un);
2819 		error = DDI_SUCCESS;
2820 		break;
2821 	case DDI_INFO_DEVT2INSTANCE:
2822 		dev = (dev_t)arg;
2823 		instance = SDUNIT(dev);
2824 		*result = (void *)(uintptr_t)instance;
2825 		error = DDI_SUCCESS;
2826 		break;
2827 	default:
2828 		error = DDI_FAILURE;
2829 	}
2830 	return (error);
2831 }
2832 
2833 /*
2834  *    Function: sd_prop_op
2835  *
2836  * Description: This is the driver prop_op(9e) entry point function.
2837  *		Return the number of blocks for the partition in question
2838  *		or forward the request to the property facilities.
2839  *
2840  *   Arguments: dev       - device number
2841  *		dip       - pointer to device info structure
2842  *		prop_op   - property operator
2843  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2844  *		name      - pointer to property name
2845  *		valuep    - pointer or address of the user buffer
2846  *		lengthp   - property length
2847  *
2848  * Return Code: DDI_PROP_SUCCESS
2849  *              DDI_PROP_NOT_FOUND
2850  *              DDI_PROP_UNDEFINED
2851  *              DDI_PROP_NO_MEMORY
2852  *              DDI_PROP_BUF_TOO_SMALL
2853  */
2854 
2855 static int
2856 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2857     char *name, caddr_t valuep, int *lengthp)
2858 {
2859 	struct sd_lun	*un;
2860 
2861 	if ((un = ddi_get_soft_state(sd_state, ddi_get_instance(dip))) == NULL)
2862 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2863 		    name, valuep, lengthp));
2864 
2865 	return (cmlb_prop_op(un->un_cmlbhandle,
2866 	    dev, dip, prop_op, mod_flags, name, valuep, lengthp,
2867 	    SDPART(dev), (void *)SD_PATH_DIRECT));
2868 }
2869 
2870 /*
2871  * The following functions are for smart probing:
2872  * sd_scsi_probe_cache_init()
2873  * sd_scsi_probe_cache_fini()
2874  * sd_scsi_clear_probe_cache()
2875  * sd_scsi_probe_with_cache()
2876  */
2877 
2878 /*
2879  *    Function: sd_scsi_probe_cache_init
2880  *
2881  * Description: Initializes the probe response cache mutex and head pointer.
2882  *
2883  *     Context: Kernel thread context
2884  */
2885 
2886 static void
2887 sd_scsi_probe_cache_init(void)
2888 {
2889 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2890 	sd_scsi_probe_cache_head = NULL;
2891 }
2892 
2893 
2894 /*
2895  *    Function: sd_scsi_probe_cache_fini
2896  *
2897  * Description: Frees all resources associated with the probe response cache.
2898  *
2899  *     Context: Kernel thread context
2900  */
2901 
2902 static void
2903 sd_scsi_probe_cache_fini(void)
2904 {
2905 	struct sd_scsi_probe_cache *cp;
2906 	struct sd_scsi_probe_cache *ncp;
2907 
2908 	/* Clean up our smart probing linked list */
2909 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2910 		ncp = cp->next;
2911 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2912 	}
2913 	sd_scsi_probe_cache_head = NULL;
2914 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2915 }
2916 
2917 
2918 /*
2919  *    Function: sd_scsi_clear_probe_cache
2920  *
2921  * Description: This routine clears the probe response cache. This is
2922  *		done when open() returns ENXIO so that when deferred
2923  *		attach is attempted (possibly after a device has been
2924  *		turned on) we will retry the probe. Since we don't know
2925  *		which target we failed to open, we just clear the
2926  *		entire cache.
2927  *
2928  *     Context: Kernel thread context
2929  */
2930 
2931 static void
2932 sd_scsi_clear_probe_cache(void)
2933 {
2934 	struct sd_scsi_probe_cache	*cp;
2935 	int				i;
2936 
2937 	mutex_enter(&sd_scsi_probe_cache_mutex);
2938 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2939 		/*
2940 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2941 		 * force probing to be performed the next time
2942 		 * sd_scsi_probe_with_cache is called.
2943 		 */
2944 		for (i = 0; i < NTARGETS_WIDE; i++) {
2945 			cp->cache[i] = SCSIPROBE_EXISTS;
2946 		}
2947 	}
2948 	mutex_exit(&sd_scsi_probe_cache_mutex);
2949 }
2950 
2951 
2952 /*
2953  *    Function: sd_scsi_probe_with_cache
2954  *
2955  * Description: This routine implements support for a scsi device probe
2956  *		with cache. The driver maintains a cache of the target
2957  *		responses to scsi probes. If we get no response from a
2958  *		target during a probe inquiry, we remember that, and we
2959  *		avoid additional calls to scsi_probe on non-zero LUNs
2960  *		on the same target until the cache is cleared. By doing
2961  *		so we avoid the 1/4 sec selection timeout for nonzero
2962  *		LUNs. lun0 of a target is always probed.
2963  *
2964  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2965  *              waitfunc - indicates what the allocator routines should
2966  *			   do when resources are not available. This value
2967  *			   is passed on to scsi_probe() when that routine
2968  *			   is called.
2969  *
2970  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2971  *		otherwise the value returned by scsi_probe(9F).
2972  *
2973  *     Context: Kernel thread context
2974  */
2975 
2976 static int
2977 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2978 {
2979 	struct sd_scsi_probe_cache	*cp;
2980 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2981 	int		lun, tgt;
2982 
2983 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2984 	    SCSI_ADDR_PROP_LUN, 0);
2985 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2986 	    SCSI_ADDR_PROP_TARGET, -1);
2987 
2988 	/* Make sure caching enabled and target in range */
2989 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2990 		/* do it the old way (no cache) */
2991 		return (scsi_probe(devp, waitfn));
2992 	}
2993 
2994 	mutex_enter(&sd_scsi_probe_cache_mutex);
2995 
2996 	/* Find the cache for this scsi bus instance */
2997 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2998 		if (cp->pdip == pdip) {
2999 			break;
3000 		}
3001 	}
3002 
3003 	/* If we can't find a cache for this pdip, create one */
3004 	if (cp == NULL) {
3005 		int i;
3006 
3007 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
3008 		    KM_SLEEP);
3009 		cp->pdip = pdip;
3010 		cp->next = sd_scsi_probe_cache_head;
3011 		sd_scsi_probe_cache_head = cp;
3012 		for (i = 0; i < NTARGETS_WIDE; i++) {
3013 			cp->cache[i] = SCSIPROBE_EXISTS;
3014 		}
3015 	}
3016 
3017 	mutex_exit(&sd_scsi_probe_cache_mutex);
3018 
3019 	/* Recompute the cache for this target if LUN zero */
3020 	if (lun == 0) {
3021 		cp->cache[tgt] = SCSIPROBE_EXISTS;
3022 	}
3023 
3024 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
3025 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
3026 		return (SCSIPROBE_NORESP);
3027 	}
3028 
3029 	/* Do the actual probe; save & return the result */
3030 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
3031 }
3032 
3033 
3034 /*
3035  *    Function: sd_scsi_target_lun_init
3036  *
3037  * Description: Initializes the attached lun chain mutex and head pointer.
3038  *
3039  *     Context: Kernel thread context
3040  */
3041 
3042 static void
3043 sd_scsi_target_lun_init(void)
3044 {
3045 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
3046 	sd_scsi_target_lun_head = NULL;
3047 }
3048 
3049 
3050 /*
3051  *    Function: sd_scsi_target_lun_fini
3052  *
3053  * Description: Frees all resources associated with the attached lun
3054  *              chain
3055  *
3056  *     Context: Kernel thread context
3057  */
3058 
3059 static void
3060 sd_scsi_target_lun_fini(void)
3061 {
3062 	struct sd_scsi_hba_tgt_lun	*cp;
3063 	struct sd_scsi_hba_tgt_lun	*ncp;
3064 
3065 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
3066 		ncp = cp->next;
3067 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
3068 	}
3069 	sd_scsi_target_lun_head = NULL;
3070 	mutex_destroy(&sd_scsi_target_lun_mutex);
3071 }
3072 
3073 
3074 /*
3075  *    Function: sd_scsi_get_target_lun_count
3076  *
3077  * Description: This routine will check in the attached lun chain to see
3078  *		how many luns are attached on the required SCSI controller
3079  *		and target. Currently, some capabilities like tagged queue
3080  *		are supported per target based by HBA. So all luns in a
3081  *		target have the same capabilities. Based on this assumption,
3082  *		sd should only set these capabilities once per target. This
3083  *		function is called when sd needs to decide how many luns
3084  *		already attached on a target.
3085  *
3086  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
3087  *			  controller device.
3088  *              target	- The target ID on the controller's SCSI bus.
3089  *
3090  * Return Code: The number of luns attached on the required target and
3091  *		controller.
3092  *		-1 if target ID is not in parallel SCSI scope or the given
3093  *		dip is not in the chain.
3094  *
3095  *     Context: Kernel thread context
3096  */
3097 
3098 static int
3099 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
3100 {
3101 	struct sd_scsi_hba_tgt_lun	*cp;
3102 
3103 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
3104 		return (-1);
3105 	}
3106 
3107 	mutex_enter(&sd_scsi_target_lun_mutex);
3108 
3109 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3110 		if (cp->pdip == dip) {
3111 			break;
3112 		}
3113 	}
3114 
3115 	mutex_exit(&sd_scsi_target_lun_mutex);
3116 
3117 	if (cp == NULL) {
3118 		return (-1);
3119 	}
3120 
3121 	return (cp->nlun[target]);
3122 }
3123 
3124 
3125 /*
3126  *    Function: sd_scsi_update_lun_on_target
3127  *
3128  * Description: This routine is used to update the attached lun chain when a
3129  *		lun is attached or detached on a target.
3130  *
3131  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
3132  *                        controller device.
3133  *              target  - The target ID on the controller's SCSI bus.
3134  *		flag	- Indicate the lun is attached or detached.
3135  *
3136  *     Context: Kernel thread context
3137  */
3138 
3139 static void
3140 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
3141 {
3142 	struct sd_scsi_hba_tgt_lun	*cp;
3143 
3144 	mutex_enter(&sd_scsi_target_lun_mutex);
3145 
3146 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3147 		if (cp->pdip == dip) {
3148 			break;
3149 		}
3150 	}
3151 
3152 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
3153 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
3154 		    KM_SLEEP);
3155 		cp->pdip = dip;
3156 		cp->next = sd_scsi_target_lun_head;
3157 		sd_scsi_target_lun_head = cp;
3158 	}
3159 
3160 	mutex_exit(&sd_scsi_target_lun_mutex);
3161 
3162 	if (cp != NULL) {
3163 		if (flag == SD_SCSI_LUN_ATTACH) {
3164 			cp->nlun[target] ++;
3165 		} else {
3166 			cp->nlun[target] --;
3167 		}
3168 	}
3169 }
3170 
3171 
3172 /*
3173  *    Function: sd_spin_up_unit
3174  *
3175  * Description: Issues the following commands to spin-up the device:
3176  *		START STOP UNIT, and INQUIRY.
3177  *
3178  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3179  *                      structure for this target.
3180  *
3181  * Return Code: 0 - success
3182  *		EIO - failure
3183  *		EACCES - reservation conflict
3184  *
3185  *     Context: Kernel thread context
3186  */
3187 
3188 static int
3189 sd_spin_up_unit(sd_ssc_t *ssc)
3190 {
3191 	size_t	resid		= 0;
3192 	int	has_conflict	= FALSE;
3193 	uchar_t *bufaddr;
3194 	int	status;
3195 	struct sd_lun	*un;
3196 
3197 	ASSERT(ssc != NULL);
3198 	un = ssc->ssc_un;
3199 	ASSERT(un != NULL);
3200 
3201 	/*
3202 	 * Send a throwaway START UNIT command.
3203 	 *
3204 	 * If we fail on this, we don't care presently what precisely
3205 	 * is wrong.  EMC's arrays will also fail this with a check
3206 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
3207 	 * we don't want to fail the attach because it may become
3208 	 * "active" later.
3209 	 * We don't know if power condition is supported or not at
3210 	 * this stage, use START STOP bit.
3211 	 */
3212 	status = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
3213 	    SD_TARGET_START, SD_PATH_DIRECT);
3214 
3215 	if (status != 0) {
3216 		if (status == EACCES)
3217 			has_conflict = TRUE;
3218 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3219 	}
3220 
3221 	/*
3222 	 * Send another INQUIRY command to the target. This is necessary for
3223 	 * non-removable media direct access devices because their INQUIRY data
3224 	 * may not be fully qualified until they are spun up (perhaps via the
3225 	 * START command above).  Note: This seems to be needed for some
3226 	 * legacy devices only.) The INQUIRY command should succeed even if a
3227 	 * Reservation Conflict is present.
3228 	 */
3229 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
3230 
3231 	if (sd_send_scsi_INQUIRY(ssc, bufaddr, SUN_INQSIZE, 0, 0, &resid)
3232 	    != 0) {
3233 		kmem_free(bufaddr, SUN_INQSIZE);
3234 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
3235 		return (EIO);
3236 	}
3237 
3238 	/*
3239 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
3240 	 * Note that this routine does not return a failure here even if the
3241 	 * INQUIRY command did not return any data.  This is a legacy behavior.
3242 	 */
3243 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
3244 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
3245 	}
3246 
3247 	kmem_free(bufaddr, SUN_INQSIZE);
3248 
3249 	/* If we hit a reservation conflict above, tell the caller. */
3250 	if (has_conflict == TRUE) {
3251 		return (EACCES);
3252 	}
3253 
3254 	return (0);
3255 }
3256 
3257 #ifdef _LP64
3258 /*
3259  *    Function: sd_enable_descr_sense
3260  *
3261  * Description: This routine attempts to select descriptor sense format
3262  *		using the Control mode page.  Devices that support 64 bit
3263  *		LBAs (for >2TB luns) should also implement descriptor
3264  *		sense data so we will call this function whenever we see
3265  *		a lun larger than 2TB.  If for some reason the device
3266  *		supports 64 bit LBAs but doesn't support descriptor sense
3267  *		presumably the mode select will fail.  Everything will
3268  *		continue to work normally except that we will not get
3269  *		complete sense data for commands that fail with an LBA
3270  *		larger than 32 bits.
3271  *
3272  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3273  *                      structure for this target.
3274  *
3275  *     Context: Kernel thread context only
3276  */
3277 
3278 static void
3279 sd_enable_descr_sense(sd_ssc_t *ssc)
3280 {
3281 	uchar_t			*header;
3282 	struct mode_control_scsi3 *ctrl_bufp;
3283 	size_t			buflen;
3284 	size_t			bd_len;
3285 	int			status;
3286 	struct sd_lun		*un;
3287 
3288 	ASSERT(ssc != NULL);
3289 	un = ssc->ssc_un;
3290 	ASSERT(un != NULL);
3291 
3292 	/*
3293 	 * Read MODE SENSE page 0xA, Control Mode Page
3294 	 */
3295 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3296 	    sizeof (struct mode_control_scsi3);
3297 	header = kmem_zalloc(buflen, KM_SLEEP);
3298 
3299 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
3300 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT);
3301 
3302 	if (status != 0) {
3303 		SD_ERROR(SD_LOG_COMMON, un,
3304 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3305 		goto eds_exit;
3306 	}
3307 
3308 	/*
3309 	 * Determine size of Block Descriptors in order to locate
3310 	 * the mode page data. ATAPI devices return 0, SCSI devices
3311 	 * should return MODE_BLK_DESC_LENGTH.
3312 	 */
3313 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3314 
3315 	/* Clear the mode data length field for MODE SELECT */
3316 	((struct mode_header *)header)->length = 0;
3317 
3318 	ctrl_bufp = (struct mode_control_scsi3 *)
3319 	    (header + MODE_HEADER_LENGTH + bd_len);
3320 
3321 	/*
3322 	 * If the page length is smaller than the expected value,
3323 	 * the target device doesn't support D_SENSE. Bail out here.
3324 	 */
3325 	if (ctrl_bufp->mode_page.length <
3326 	    sizeof (struct mode_control_scsi3) - 2) {
3327 		SD_ERROR(SD_LOG_COMMON, un,
3328 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3329 		goto eds_exit;
3330 	}
3331 
3332 	/*
3333 	 * Clear PS bit for MODE SELECT
3334 	 */
3335 	ctrl_bufp->mode_page.ps = 0;
3336 
3337 	/*
3338 	 * Set D_SENSE to enable descriptor sense format.
3339 	 */
3340 	ctrl_bufp->d_sense = 1;
3341 
3342 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3343 
3344 	/*
3345 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3346 	 */
3347 	status = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
3348 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT);
3349 
3350 	if (status != 0) {
3351 		SD_INFO(SD_LOG_COMMON, un,
3352 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3353 	} else {
3354 		kmem_free(header, buflen);
3355 		return;
3356 	}
3357 
3358 eds_exit:
3359 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3360 	kmem_free(header, buflen);
3361 }
3362 
3363 /*
3364  *    Function: sd_reenable_dsense_task
3365  *
3366  * Description: Re-enable descriptor sense after device or bus reset
3367  *
3368  *     Context: Executes in a taskq() thread context
3369  */
3370 static void
3371 sd_reenable_dsense_task(void *arg)
3372 {
3373 	struct	sd_lun	*un = arg;
3374 	sd_ssc_t	*ssc;
3375 
3376 	ASSERT(un != NULL);
3377 
3378 	ssc = sd_ssc_init(un);
3379 	sd_enable_descr_sense(ssc);
3380 	sd_ssc_fini(ssc);
3381 }
3382 #endif /* _LP64 */
3383 
3384 /*
3385  *    Function: sd_set_mmc_caps
3386  *
3387  * Description: This routine determines if the device is MMC compliant and if
3388  *		the device supports CDDA via a mode sense of the CDVD
3389  *		capabilities mode page. Also checks if the device is a
3390  *		dvdram writable device.
3391  *
3392  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3393  *                      structure for this target.
3394  *
3395  *     Context: Kernel thread context only
3396  */
3397 
3398 static void
3399 sd_set_mmc_caps(sd_ssc_t *ssc)
3400 {
3401 	struct mode_header_grp2		*sense_mhp;
3402 	uchar_t				*sense_page;
3403 	caddr_t				buf;
3404 	int				bd_len;
3405 	int				status;
3406 	struct uscsi_cmd		com;
3407 	int				rtn;
3408 	uchar_t				*out_data_rw, *out_data_hd;
3409 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3410 	uchar_t				*out_data_gesn;
3411 	int				gesn_len;
3412 	struct sd_lun			*un;
3413 
3414 	ASSERT(ssc != NULL);
3415 	un = ssc->ssc_un;
3416 	ASSERT(un != NULL);
3417 
3418 	/*
3419 	 * The flags which will be set in this function are - mmc compliant,
3420 	 * dvdram writable device, cdda support. Initialize them to FALSE
3421 	 * and if a capability is detected - it will be set to TRUE.
3422 	 */
3423 	un->un_f_mmc_cap = FALSE;
3424 	un->un_f_dvdram_writable_device = FALSE;
3425 	un->un_f_cfg_cdda = FALSE;
3426 
3427 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3428 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3429 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3430 
3431 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3432 
3433 	if (status != 0) {
3434 		/* command failed; just return */
3435 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3436 		return;
3437 	}
3438 	/*
3439 	 * If the mode sense request for the CDROM CAPABILITIES
3440 	 * page (0x2A) succeeds the device is assumed to be MMC.
3441 	 */
3442 	un->un_f_mmc_cap = TRUE;
3443 
3444 	/* See if GET STATUS EVENT NOTIFICATION is supported */
3445 	if (un->un_f_mmc_gesn_polling) {
3446 		gesn_len = SD_GESN_HEADER_LEN + SD_GESN_MEDIA_DATA_LEN;
3447 		out_data_gesn = kmem_zalloc(gesn_len, KM_SLEEP);
3448 
3449 		rtn = sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(ssc,
3450 		    out_data_gesn, gesn_len, 1 << SD_GESN_MEDIA_CLASS);
3451 
3452 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3453 
3454 		if ((rtn != 0) || !sd_gesn_media_data_valid(out_data_gesn)) {
3455 			un->un_f_mmc_gesn_polling = FALSE;
3456 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3457 			    "sd_set_mmc_caps: gesn not supported "
3458 			    "%d %x %x %x %x\n", rtn,
3459 			    out_data_gesn[0], out_data_gesn[1],
3460 			    out_data_gesn[2], out_data_gesn[3]);
3461 		}
3462 
3463 		kmem_free(out_data_gesn, gesn_len);
3464 	}
3465 
3466 	/* Get to the page data */
3467 	sense_mhp = (struct mode_header_grp2 *)buf;
3468 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3469 	    sense_mhp->bdesc_length_lo;
3470 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3471 		/*
3472 		 * We did not get back the expected block descriptor
3473 		 * length so we cannot determine if the device supports
3474 		 * CDDA. However, we still indicate the device is MMC
3475 		 * according to the successful response to the page
3476 		 * 0x2A mode sense request.
3477 		 */
3478 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3479 		    "sd_set_mmc_caps: Mode Sense returned "
3480 		    "invalid block descriptor length\n");
3481 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3482 		return;
3483 	}
3484 
3485 	/* See if read CDDA is supported */
3486 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3487 	    bd_len);
3488 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3489 
3490 	/* See if writing DVD RAM is supported. */
3491 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3492 	if (un->un_f_dvdram_writable_device == TRUE) {
3493 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3494 		return;
3495 	}
3496 
3497 	/*
3498 	 * If the device presents DVD or CD capabilities in the mode
3499 	 * page, we can return here since a RRD will not have
3500 	 * these capabilities.
3501 	 */
3502 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3503 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3504 		return;
3505 	}
3506 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3507 
3508 	/*
3509 	 * If un->un_f_dvdram_writable_device is still FALSE,
3510 	 * check for a Removable Rigid Disk (RRD).  A RRD
3511 	 * device is identified by the features RANDOM_WRITABLE and
3512 	 * HARDWARE_DEFECT_MANAGEMENT.
3513 	 */
3514 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3515 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3516 
3517 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3518 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3519 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3520 
3521 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3522 
3523 	if (rtn != 0) {
3524 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3525 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3526 		return;
3527 	}
3528 
3529 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3530 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3531 
3532 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3533 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3534 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3535 
3536 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3537 
3538 	if (rtn == 0) {
3539 		/*
3540 		 * We have good information, check for random writable
3541 		 * and hardware defect features.
3542 		 */
3543 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3544 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3545 			un->un_f_dvdram_writable_device = TRUE;
3546 		}
3547 	}
3548 
3549 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3550 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3551 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3552 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3553 }
3554 
3555 /*
3556  *    Function: sd_check_for_writable_cd
3557  *
3558  * Description: This routine determines if the media in the device is
3559  *		writable or not. It uses the get configuration command (0x46)
3560  *		to determine if the media is writable
3561  *
3562  *   Arguments: un - driver soft state (unit) structure
3563  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3564  *                           chain and the normal command waitq, or
3565  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3566  *                           "direct" chain and bypass the normal command
3567  *                           waitq.
3568  *
3569  *     Context: Never called at interrupt context.
3570  */
3571 
3572 static void
3573 sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag)
3574 {
3575 	struct uscsi_cmd		com;
3576 	uchar_t				*out_data;
3577 	uchar_t				*rqbuf;
3578 	int				rtn;
3579 	uchar_t				*out_data_rw, *out_data_hd;
3580 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3581 	struct mode_header_grp2		*sense_mhp;
3582 	uchar_t				*sense_page;
3583 	caddr_t				buf;
3584 	int				bd_len;
3585 	int				status;
3586 	struct sd_lun			*un;
3587 
3588 	ASSERT(ssc != NULL);
3589 	un = ssc->ssc_un;
3590 	ASSERT(un != NULL);
3591 	ASSERT(mutex_owned(SD_MUTEX(un)));
3592 
3593 	/*
3594 	 * Initialize the writable media to false, if configuration info.
3595 	 * tells us otherwise then only we will set it.
3596 	 */
3597 	un->un_f_mmc_writable_media = FALSE;
3598 	mutex_exit(SD_MUTEX(un));
3599 
3600 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3601 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3602 
3603 	rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf, SENSE_LENGTH,
3604 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3605 
3606 	if (rtn != 0)
3607 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3608 
3609 	mutex_enter(SD_MUTEX(un));
3610 	if (rtn == 0) {
3611 		/*
3612 		 * We have good information, check for writable DVD.
3613 		 */
3614 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3615 			un->un_f_mmc_writable_media = TRUE;
3616 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3617 			kmem_free(rqbuf, SENSE_LENGTH);
3618 			return;
3619 		}
3620 	}
3621 
3622 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3623 	kmem_free(rqbuf, SENSE_LENGTH);
3624 
3625 	/*
3626 	 * Determine if this is a RRD type device.
3627 	 */
3628 	mutex_exit(SD_MUTEX(un));
3629 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3630 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3631 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3632 
3633 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3634 
3635 	mutex_enter(SD_MUTEX(un));
3636 	if (status != 0) {
3637 		/* command failed; just return */
3638 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3639 		return;
3640 	}
3641 
3642 	/* Get to the page data */
3643 	sense_mhp = (struct mode_header_grp2 *)buf;
3644 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3645 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3646 		/*
3647 		 * We did not get back the expected block descriptor length so
3648 		 * we cannot check the mode page.
3649 		 */
3650 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3651 		    "sd_check_for_writable_cd: Mode Sense returned "
3652 		    "invalid block descriptor length\n");
3653 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3654 		return;
3655 	}
3656 
3657 	/*
3658 	 * If the device presents DVD or CD capabilities in the mode
3659 	 * page, we can return here since a RRD device will not have
3660 	 * these capabilities.
3661 	 */
3662 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3663 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3664 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3665 		return;
3666 	}
3667 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3668 
3669 	/*
3670 	 * If un->un_f_mmc_writable_media is still FALSE,
3671 	 * check for RRD type media.  A RRD device is identified
3672 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3673 	 */
3674 	mutex_exit(SD_MUTEX(un));
3675 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3676 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3677 
3678 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3679 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3680 	    RANDOM_WRITABLE, path_flag);
3681 
3682 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3683 	if (rtn != 0) {
3684 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3685 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3686 		mutex_enter(SD_MUTEX(un));
3687 		return;
3688 	}
3689 
3690 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3691 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3692 
3693 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3694 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3695 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3696 
3697 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3698 	mutex_enter(SD_MUTEX(un));
3699 	if (rtn == 0) {
3700 		/*
3701 		 * We have good information, check for random writable
3702 		 * and hardware defect features as current.
3703 		 */
3704 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3705 		    (out_data_rw[10] & 0x1) &&
3706 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3707 		    (out_data_hd[10] & 0x1)) {
3708 			un->un_f_mmc_writable_media = TRUE;
3709 		}
3710 	}
3711 
3712 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3713 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3714 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3715 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3716 }
3717 
3718 /*
3719  *    Function: sd_read_unit_properties
3720  *
3721  * Description: The following implements a property lookup mechanism.
3722  *		Properties for particular disks (keyed on vendor, model
3723  *		and rev numbers) are sought in the sd.conf file via
3724  *		sd_process_sdconf_file(), and if not found there, are
3725  *		looked for in a list hardcoded in this driver via
3726  *		sd_process_sdconf_table() Once located the properties
3727  *		are used to update the driver unit structure.
3728  *
3729  *   Arguments: un - driver soft state (unit) structure
3730  */
3731 
3732 static void
3733 sd_read_unit_properties(struct sd_lun *un)
3734 {
3735 	/*
3736 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3737 	 * the "sd-config-list" property (from the sd.conf file) or if
3738 	 * there was not a match for the inquiry vid/pid. If this event
3739 	 * occurs the static driver configuration table is searched for
3740 	 * a match.
3741 	 */
3742 	ASSERT(un != NULL);
3743 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3744 		sd_process_sdconf_table(un);
3745 	}
3746 
3747 	/* check for LSI device */
3748 	sd_is_lsi(un);
3749 
3750 
3751 }
3752 
3753 
3754 /*
3755  *    Function: sd_process_sdconf_file
3756  *
3757  * Description: Use ddi_prop_lookup(9F) to obtain the properties from the
3758  *		driver's config file (ie, sd.conf) and update the driver
3759  *		soft state structure accordingly.
3760  *
3761  *   Arguments: un - driver soft state (unit) structure
3762  *
3763  * Return Code: SD_SUCCESS - The properties were successfully set according
3764  *			     to the driver configuration file.
3765  *		SD_FAILURE - The driver config list was not obtained or
3766  *			     there was no vid/pid match. This indicates that
3767  *			     the static config table should be used.
3768  *
3769  * The config file has a property, "sd-config-list". Currently we support
3770  * two kinds of formats. For both formats, the value of this property
3771  * is a list of duplets:
3772  *
3773  *  sd-config-list=
3774  *	<duplet>,
3775  *	[,<duplet>]*;
3776  *
3777  * For the improved format, where
3778  *
3779  *     <duplet>:= "<vid+pid>","<tunable-list>"
3780  *
3781  * and
3782  *
3783  *     <tunable-list>:=   <tunable> [, <tunable> ]*;
3784  *     <tunable> =        <name> : <value>
3785  *
3786  * The <vid+pid> is the string that is returned by the target device on a
3787  * SCSI inquiry command, the <tunable-list> contains one or more tunables
3788  * to apply to all target devices with the specified <vid+pid>.
3789  *
3790  * Each <tunable> is a "<name> : <value>" pair.
3791  *
3792  * For the old format, the structure of each duplet is as follows:
3793  *
3794  *  <duplet>:= "<vid+pid>","<data-property-name_list>"
3795  *
3796  * The first entry of the duplet is the device ID string (the concatenated
3797  * vid & pid; not to be confused with a device_id).  This is defined in
3798  * the same way as in the sd_disk_table.
3799  *
3800  * The second part of the duplet is a string that identifies a
3801  * data-property-name-list. The data-property-name-list is defined as
3802  * follows:
3803  *
3804  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3805  *
3806  * The syntax of <data-property-name> depends on the <version> field.
3807  *
3808  * If version = SD_CONF_VERSION_1 we have the following syntax:
3809  *
3810  *	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3811  *
3812  * where the prop0 value will be used to set prop0 if bit0 set in the
3813  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3814  *
3815  */
3816 
3817 static int
3818 sd_process_sdconf_file(struct sd_lun *un)
3819 {
3820 	char	**config_list = NULL;
3821 	uint_t	nelements;
3822 	char	*vidptr;
3823 	int	vidlen;
3824 	char	*dnlist_ptr;
3825 	char	*dataname_ptr;
3826 	char	*dataname_lasts;
3827 	int	*data_list = NULL;
3828 	uint_t	data_list_len;
3829 	int	rval = SD_FAILURE;
3830 	int	i;
3831 
3832 	ASSERT(un != NULL);
3833 
3834 	/* Obtain the configuration list associated with the .conf file */
3835 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, SD_DEVINFO(un),
3836 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, sd_config_list,
3837 	    &config_list, &nelements) != DDI_PROP_SUCCESS) {
3838 		return (SD_FAILURE);
3839 	}
3840 
3841 	/*
3842 	 * Compare vids in each duplet to the inquiry vid - if a match is
3843 	 * made, get the data value and update the soft state structure
3844 	 * accordingly.
3845 	 *
3846 	 * Each duplet should show as a pair of strings, return SD_FAILURE
3847 	 * otherwise.
3848 	 */
3849 	if (nelements & 1) {
3850 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3851 		    "sd-config-list should show as pairs of strings.\n");
3852 		if (config_list)
3853 			ddi_prop_free(config_list);
3854 		return (SD_FAILURE);
3855 	}
3856 
3857 	for (i = 0; i < nelements; i += 2) {
3858 		/*
3859 		 * Note: The assumption here is that each vid entry is on
3860 		 * a unique line from its associated duplet.
3861 		 */
3862 		vidptr = config_list[i];
3863 		vidlen = (int)strlen(vidptr);
3864 		if (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS) {
3865 			continue;
3866 		}
3867 
3868 		/*
3869 		 * dnlist contains 1 or more blank separated
3870 		 * data-property-name entries
3871 		 */
3872 		dnlist_ptr = config_list[i + 1];
3873 
3874 		if (strchr(dnlist_ptr, ':') != NULL) {
3875 			/*
3876 			 * Decode the improved format sd-config-list.
3877 			 */
3878 			sd_nvpair_str_decode(un, dnlist_ptr);
3879 		} else {
3880 			/*
3881 			 * The old format sd-config-list, loop through all
3882 			 * data-property-name entries in the
3883 			 * data-property-name-list
3884 			 * setting the properties for each.
3885 			 */
3886 			for (dataname_ptr = strtok_r(dnlist_ptr, " \t",
3887 			    &dataname_lasts); dataname_ptr != NULL;
3888 			    dataname_ptr = strtok_r(NULL, " \t",
3889 			    &dataname_lasts)) {
3890 				int version;
3891 
3892 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3893 				    "sd_process_sdconf_file: disk:%s, "
3894 				    "data:%s\n", vidptr, dataname_ptr);
3895 
3896 				/* Get the data list */
3897 				if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY,
3898 				    SD_DEVINFO(un), 0, dataname_ptr, &data_list,
3899 				    &data_list_len) != DDI_PROP_SUCCESS) {
3900 					SD_INFO(SD_LOG_ATTACH_DETACH, un,
3901 					    "sd_process_sdconf_file: data "
3902 					    "property (%s) has no value\n",
3903 					    dataname_ptr);
3904 					continue;
3905 				}
3906 
3907 				version = data_list[0];
3908 
3909 				if (version == SD_CONF_VERSION_1) {
3910 					sd_tunables values;
3911 
3912 					/* Set the properties */
3913 					if (sd_chk_vers1_data(un, data_list[1],
3914 					    &data_list[2], data_list_len,
3915 					    dataname_ptr) == SD_SUCCESS) {
3916 						sd_get_tunables_from_conf(un,
3917 						    data_list[1], &data_list[2],
3918 						    &values);
3919 						sd_set_vers1_properties(un,
3920 						    data_list[1], &values);
3921 						rval = SD_SUCCESS;
3922 					} else {
3923 						rval = SD_FAILURE;
3924 					}
3925 				} else {
3926 					scsi_log(SD_DEVINFO(un), sd_label,
3927 					    CE_WARN, "data property %s version "
3928 					    "0x%x is invalid.",
3929 					    dataname_ptr, version);
3930 					rval = SD_FAILURE;
3931 				}
3932 				if (data_list)
3933 					ddi_prop_free(data_list);
3934 			}
3935 		}
3936 	}
3937 
3938 	/* free up the memory allocated by ddi_prop_lookup_string_array(). */
3939 	if (config_list) {
3940 		ddi_prop_free(config_list);
3941 	}
3942 
3943 	return (rval);
3944 }
3945 
3946 /*
3947  *    Function: sd_nvpair_str_decode()
3948  *
3949  * Description: Parse the improved format sd-config-list to get
3950  *    each entry of tunable, which includes a name-value pair.
3951  *    Then call sd_set_properties() to set the property.
3952  *
3953  *   Arguments: un - driver soft state (unit) structure
3954  *    nvpair_str - the tunable list
3955  */
3956 static void
3957 sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str)
3958 {
3959 	char	*nv, *name, *value, *token;
3960 	char	*nv_lasts, *v_lasts, *x_lasts;
3961 
3962 	for (nv = strtok_r(nvpair_str, ",", &nv_lasts); nv != NULL;
3963 	    nv = strtok_r(NULL, ",", &nv_lasts)) {
3964 		token = strtok_r(nv, ":", &v_lasts);
3965 		name  = strtok_r(token, " \t", &x_lasts);
3966 		token = strtok_r(NULL, ":", &v_lasts);
3967 		value = strtok_r(token, " \t", &x_lasts);
3968 		if (name == NULL || value == NULL) {
3969 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3970 			    "sd_nvpair_str_decode: "
3971 			    "name or value is not valid!\n");
3972 		} else {
3973 			sd_set_properties(un, name, value);
3974 		}
3975 	}
3976 }
3977 
3978 /*
3979  *    Function: sd_set_properties()
3980  *
3981  * Description: Set device properties based on the improved
3982  *    format sd-config-list.
3983  *
3984  *   Arguments: un - driver soft state (unit) structure
3985  *    name  - supported tunable name
3986  *    value - tunable value
3987  */
3988 static void
3989 sd_set_properties(struct sd_lun *un, char *name, char *value)
3990 {
3991 	char	*endptr = NULL;
3992 	long	val = 0;
3993 
3994 	if (strcasecmp(name, "cache-nonvolatile") == 0) {
3995 		if (strcasecmp(value, "true") == 0) {
3996 			un->un_f_suppress_cache_flush = TRUE;
3997 		} else if (strcasecmp(value, "false") == 0) {
3998 			un->un_f_suppress_cache_flush = FALSE;
3999 		} else {
4000 			goto value_invalid;
4001 		}
4002 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4003 		    "suppress_cache_flush flag set to %d\n",
4004 		    un->un_f_suppress_cache_flush);
4005 		return;
4006 	}
4007 
4008 	if (strcasecmp(name, "controller-type") == 0) {
4009 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4010 			un->un_ctype = val;
4011 		} else {
4012 			goto value_invalid;
4013 		}
4014 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4015 		    "ctype set to %d\n", un->un_ctype);
4016 		return;
4017 	}
4018 
4019 	if (strcasecmp(name, "delay-busy") == 0) {
4020 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4021 			un->un_busy_timeout = drv_usectohz(val / 1000);
4022 		} else {
4023 			goto value_invalid;
4024 		}
4025 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4026 		    "busy_timeout set to %d\n", un->un_busy_timeout);
4027 		return;
4028 	}
4029 
4030 	if (strcasecmp(name, "disksort") == 0) {
4031 		if (strcasecmp(value, "true") == 0) {
4032 			un->un_f_disksort_disabled = FALSE;
4033 		} else if (strcasecmp(value, "false") == 0) {
4034 			un->un_f_disksort_disabled = TRUE;
4035 		} else {
4036 			goto value_invalid;
4037 		}
4038 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4039 		    "disksort disabled flag set to %d\n",
4040 		    un->un_f_disksort_disabled);
4041 		return;
4042 	}
4043 
4044 	if (strcasecmp(name, "power-condition") == 0) {
4045 		if (strcasecmp(value, "true") == 0) {
4046 			un->un_f_power_condition_disabled = FALSE;
4047 		} else if (strcasecmp(value, "false") == 0) {
4048 			un->un_f_power_condition_disabled = TRUE;
4049 		} else {
4050 			goto value_invalid;
4051 		}
4052 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4053 		    "power condition disabled flag set to %d\n",
4054 		    un->un_f_power_condition_disabled);
4055 		return;
4056 	}
4057 
4058 	if (strcasecmp(name, "timeout-releasereservation") == 0) {
4059 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4060 			un->un_reserve_release_time = val;
4061 		} else {
4062 			goto value_invalid;
4063 		}
4064 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4065 		    "reservation release timeout set to %d\n",
4066 		    un->un_reserve_release_time);
4067 		return;
4068 	}
4069 
4070 	if (strcasecmp(name, "reset-lun") == 0) {
4071 		if (strcasecmp(value, "true") == 0) {
4072 			un->un_f_lun_reset_enabled = TRUE;
4073 		} else if (strcasecmp(value, "false") == 0) {
4074 			un->un_f_lun_reset_enabled = FALSE;
4075 		} else {
4076 			goto value_invalid;
4077 		}
4078 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4079 		    "lun reset enabled flag set to %d\n",
4080 		    un->un_f_lun_reset_enabled);
4081 		return;
4082 	}
4083 
4084 	if (strcasecmp(name, "retries-busy") == 0) {
4085 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4086 			un->un_busy_retry_count = val;
4087 		} else {
4088 			goto value_invalid;
4089 		}
4090 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4091 		    "busy retry count set to %d\n", un->un_busy_retry_count);
4092 		return;
4093 	}
4094 
4095 	if (strcasecmp(name, "retries-timeout") == 0) {
4096 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4097 			un->un_retry_count = val;
4098 		} else {
4099 			goto value_invalid;
4100 		}
4101 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4102 		    "timeout retry count set to %d\n", un->un_retry_count);
4103 		return;
4104 	}
4105 
4106 	if (strcasecmp(name, "retries-notready") == 0) {
4107 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4108 			un->un_notready_retry_count = val;
4109 		} else {
4110 			goto value_invalid;
4111 		}
4112 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4113 		    "notready retry count set to %d\n",
4114 		    un->un_notready_retry_count);
4115 		return;
4116 	}
4117 
4118 	if (strcasecmp(name, "retries-reset") == 0) {
4119 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4120 			un->un_reset_retry_count = val;
4121 		} else {
4122 			goto value_invalid;
4123 		}
4124 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4125 		    "reset retry count set to %d\n",
4126 		    un->un_reset_retry_count);
4127 		return;
4128 	}
4129 
4130 	if (strcasecmp(name, "throttle-max") == 0) {
4131 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4132 			un->un_saved_throttle = un->un_throttle = val;
4133 		} else {
4134 			goto value_invalid;
4135 		}
4136 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4137 		    "throttle set to %d\n", un->un_throttle);
4138 	}
4139 
4140 	if (strcasecmp(name, "throttle-min") == 0) {
4141 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4142 			un->un_min_throttle = val;
4143 		} else {
4144 			goto value_invalid;
4145 		}
4146 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4147 		    "min throttle set to %d\n", un->un_min_throttle);
4148 	}
4149 
4150 	if (strcasecmp(name, "rmw-type") == 0) {
4151 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4152 			un->un_f_rmw_type = val;
4153 		} else {
4154 			goto value_invalid;
4155 		}
4156 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4157 		    "RMW type set to %d\n", un->un_f_rmw_type);
4158 	}
4159 
4160 	if (strcasecmp(name, "physical-block-size") == 0) {
4161 		if (ddi_strtol(value, &endptr, 0, &val) == 0 &&
4162 		    ISP2(val) && val >= un->un_tgt_blocksize &&
4163 		    val >= un->un_sys_blocksize) {
4164 			un->un_phy_blocksize = val;
4165 		} else {
4166 			goto value_invalid;
4167 		}
4168 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4169 		    "physical block size set to %d\n", un->un_phy_blocksize);
4170 	}
4171 
4172 	if (strcasecmp(name, "retries-victim") == 0) {
4173 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4174 			un->un_victim_retry_count = val;
4175 		} else {
4176 			goto value_invalid;
4177 		}
4178 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4179 		    "victim retry count set to %d\n",
4180 		    un->un_victim_retry_count);
4181 		return;
4182 	}
4183 
4184 	/*
4185 	 * Validate the throttle values.
4186 	 * If any of the numbers are invalid, set everything to defaults.
4187 	 */
4188 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4189 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4190 	    (un->un_min_throttle > un->un_throttle)) {
4191 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4192 		un->un_min_throttle = sd_min_throttle;
4193 	}
4194 
4195 	if (strcasecmp(name, "mmc-gesn-polling") == 0) {
4196 		if (strcasecmp(value, "true") == 0) {
4197 			un->un_f_mmc_gesn_polling = TRUE;
4198 		} else if (strcasecmp(value, "false") == 0) {
4199 			un->un_f_mmc_gesn_polling = FALSE;
4200 		} else {
4201 			goto value_invalid;
4202 		}
4203 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4204 		    "mmc-gesn-polling set to %d\n",
4205 		    un->un_f_mmc_gesn_polling);
4206 	}
4207 
4208 	return;
4209 
4210 value_invalid:
4211 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4212 	    "value of prop %s is invalid\n", name);
4213 }
4214 
4215 /*
4216  *    Function: sd_get_tunables_from_conf()
4217  *
4218  *
4219  *    This function reads the data list from the sd.conf file and pulls
4220  *    the values that can have numeric values as arguments and places
4221  *    the values in the appropriate sd_tunables member.
4222  *    Since the order of the data list members varies across platforms
4223  *    This function reads them from the data list in a platform specific
4224  *    order and places them into the correct sd_tunable member that is
4225  *    consistent across all platforms.
4226  */
4227 static void
4228 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
4229     sd_tunables *values)
4230 {
4231 	int i;
4232 	int mask;
4233 
4234 	bzero(values, sizeof (sd_tunables));
4235 
4236 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4237 
4238 		mask = 1 << i;
4239 		if (mask > flags) {
4240 			break;
4241 		}
4242 
4243 		switch (mask & flags) {
4244 		case 0:	/* This mask bit not set in flags */
4245 			continue;
4246 		case SD_CONF_BSET_THROTTLE:
4247 			values->sdt_throttle = data_list[i];
4248 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4249 			    "sd_get_tunables_from_conf: throttle = %d\n",
4250 			    values->sdt_throttle);
4251 			break;
4252 		case SD_CONF_BSET_CTYPE:
4253 			values->sdt_ctype = data_list[i];
4254 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4255 			    "sd_get_tunables_from_conf: ctype = %d\n",
4256 			    values->sdt_ctype);
4257 			break;
4258 		case SD_CONF_BSET_NRR_COUNT:
4259 			values->sdt_not_rdy_retries = data_list[i];
4260 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4261 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
4262 			    values->sdt_not_rdy_retries);
4263 			break;
4264 		case SD_CONF_BSET_BSY_RETRY_COUNT:
4265 			values->sdt_busy_retries = data_list[i];
4266 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4267 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
4268 			    values->sdt_busy_retries);
4269 			break;
4270 		case SD_CONF_BSET_RST_RETRIES:
4271 			values->sdt_reset_retries = data_list[i];
4272 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4273 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
4274 			    values->sdt_reset_retries);
4275 			break;
4276 		case SD_CONF_BSET_RSV_REL_TIME:
4277 			values->sdt_reserv_rel_time = data_list[i];
4278 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4279 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
4280 			    values->sdt_reserv_rel_time);
4281 			break;
4282 		case SD_CONF_BSET_MIN_THROTTLE:
4283 			values->sdt_min_throttle = data_list[i];
4284 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4285 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
4286 			    values->sdt_min_throttle);
4287 			break;
4288 		case SD_CONF_BSET_DISKSORT_DISABLED:
4289 			values->sdt_disk_sort_dis = data_list[i];
4290 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4291 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
4292 			    values->sdt_disk_sort_dis);
4293 			break;
4294 		case SD_CONF_BSET_LUN_RESET_ENABLED:
4295 			values->sdt_lun_reset_enable = data_list[i];
4296 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4297 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
4298 			    "\n", values->sdt_lun_reset_enable);
4299 			break;
4300 		case SD_CONF_BSET_CACHE_IS_NV:
4301 			values->sdt_suppress_cache_flush = data_list[i];
4302 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4303 			    "sd_get_tunables_from_conf: \
4304 			    suppress_cache_flush = %d"
4305 			    "\n", values->sdt_suppress_cache_flush);
4306 			break;
4307 		case SD_CONF_BSET_PC_DISABLED:
4308 			values->sdt_disk_sort_dis = data_list[i];
4309 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4310 			    "sd_get_tunables_from_conf: power_condition_dis = "
4311 			    "%d\n", values->sdt_power_condition_dis);
4312 			break;
4313 		}
4314 	}
4315 }
4316 
4317 /*
4318  *    Function: sd_process_sdconf_table
4319  *
4320  * Description: Search the static configuration table for a match on the
4321  *		inquiry vid/pid and update the driver soft state structure
4322  *		according to the table property values for the device.
4323  *
4324  *		The form of a configuration table entry is:
4325  *		  <vid+pid>,<flags>,<property-data>
4326  *		  "SEAGATE ST42400N",1,0x40000,
4327  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
4328  *
4329  *   Arguments: un - driver soft state (unit) structure
4330  */
4331 
4332 static void
4333 sd_process_sdconf_table(struct sd_lun *un)
4334 {
4335 	char	*id = NULL;
4336 	int	table_index;
4337 	int	idlen;
4338 
4339 	ASSERT(un != NULL);
4340 	for (table_index = 0; table_index < sd_disk_table_size;
4341 	    table_index++) {
4342 		id = sd_disk_table[table_index].device_id;
4343 		idlen = strlen(id);
4344 
4345 		/*
4346 		 * The static configuration table currently does not
4347 		 * implement version 10 properties. Additionally,
4348 		 * multiple data-property-name entries are not
4349 		 * implemented in the static configuration table.
4350 		 */
4351 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4352 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4353 			    "sd_process_sdconf_table: disk %s\n", id);
4354 			sd_set_vers1_properties(un,
4355 			    sd_disk_table[table_index].flags,
4356 			    sd_disk_table[table_index].properties);
4357 			break;
4358 		}
4359 	}
4360 }
4361 
4362 
4363 /*
4364  *    Function: sd_sdconf_id_match
4365  *
4366  * Description: This local function implements a case sensitive vid/pid
4367  *		comparison as well as the boundary cases of wild card and
4368  *		multiple blanks.
4369  *
4370  *		Note: An implicit assumption made here is that the scsi
4371  *		inquiry structure will always keep the vid, pid and
4372  *		revision strings in consecutive sequence, so they can be
4373  *		read as a single string. If this assumption is not the
4374  *		case, a separate string, to be used for the check, needs
4375  *		to be built with these strings concatenated.
4376  *
4377  *   Arguments: un - driver soft state (unit) structure
4378  *		id - table or config file vid/pid
4379  *		idlen  - length of the vid/pid (bytes)
4380  *
4381  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4382  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4383  */
4384 
4385 static int
4386 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
4387 {
4388 	struct scsi_inquiry	*sd_inq;
4389 	int			rval = SD_SUCCESS;
4390 
4391 	ASSERT(un != NULL);
4392 	sd_inq = un->un_sd->sd_inq;
4393 	ASSERT(id != NULL);
4394 
4395 	/*
4396 	 * We use the inq_vid as a pointer to a buffer containing the
4397 	 * vid and pid and use the entire vid/pid length of the table
4398 	 * entry for the comparison. This works because the inq_pid
4399 	 * data member follows inq_vid in the scsi_inquiry structure.
4400 	 */
4401 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
4402 		/*
4403 		 * The user id string is compared to the inquiry vid/pid
4404 		 * using a case insensitive comparison and ignoring
4405 		 * multiple spaces.
4406 		 */
4407 		rval = sd_blank_cmp(un, id, idlen);
4408 		if (rval != SD_SUCCESS) {
4409 			/*
4410 			 * User id strings that start and end with a "*"
4411 			 * are a special case. These do not have a
4412 			 * specific vendor, and the product string can
4413 			 * appear anywhere in the 16 byte PID portion of
4414 			 * the inquiry data. This is a simple strstr()
4415 			 * type search for the user id in the inquiry data.
4416 			 */
4417 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
4418 				char	*pidptr = &id[1];
4419 				int	i;
4420 				int	j;
4421 				int	pidstrlen = idlen - 2;
4422 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
4423 				    pidstrlen;
4424 
4425 				if (j < 0) {
4426 					return (SD_FAILURE);
4427 				}
4428 				for (i = 0; i < j; i++) {
4429 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
4430 					    pidptr, pidstrlen) == 0) {
4431 						rval = SD_SUCCESS;
4432 						break;
4433 					}
4434 				}
4435 			}
4436 		}
4437 	}
4438 	return (rval);
4439 }
4440 
4441 
4442 /*
4443  *    Function: sd_blank_cmp
4444  *
4445  * Description: If the id string starts and ends with a space, treat
4446  *		multiple consecutive spaces as equivalent to a single
4447  *		space. For example, this causes a sd_disk_table entry
4448  *		of " NEC CDROM " to match a device's id string of
4449  *		"NEC       CDROM".
4450  *
4451  *		Note: The success exit condition for this routine is if
4452  *		the pointer to the table entry is '\0' and the cnt of
4453  *		the inquiry length is zero. This will happen if the inquiry
4454  *		string returned by the device is padded with spaces to be
4455  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
4456  *		SCSI spec states that the inquiry string is to be padded with
4457  *		spaces.
4458  *
4459  *   Arguments: un - driver soft state (unit) structure
4460  *		id - table or config file vid/pid
4461  *		idlen  - length of the vid/pid (bytes)
4462  *
4463  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4464  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4465  */
4466 
4467 static int
4468 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
4469 {
4470 	char		*p1;
4471 	char		*p2;
4472 	int		cnt;
4473 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
4474 	    sizeof (SD_INQUIRY(un)->inq_pid);
4475 
4476 	ASSERT(un != NULL);
4477 	p2 = un->un_sd->sd_inq->inq_vid;
4478 	ASSERT(id != NULL);
4479 	p1 = id;
4480 
4481 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
4482 		/*
4483 		 * Note: string p1 is terminated by a NUL but string p2
4484 		 * isn't.  The end of p2 is determined by cnt.
4485 		 */
4486 		for (;;) {
4487 			/* skip over any extra blanks in both strings */
4488 			while ((*p1 != '\0') && (*p1 == ' ')) {
4489 				p1++;
4490 			}
4491 			while ((cnt != 0) && (*p2 == ' ')) {
4492 				p2++;
4493 				cnt--;
4494 			}
4495 
4496 			/* compare the two strings */
4497 			if ((cnt == 0) ||
4498 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
4499 				break;
4500 			}
4501 			while ((cnt > 0) &&
4502 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
4503 				p1++;
4504 				p2++;
4505 				cnt--;
4506 			}
4507 		}
4508 	}
4509 
4510 	/* return SD_SUCCESS if both strings match */
4511 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
4512 }
4513 
4514 
4515 /*
4516  *    Function: sd_chk_vers1_data
4517  *
4518  * Description: Verify the version 1 device properties provided by the
4519  *		user via the configuration file
4520  *
4521  *   Arguments: un	     - driver soft state (unit) structure
4522  *		flags	     - integer mask indicating properties to be set
4523  *		prop_list    - integer list of property values
4524  *		list_len     - number of the elements
4525  *
4526  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
4527  *		SD_FAILURE - Indicates the user provided data is invalid
4528  */
4529 
4530 static int
4531 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
4532     int list_len, char *dataname_ptr)
4533 {
4534 	int i;
4535 	int mask = 1;
4536 	int index = 0;
4537 
4538 	ASSERT(un != NULL);
4539 
4540 	/* Check for a NULL property name and list */
4541 	if (dataname_ptr == NULL) {
4542 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4543 		    "sd_chk_vers1_data: NULL data property name.");
4544 		return (SD_FAILURE);
4545 	}
4546 	if (prop_list == NULL) {
4547 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4548 		    "sd_chk_vers1_data: %s NULL data property list.",
4549 		    dataname_ptr);
4550 		return (SD_FAILURE);
4551 	}
4552 
4553 	/* Display a warning if undefined bits are set in the flags */
4554 	if (flags & ~SD_CONF_BIT_MASK) {
4555 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4556 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
4557 		    "Properties not set.",
4558 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
4559 		return (SD_FAILURE);
4560 	}
4561 
4562 	/*
4563 	 * Verify the length of the list by identifying the highest bit set
4564 	 * in the flags and validating that the property list has a length
4565 	 * up to the index of this bit.
4566 	 */
4567 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4568 		if (flags & mask) {
4569 			index++;
4570 		}
4571 		mask = 1 << i;
4572 	}
4573 	if (list_len < (index + 2)) {
4574 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4575 		    "sd_chk_vers1_data: "
4576 		    "Data property list %s size is incorrect. "
4577 		    "Properties not set.", dataname_ptr);
4578 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
4579 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
4580 		return (SD_FAILURE);
4581 	}
4582 	return (SD_SUCCESS);
4583 }
4584 
4585 
4586 /*
4587  *    Function: sd_set_vers1_properties
4588  *
4589  * Description: Set version 1 device properties based on a property list
4590  *		retrieved from the driver configuration file or static
4591  *		configuration table. Version 1 properties have the format:
4592  *
4593  *	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
4594  *
4595  *		where the prop0 value will be used to set prop0 if bit0
4596  *		is set in the flags
4597  *
4598  *   Arguments: un	     - driver soft state (unit) structure
4599  *		flags	     - integer mask indicating properties to be set
4600  *		prop_list    - integer list of property values
4601  */
4602 
4603 static void
4604 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4605 {
4606 	ASSERT(un != NULL);
4607 
4608 	/*
4609 	 * Set the flag to indicate cache is to be disabled. An attempt
4610 	 * to disable the cache via sd_cache_control() will be made
4611 	 * later during attach once the basic initialization is complete.
4612 	 */
4613 	if (flags & SD_CONF_BSET_NOCACHE) {
4614 		un->un_f_opt_disable_cache = TRUE;
4615 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4616 		    "sd_set_vers1_properties: caching disabled flag set\n");
4617 	}
4618 
4619 	/* CD-specific configuration parameters */
4620 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4621 		un->un_f_cfg_playmsf_bcd = TRUE;
4622 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4623 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4624 	}
4625 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4626 		un->un_f_cfg_readsub_bcd = TRUE;
4627 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4628 		    "sd_set_vers1_properties: readsub_bcd set\n");
4629 	}
4630 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4631 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4632 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4633 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4634 	}
4635 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4636 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4637 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4638 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4639 	}
4640 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4641 		un->un_f_cfg_no_read_header = TRUE;
4642 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4643 		    "sd_set_vers1_properties: no_read_header set\n");
4644 	}
4645 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4646 		un->un_f_cfg_read_cd_xd4 = TRUE;
4647 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4648 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4649 	}
4650 
4651 	/* Support for devices which do not have valid/unique serial numbers */
4652 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4653 		un->un_f_opt_fab_devid = TRUE;
4654 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4655 		    "sd_set_vers1_properties: fab_devid bit set\n");
4656 	}
4657 
4658 	/* Support for user throttle configuration */
4659 	if (flags & SD_CONF_BSET_THROTTLE) {
4660 		ASSERT(prop_list != NULL);
4661 		un->un_saved_throttle = un->un_throttle =
4662 		    prop_list->sdt_throttle;
4663 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4664 		    "sd_set_vers1_properties: throttle set to %d\n",
4665 		    prop_list->sdt_throttle);
4666 	}
4667 
4668 	/* Set the per disk retry count according to the conf file or table. */
4669 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4670 		ASSERT(prop_list != NULL);
4671 		if (prop_list->sdt_not_rdy_retries) {
4672 			un->un_notready_retry_count =
4673 			    prop_list->sdt_not_rdy_retries;
4674 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4675 			    "sd_set_vers1_properties: not ready retry count"
4676 			    " set to %d\n", un->un_notready_retry_count);
4677 		}
4678 	}
4679 
4680 	/* The controller type is reported for generic disk driver ioctls */
4681 	if (flags & SD_CONF_BSET_CTYPE) {
4682 		ASSERT(prop_list != NULL);
4683 		switch (prop_list->sdt_ctype) {
4684 		case CTYPE_CDROM:
4685 			un->un_ctype = prop_list->sdt_ctype;
4686 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4687 			    "sd_set_vers1_properties: ctype set to "
4688 			    "CTYPE_CDROM\n");
4689 			break;
4690 		case CTYPE_CCS:
4691 			un->un_ctype = prop_list->sdt_ctype;
4692 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4693 			    "sd_set_vers1_properties: ctype set to "
4694 			    "CTYPE_CCS\n");
4695 			break;
4696 		case CTYPE_ROD:		/* RW optical */
4697 			un->un_ctype = prop_list->sdt_ctype;
4698 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4699 			    "sd_set_vers1_properties: ctype set to "
4700 			    "CTYPE_ROD\n");
4701 			break;
4702 		default:
4703 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4704 			    "sd_set_vers1_properties: Could not set "
4705 			    "invalid ctype value (%d)",
4706 			    prop_list->sdt_ctype);
4707 		}
4708 	}
4709 
4710 	/* Purple failover timeout */
4711 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4712 		ASSERT(prop_list != NULL);
4713 		un->un_busy_retry_count =
4714 		    prop_list->sdt_busy_retries;
4715 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4716 		    "sd_set_vers1_properties: "
4717 		    "busy retry count set to %d\n",
4718 		    un->un_busy_retry_count);
4719 	}
4720 
4721 	/* Purple reset retry count */
4722 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4723 		ASSERT(prop_list != NULL);
4724 		un->un_reset_retry_count =
4725 		    prop_list->sdt_reset_retries;
4726 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4727 		    "sd_set_vers1_properties: "
4728 		    "reset retry count set to %d\n",
4729 		    un->un_reset_retry_count);
4730 	}
4731 
4732 	/* Purple reservation release timeout */
4733 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4734 		ASSERT(prop_list != NULL);
4735 		un->un_reserve_release_time =
4736 		    prop_list->sdt_reserv_rel_time;
4737 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4738 		    "sd_set_vers1_properties: "
4739 		    "reservation release timeout set to %d\n",
4740 		    un->un_reserve_release_time);
4741 	}
4742 
4743 	/*
4744 	 * Driver flag telling the driver to verify that no commands are pending
4745 	 * for a device before issuing a Test Unit Ready. This is a workaround
4746 	 * for a firmware bug in some Seagate eliteI drives.
4747 	 */
4748 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4749 		un->un_f_cfg_tur_check = TRUE;
4750 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4751 		    "sd_set_vers1_properties: tur queue check set\n");
4752 	}
4753 
4754 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4755 		un->un_min_throttle = prop_list->sdt_min_throttle;
4756 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4757 		    "sd_set_vers1_properties: min throttle set to %d\n",
4758 		    un->un_min_throttle);
4759 	}
4760 
4761 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4762 		un->un_f_disksort_disabled =
4763 		    (prop_list->sdt_disk_sort_dis != 0) ?
4764 		    TRUE : FALSE;
4765 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4766 		    "sd_set_vers1_properties: disksort disabled "
4767 		    "flag set to %d\n",
4768 		    prop_list->sdt_disk_sort_dis);
4769 	}
4770 
4771 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4772 		un->un_f_lun_reset_enabled =
4773 		    (prop_list->sdt_lun_reset_enable != 0) ?
4774 		    TRUE : FALSE;
4775 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4776 		    "sd_set_vers1_properties: lun reset enabled "
4777 		    "flag set to %d\n",
4778 		    prop_list->sdt_lun_reset_enable);
4779 	}
4780 
4781 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4782 		un->un_f_suppress_cache_flush =
4783 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4784 		    TRUE : FALSE;
4785 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4786 		    "sd_set_vers1_properties: suppress_cache_flush "
4787 		    "flag set to %d\n",
4788 		    prop_list->sdt_suppress_cache_flush);
4789 	}
4790 
4791 	if (flags & SD_CONF_BSET_PC_DISABLED) {
4792 		un->un_f_power_condition_disabled =
4793 		    (prop_list->sdt_power_condition_dis != 0) ?
4794 		    TRUE : FALSE;
4795 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4796 		    "sd_set_vers1_properties: power_condition_disabled "
4797 		    "flag set to %d\n",
4798 		    prop_list->sdt_power_condition_dis);
4799 	}
4800 
4801 	/*
4802 	 * Validate the throttle values.
4803 	 * If any of the numbers are invalid, set everything to defaults.
4804 	 */
4805 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4806 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4807 	    (un->un_min_throttle > un->un_throttle)) {
4808 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4809 		un->un_min_throttle = sd_min_throttle;
4810 	}
4811 }
4812 
4813 /*
4814  *   Function: sd_is_lsi()
4815  *
4816  *   Description: Check for lsi devices, step through the static device
4817  *	table to match vid/pid.
4818  *
4819  *   Args: un - ptr to sd_lun
4820  *
4821  *   Notes:  When creating new LSI property, need to add the new LSI property
4822  *		to this function.
4823  */
4824 static void
4825 sd_is_lsi(struct sd_lun *un)
4826 {
4827 	char	*id = NULL;
4828 	int	table_index;
4829 	int	idlen;
4830 	void	*prop;
4831 
4832 	ASSERT(un != NULL);
4833 	for (table_index = 0; table_index < sd_disk_table_size;
4834 	    table_index++) {
4835 		id = sd_disk_table[table_index].device_id;
4836 		idlen = strlen(id);
4837 		if (idlen == 0) {
4838 			continue;
4839 		}
4840 
4841 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4842 			prop = sd_disk_table[table_index].properties;
4843 			if (prop == &lsi_properties ||
4844 			    prop == &lsi_oem_properties ||
4845 			    prop == &lsi_properties_scsi ||
4846 			    prop == &symbios_properties) {
4847 				un->un_f_cfg_is_lsi = TRUE;
4848 			}
4849 			break;
4850 		}
4851 	}
4852 }
4853 
4854 /*
4855  *    Function: sd_get_physical_geometry
4856  *
4857  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4858  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4859  *		target, and use this information to initialize the physical
4860  *		geometry cache specified by pgeom_p.
4861  *
4862  *		MODE SENSE is an optional command, so failure in this case
4863  *		does not necessarily denote an error. We want to use the
4864  *		MODE SENSE commands to derive the physical geometry of the
4865  *		device, but if either command fails, the logical geometry is
4866  *		used as the fallback for disk label geometry in cmlb.
4867  *
4868  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4869  *		have already been initialized for the current target and
4870  *		that the current values be passed as args so that we don't
4871  *		end up ever trying to use -1 as a valid value. This could
4872  *		happen if either value is reset while we're not holding
4873  *		the mutex.
4874  *
4875  *   Arguments: un - driver soft state (unit) structure
4876  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4877  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4878  *			to use the USCSI "direct" chain and bypass the normal
4879  *			command waitq.
4880  *
4881  *     Context: Kernel thread only (can sleep).
4882  */
4883 
4884 static int
4885 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4886     diskaddr_t capacity, int lbasize, int path_flag)
4887 {
4888 	struct	mode_format	*page3p;
4889 	struct	mode_geometry	*page4p;
4890 	struct	mode_header	*headerp;
4891 	int	sector_size;
4892 	int	nsect;
4893 	int	nhead;
4894 	int	ncyl;
4895 	int	intrlv;
4896 	int	spc;
4897 	diskaddr_t	modesense_capacity;
4898 	int	rpm;
4899 	int	bd_len;
4900 	int	mode_header_length;
4901 	uchar_t	*p3bufp;
4902 	uchar_t	*p4bufp;
4903 	int	cdbsize;
4904 	int	ret = EIO;
4905 	sd_ssc_t *ssc;
4906 	int	status;
4907 
4908 	ASSERT(un != NULL);
4909 
4910 	if (lbasize == 0) {
4911 		if (ISCD(un)) {
4912 			lbasize = 2048;
4913 		} else {
4914 			lbasize = un->un_sys_blocksize;
4915 		}
4916 	}
4917 	pgeom_p->g_secsize = (unsigned short)lbasize;
4918 
4919 	/*
4920 	 * If the unit is a cd/dvd drive MODE SENSE page three
4921 	 * and MODE SENSE page four are reserved (see SBC spec
4922 	 * and MMC spec). To prevent soft errors just return
4923 	 * using the default LBA size.
4924 	 *
4925 	 * Since SATA MODE SENSE function (sata_txlt_mode_sense()) does not
4926 	 * implement support for mode pages 3 and 4 return here to prevent
4927 	 * illegal requests on SATA drives.
4928 	 *
4929 	 * These pages are also reserved in SBC-2 and later.  We assume SBC-2
4930 	 * or later for a direct-attached block device if the SCSI version is
4931 	 * at least SPC-3.
4932 	 */
4933 
4934 	if (ISCD(un) ||
4935 	    un->un_interconnect_type == SD_INTERCONNECT_SATA ||
4936 	    (un->un_ctype == CTYPE_CCS && SD_INQUIRY(un)->inq_ansi >= 5))
4937 		return (ret);
4938 
4939 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4940 
4941 	/*
4942 	 * Retrieve MODE SENSE page 3 - Format Device Page
4943 	 */
4944 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4945 	ssc = sd_ssc_init(un);
4946 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p3bufp,
4947 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag);
4948 	if (status != 0) {
4949 		SD_ERROR(SD_LOG_COMMON, un,
4950 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4951 		goto page3_exit;
4952 	}
4953 
4954 	/*
4955 	 * Determine size of Block Descriptors in order to locate the mode
4956 	 * page data.  ATAPI devices return 0, SCSI devices should return
4957 	 * MODE_BLK_DESC_LENGTH.
4958 	 */
4959 	headerp = (struct mode_header *)p3bufp;
4960 	if (un->un_f_cfg_is_atapi == TRUE) {
4961 		struct mode_header_grp2 *mhp =
4962 		    (struct mode_header_grp2 *)headerp;
4963 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4964 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4965 	} else {
4966 		mode_header_length = MODE_HEADER_LENGTH;
4967 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4968 	}
4969 
4970 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4971 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4972 		    "sd_get_physical_geometry: received unexpected bd_len "
4973 		    "of %d, page3\n", bd_len);
4974 		status = EIO;
4975 		goto page3_exit;
4976 	}
4977 
4978 	page3p = (struct mode_format *)
4979 	    ((caddr_t)headerp + mode_header_length + bd_len);
4980 
4981 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4982 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4983 		    "sd_get_physical_geometry: mode sense pg3 code mismatch "
4984 		    "%d\n", page3p->mode_page.code);
4985 		status = EIO;
4986 		goto page3_exit;
4987 	}
4988 
4989 	/*
4990 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4991 	 * complete successfully; otherwise, revert to the logical geometry.
4992 	 * So, we need to save everything in temporary variables.
4993 	 */
4994 	sector_size = BE_16(page3p->data_bytes_sect);
4995 
4996 	/*
4997 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4998 	 */
4999 	if (sector_size == 0) {
5000 		sector_size = un->un_sys_blocksize;
5001 	} else {
5002 		sector_size &= ~(un->un_sys_blocksize - 1);
5003 	}
5004 
5005 	nsect  = BE_16(page3p->sect_track);
5006 	intrlv = BE_16(page3p->interleave);
5007 
5008 	SD_INFO(SD_LOG_COMMON, un,
5009 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
5010 	SD_INFO(SD_LOG_COMMON, un,
5011 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
5012 	    page3p->mode_page.code, nsect, sector_size);
5013 	SD_INFO(SD_LOG_COMMON, un,
5014 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
5015 	    BE_16(page3p->track_skew),
5016 	    BE_16(page3p->cylinder_skew));
5017 
5018 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5019 
5020 	/*
5021 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
5022 	 */
5023 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
5024 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p4bufp,
5025 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag);
5026 	if (status != 0) {
5027 		SD_ERROR(SD_LOG_COMMON, un,
5028 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
5029 		goto page4_exit;
5030 	}
5031 
5032 	/*
5033 	 * Determine size of Block Descriptors in order to locate the mode
5034 	 * page data.  ATAPI devices return 0, SCSI devices should return
5035 	 * MODE_BLK_DESC_LENGTH.
5036 	 */
5037 	headerp = (struct mode_header *)p4bufp;
5038 	if (un->un_f_cfg_is_atapi == TRUE) {
5039 		struct mode_header_grp2 *mhp =
5040 		    (struct mode_header_grp2 *)headerp;
5041 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
5042 	} else {
5043 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
5044 	}
5045 
5046 	if (bd_len > MODE_BLK_DESC_LENGTH) {
5047 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5048 		    "sd_get_physical_geometry: received unexpected bd_len of "
5049 		    "%d, page4\n", bd_len);
5050 		status = EIO;
5051 		goto page4_exit;
5052 	}
5053 
5054 	page4p = (struct mode_geometry *)
5055 	    ((caddr_t)headerp + mode_header_length + bd_len);
5056 
5057 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
5058 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5059 		    "sd_get_physical_geometry: mode sense pg4 code mismatch "
5060 		    "%d\n", page4p->mode_page.code);
5061 		status = EIO;
5062 		goto page4_exit;
5063 	}
5064 
5065 	/*
5066 	 * Stash the data now, after we know that both commands completed.
5067 	 */
5068 
5069 
5070 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
5071 	spc   = nhead * nsect;
5072 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
5073 	rpm   = BE_16(page4p->rpm);
5074 
5075 	modesense_capacity = spc * ncyl;
5076 
5077 	SD_INFO(SD_LOG_COMMON, un,
5078 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
5079 	SD_INFO(SD_LOG_COMMON, un,
5080 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
5081 	SD_INFO(SD_LOG_COMMON, un,
5082 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
5083 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
5084 	    (void *)pgeom_p, capacity);
5085 
5086 	/*
5087 	 * Compensate if the drive's geometry is not rectangular, i.e.,
5088 	 * the product of C * H * S returned by MODE SENSE >= that returned
5089 	 * by read capacity. This is an idiosyncrasy of the original x86
5090 	 * disk subsystem.
5091 	 */
5092 	if (modesense_capacity >= capacity) {
5093 		SD_INFO(SD_LOG_COMMON, un,
5094 		    "sd_get_physical_geometry: adjusting acyl; "
5095 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
5096 		    (modesense_capacity - capacity + spc - 1) / spc);
5097 		if (sector_size != 0) {
5098 			/* 1243403: NEC D38x7 drives don't support sec size */
5099 			pgeom_p->g_secsize = (unsigned short)sector_size;
5100 		}
5101 		pgeom_p->g_nsect    = (unsigned short)nsect;
5102 		pgeom_p->g_nhead    = (unsigned short)nhead;
5103 		pgeom_p->g_capacity = capacity;
5104 		pgeom_p->g_acyl	    =
5105 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
5106 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
5107 	}
5108 
5109 	pgeom_p->g_rpm    = (unsigned short)rpm;
5110 	pgeom_p->g_intrlv = (unsigned short)intrlv;
5111 	ret = 0;
5112 
5113 	SD_INFO(SD_LOG_COMMON, un,
5114 	    "sd_get_physical_geometry: mode sense geometry:\n");
5115 	SD_INFO(SD_LOG_COMMON, un,
5116 	    "   nsect: %d; sector size: %d; interlv: %d\n",
5117 	    nsect, sector_size, intrlv);
5118 	SD_INFO(SD_LOG_COMMON, un,
5119 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
5120 	    nhead, ncyl, rpm, modesense_capacity);
5121 	SD_INFO(SD_LOG_COMMON, un,
5122 	    "sd_get_physical_geometry: (cached)\n");
5123 	SD_INFO(SD_LOG_COMMON, un,
5124 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5125 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
5126 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
5127 	SD_INFO(SD_LOG_COMMON, un,
5128 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
5129 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
5130 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
5131 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5132 
5133 page4_exit:
5134 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
5135 
5136 page3_exit:
5137 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
5138 
5139 	if (status != 0) {
5140 		if (status == EIO) {
5141 			/*
5142 			 * Some disks do not support mode sense(6), we
5143 			 * should ignore this kind of error(sense key is
5144 			 * 0x5 - illegal request).
5145 			 */
5146 			uint8_t *sensep;
5147 			int senlen;
5148 
5149 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
5150 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
5151 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
5152 
5153 			if (senlen > 0 &&
5154 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
5155 				sd_ssc_assessment(ssc,
5156 				    SD_FMT_IGNORE_COMPROMISE);
5157 			} else {
5158 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
5159 			}
5160 		} else {
5161 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5162 		}
5163 	}
5164 	sd_ssc_fini(ssc);
5165 	return (ret);
5166 }
5167 
5168 /*
5169  *    Function: sd_get_virtual_geometry
5170  *
5171  * Description: Ask the controller to tell us about the target device.
5172  *
5173  *   Arguments: un - pointer to softstate
5174  *		capacity - disk capacity in #blocks
5175  *		lbasize - disk block size in bytes
5176  *
5177  *     Context: Kernel thread only
5178  */
5179 
5180 static int
5181 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
5182     diskaddr_t capacity, int lbasize)
5183 {
5184 	uint_t	geombuf;
5185 	int	spc;
5186 
5187 	ASSERT(un != NULL);
5188 
5189 	/* Set sector size, and total number of sectors */
5190 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
5191 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
5192 
5193 	/* Let the HBA tell us its geometry */
5194 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
5195 
5196 	/* A value of -1 indicates an undefined "geometry" property */
5197 	if (geombuf == (-1)) {
5198 		return (EINVAL);
5199 	}
5200 
5201 	/* Initialize the logical geometry cache. */
5202 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
5203 	lgeom_p->g_nsect   = geombuf & 0xffff;
5204 	lgeom_p->g_secsize = un->un_sys_blocksize;
5205 
5206 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
5207 
5208 	/*
5209 	 * Note: The driver originally converted the capacity value from
5210 	 * target blocks to system blocks. However, the capacity value passed
5211 	 * to this routine is already in terms of system blocks (this scaling
5212 	 * is done when the READ CAPACITY command is issued and processed).
5213 	 * This 'error' may have gone undetected because the usage of g_ncyl
5214 	 * (which is based upon g_capacity) is very limited within the driver
5215 	 */
5216 	lgeom_p->g_capacity = capacity;
5217 
5218 	/*
5219 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
5220 	 * hba may return zero values if the device has been removed.
5221 	 */
5222 	if (spc == 0) {
5223 		lgeom_p->g_ncyl = 0;
5224 	} else {
5225 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
5226 	}
5227 	lgeom_p->g_acyl = 0;
5228 
5229 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
5230 	return (0);
5231 
5232 }
5233 /*
5234  *    Function: sd_update_block_info
5235  *
5236  * Description: Calculate a byte count to sector count bitshift value
5237  *		from sector size.
5238  *
5239  *   Arguments: un: unit struct.
5240  *		lbasize: new target sector size
5241  *		capacity: new target capacity, ie. block count
5242  *
5243  *     Context: Kernel thread context
5244  */
5245 
5246 static void
5247 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
5248 {
5249 	if (lbasize != 0) {
5250 		un->un_tgt_blocksize = lbasize;
5251 		un->un_f_tgt_blocksize_is_valid = TRUE;
5252 		if (!un->un_f_has_removable_media) {
5253 			un->un_sys_blocksize = lbasize;
5254 		}
5255 	}
5256 
5257 	if (capacity != 0) {
5258 		un->un_blockcount		= capacity;
5259 		un->un_f_blockcount_is_valid	= TRUE;
5260 
5261 		/*
5262 		 * The capacity has changed so update the errstats.
5263 		 */
5264 		if (un->un_errstats != NULL) {
5265 			struct sd_errstats *stp;
5266 
5267 			capacity *= un->un_sys_blocksize;
5268 			stp = (struct sd_errstats *)un->un_errstats->ks_data;
5269 			if (stp->sd_capacity.value.ui64 < capacity)
5270 				stp->sd_capacity.value.ui64 = capacity;
5271 		}
5272 	}
5273 }
5274 
5275 /*
5276  * Parses the SCSI Block Limits VPD page (0xB0). It's legal to pass NULL for
5277  * vpd_pg, in which case all the block limits will be reset to the defaults.
5278  */
5279 static void
5280 sd_parse_blk_limits_vpd(struct sd_lun *un, uchar_t *vpd_pg)
5281 {
5282 	sd_blk_limits_t *lim = &un->un_blk_lim;
5283 	unsigned pg_len;
5284 
5285 	if (vpd_pg != NULL)
5286 		pg_len = BE_IN16(&vpd_pg[2]);
5287 	else
5288 		pg_len = 0;
5289 
5290 	/* Block Limits VPD can be 16 bytes or 64 bytes long - support both */
5291 	if (pg_len >= 0x10) {
5292 		lim->lim_opt_xfer_len_gran = BE_IN16(&vpd_pg[6]);
5293 		lim->lim_max_xfer_len = BE_IN32(&vpd_pg[8]);
5294 		lim->lim_opt_xfer_len = BE_IN32(&vpd_pg[12]);
5295 
5296 		/* Zero means not reported, so use "unlimited" */
5297 		if (lim->lim_max_xfer_len == 0)
5298 			lim->lim_max_xfer_len = UINT32_MAX;
5299 		if (lim->lim_opt_xfer_len == 0)
5300 			lim->lim_opt_xfer_len = UINT32_MAX;
5301 	} else {
5302 		lim->lim_opt_xfer_len_gran = 0;
5303 		lim->lim_max_xfer_len = UINT32_MAX;
5304 		lim->lim_opt_xfer_len = UINT32_MAX;
5305 	}
5306 	if (pg_len >= 0x3c) {
5307 		lim->lim_max_pfetch_len = BE_IN32(&vpd_pg[16]);
5308 		/*
5309 		 * A zero in either of the following two fields indicates lack
5310 		 * of UNMAP support.
5311 		 */
5312 		lim->lim_max_unmap_lba_cnt = BE_IN32(&vpd_pg[20]);
5313 		lim->lim_max_unmap_descr_cnt = BE_IN32(&vpd_pg[24]);
5314 		lim->lim_opt_unmap_gran = BE_IN32(&vpd_pg[28]);
5315 		if ((vpd_pg[32] >> 7) == 1) {
5316 			lim->lim_unmap_gran_align =
5317 			    ((vpd_pg[32] & 0x7f) << 24) | (vpd_pg[33] << 16) |
5318 			    (vpd_pg[34] << 8) | vpd_pg[35];
5319 		} else {
5320 			lim->lim_unmap_gran_align = 0;
5321 		}
5322 		lim->lim_max_write_same_len = BE_IN64(&vpd_pg[36]);
5323 	} else {
5324 		lim->lim_max_pfetch_len = UINT32_MAX;
5325 		lim->lim_max_unmap_lba_cnt = UINT32_MAX;
5326 		lim->lim_max_unmap_descr_cnt = SD_UNMAP_MAX_DESCR;
5327 		lim->lim_opt_unmap_gran = 0;
5328 		lim->lim_unmap_gran_align = 0;
5329 		lim->lim_max_write_same_len = UINT64_MAX;
5330 	}
5331 }
5332 
5333 /*
5334  * Collects VPD page B0 data if available (block limits). If the data is
5335  * not available or querying the device failed, we revert to the defaults.
5336  */
5337 static void
5338 sd_setup_blk_limits(sd_ssc_t *ssc)
5339 {
5340 	struct sd_lun	*un		= ssc->ssc_un;
5341 	uchar_t		*inqB0		= NULL;
5342 	size_t		inqB0_resid	= 0;
5343 	int		rval;
5344 
5345 	if (un->un_vpd_page_mask & SD_VPD_BLK_LIMITS_PG) {
5346 		inqB0 = kmem_zalloc(MAX_INQUIRY_SIZE, KM_SLEEP);
5347 		rval = sd_send_scsi_INQUIRY(ssc, inqB0, MAX_INQUIRY_SIZE, 0x01,
5348 		    0xB0, &inqB0_resid);
5349 		if (rval != 0) {
5350 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5351 			kmem_free(inqB0, MAX_INQUIRY_SIZE);
5352 			inqB0 = NULL;
5353 		}
5354 	}
5355 	/* passing NULL inqB0 will reset to defaults */
5356 	sd_parse_blk_limits_vpd(ssc->ssc_un, inqB0);
5357 	if (inqB0)
5358 		kmem_free(inqB0, MAX_INQUIRY_SIZE);
5359 }
5360 
5361 /*
5362  *    Function: sd_register_devid
5363  *
5364  * Description: This routine will obtain the device id information from the
5365  *		target, obtain the serial number, and register the device
5366  *		id with the ddi framework.
5367  *
5368  *   Arguments: devi - the system's dev_info_t for the device.
5369  *		un - driver soft state (unit) structure
5370  *		reservation_flag - indicates if a reservation conflict
5371  *		occurred during attach
5372  *
5373  *     Context: Kernel Thread
5374  */
5375 static void
5376 sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi, int reservation_flag)
5377 {
5378 	int		rval		= 0;
5379 	uchar_t		*inq80		= NULL;
5380 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5381 	size_t		inq80_resid	= 0;
5382 	uchar_t		*inq83		= NULL;
5383 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5384 	size_t		inq83_resid	= 0;
5385 	int		dlen, len;
5386 	char		*sn;
5387 	struct sd_lun	*un;
5388 
5389 	ASSERT(ssc != NULL);
5390 	un = ssc->ssc_un;
5391 	ASSERT(un != NULL);
5392 	ASSERT(mutex_owned(SD_MUTEX(un)));
5393 	ASSERT((SD_DEVINFO(un)) == devi);
5394 
5395 
5396 	/*
5397 	 * We check the availability of the World Wide Name (0x83) and Unit
5398 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5399 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5400 	 * 0x83 is available, that is the best choice.  Our next choice is
5401 	 * 0x80.  If neither are available, we munge the devid from the device
5402 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5403 	 * to fabricate a devid for non-Sun qualified disks.
5404 	 */
5405 	if (sd_check_vpd_page_support(ssc) == 0) {
5406 		/* collect page 80 data if available */
5407 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5408 
5409 			mutex_exit(SD_MUTEX(un));
5410 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5411 
5412 			rval = sd_send_scsi_INQUIRY(ssc, inq80, inq80_len,
5413 			    0x01, 0x80, &inq80_resid);
5414 
5415 			if (rval != 0) {
5416 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5417 				kmem_free(inq80, inq80_len);
5418 				inq80 = NULL;
5419 				inq80_len = 0;
5420 			} else if (ddi_prop_exists(
5421 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
5422 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
5423 			    INQUIRY_SERIAL_NO) == 0) {
5424 				/*
5425 				 * If we don't already have a serial number
5426 				 * property, do quick verify of data returned
5427 				 * and define property.
5428 				 */
5429 				dlen = inq80_len - inq80_resid;
5430 				len = (size_t)inq80[3];
5431 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
5432 					/*
5433 					 * Ensure sn termination, skip leading
5434 					 * blanks, and create property
5435 					 * 'inquiry-serial-no'.
5436 					 */
5437 					sn = (char *)&inq80[4];
5438 					sn[len] = 0;
5439 					while (*sn && (*sn == ' '))
5440 						sn++;
5441 					if (*sn) {
5442 						(void) ddi_prop_update_string(
5443 						    DDI_DEV_T_NONE,
5444 						    SD_DEVINFO(un),
5445 						    INQUIRY_SERIAL_NO, sn);
5446 					}
5447 				}
5448 			}
5449 			mutex_enter(SD_MUTEX(un));
5450 		}
5451 
5452 		/* collect page 83 data if available */
5453 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5454 			mutex_exit(SD_MUTEX(un));
5455 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
5456 
5457 			rval = sd_send_scsi_INQUIRY(ssc, inq83, inq83_len,
5458 			    0x01, 0x83, &inq83_resid);
5459 
5460 			if (rval != 0) {
5461 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5462 				kmem_free(inq83, inq83_len);
5463 				inq83 = NULL;
5464 				inq83_len = 0;
5465 			}
5466 			mutex_enter(SD_MUTEX(un));
5467 		}
5468 	}
5469 
5470 	/*
5471 	 * If transport has already registered a devid for this target
5472 	 * then that takes precedence over the driver's determination
5473 	 * of the devid.
5474 	 *
5475 	 * NOTE: The reason this check is done here instead of at the beginning
5476 	 * of the function is to allow the code above to create the
5477 	 * 'inquiry-serial-no' property.
5478 	 */
5479 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
5480 		ASSERT(un->un_devid);
5481 		un->un_f_devid_transport_defined = TRUE;
5482 		goto cleanup; /* use devid registered by the transport */
5483 	}
5484 
5485 	/*
5486 	 * This is the case of antiquated Sun disk drives that have the
5487 	 * FAB_DEVID property set in the disk_table.  These drives
5488 	 * manage the devid's by storing them in last 2 available sectors
5489 	 * on the drive and have them fabricated by the ddi layer by calling
5490 	 * ddi_devid_init and passing the DEVID_FAB flag.
5491 	 */
5492 	if (un->un_f_opt_fab_devid == TRUE) {
5493 		/*
5494 		 * Depending on EINVAL isn't reliable, since a reserved disk
5495 		 * may result in invalid geometry, so check to make sure a
5496 		 * reservation conflict did not occur during attach.
5497 		 */
5498 		if ((sd_get_devid(ssc) == EINVAL) &&
5499 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5500 			/*
5501 			 * The devid is invalid AND there is no reservation
5502 			 * conflict.  Fabricate a new devid.
5503 			 */
5504 			(void) sd_create_devid(ssc);
5505 		}
5506 
5507 		/* Register the devid if it exists */
5508 		if (un->un_devid != NULL) {
5509 			(void) ddi_devid_register(SD_DEVINFO(un),
5510 			    un->un_devid);
5511 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5512 			    "sd_register_devid: Devid Fabricated\n");
5513 		}
5514 		goto cleanup;
5515 	}
5516 
5517 	/* encode best devid possible based on data available */
5518 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
5519 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
5520 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
5521 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
5522 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
5523 
5524 		/* devid successfully encoded, register devid */
5525 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
5526 
5527 	} else {
5528 		/*
5529 		 * Unable to encode a devid based on data available.
5530 		 * This is not a Sun qualified disk.  Older Sun disk
5531 		 * drives that have the SD_FAB_DEVID property
5532 		 * set in the disk_table and non Sun qualified
5533 		 * disks are treated in the same manner.  These
5534 		 * drives manage the devid's by storing them in
5535 		 * last 2 available sectors on the drive and
5536 		 * have them fabricated by the ddi layer by
5537 		 * calling ddi_devid_init and passing the
5538 		 * DEVID_FAB flag.
5539 		 * Create a fabricate devid only if there's no
5540 		 * fabricate devid existed.
5541 		 */
5542 		if (sd_get_devid(ssc) == EINVAL) {
5543 			(void) sd_create_devid(ssc);
5544 		}
5545 		un->un_f_opt_fab_devid = TRUE;
5546 
5547 		/* Register the devid if it exists */
5548 		if (un->un_devid != NULL) {
5549 			(void) ddi_devid_register(SD_DEVINFO(un),
5550 			    un->un_devid);
5551 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5552 			    "sd_register_devid: devid fabricated using "
5553 			    "ddi framework\n");
5554 		}
5555 	}
5556 
5557 cleanup:
5558 	/* clean up resources */
5559 	if (inq80 != NULL) {
5560 		kmem_free(inq80, inq80_len);
5561 	}
5562 	if (inq83 != NULL) {
5563 		kmem_free(inq83, inq83_len);
5564 	}
5565 }
5566 
5567 
5568 
5569 /*
5570  *    Function: sd_get_devid
5571  *
5572  * Description: This routine will return 0 if a valid device id has been
5573  *		obtained from the target and stored in the soft state. If a
5574  *		valid device id has not been previously read and stored, a
5575  *		read attempt will be made.
5576  *
5577  *   Arguments: un - driver soft state (unit) structure
5578  *
5579  * Return Code: 0 if we successfully get the device id
5580  *
5581  *     Context: Kernel Thread
5582  */
5583 
5584 static int
5585 sd_get_devid(sd_ssc_t *ssc)
5586 {
5587 	struct dk_devid		*dkdevid;
5588 	ddi_devid_t		tmpid;
5589 	uint_t			*ip;
5590 	size_t			sz;
5591 	diskaddr_t		blk;
5592 	int			status;
5593 	int			chksum;
5594 	int			i;
5595 	size_t			buffer_size;
5596 	struct sd_lun		*un;
5597 
5598 	ASSERT(ssc != NULL);
5599 	un = ssc->ssc_un;
5600 	ASSERT(un != NULL);
5601 	ASSERT(mutex_owned(SD_MUTEX(un)));
5602 
5603 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
5604 	    un);
5605 
5606 	if (un->un_devid != NULL) {
5607 		return (0);
5608 	}
5609 
5610 	mutex_exit(SD_MUTEX(un));
5611 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5612 	    (void *)SD_PATH_DIRECT) != 0) {
5613 		mutex_enter(SD_MUTEX(un));
5614 		return (EINVAL);
5615 	}
5616 
5617 	/*
5618 	 * Read and verify device id, stored in the reserved cylinders at the
5619 	 * end of the disk. Backup label is on the odd sectors of the last
5620 	 * track of the last cylinder. Device id will be on track of the next
5621 	 * to last cylinder.
5622 	 */
5623 	mutex_enter(SD_MUTEX(un));
5624 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
5625 	mutex_exit(SD_MUTEX(un));
5626 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
5627 	status = sd_send_scsi_READ(ssc, dkdevid, buffer_size, blk,
5628 	    SD_PATH_DIRECT);
5629 
5630 	if (status != 0) {
5631 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5632 		goto error;
5633 	}
5634 
5635 	/* Validate the revision */
5636 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
5637 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
5638 		status = EINVAL;
5639 		goto error;
5640 	}
5641 
5642 	/* Calculate the checksum */
5643 	chksum = 0;
5644 	ip = (uint_t *)dkdevid;
5645 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5646 	    i++) {
5647 		chksum ^= ip[i];
5648 	}
5649 
5650 	/* Compare the checksums */
5651 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
5652 		status = EINVAL;
5653 		goto error;
5654 	}
5655 
5656 	/* Validate the device id */
5657 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
5658 		status = EINVAL;
5659 		goto error;
5660 	}
5661 
5662 	/*
5663 	 * Store the device id in the driver soft state
5664 	 */
5665 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
5666 	tmpid = kmem_alloc(sz, KM_SLEEP);
5667 
5668 	mutex_enter(SD_MUTEX(un));
5669 
5670 	un->un_devid = tmpid;
5671 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
5672 
5673 	kmem_free(dkdevid, buffer_size);
5674 
5675 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
5676 
5677 	return (status);
5678 error:
5679 	mutex_enter(SD_MUTEX(un));
5680 	kmem_free(dkdevid, buffer_size);
5681 	return (status);
5682 }
5683 
5684 
5685 /*
5686  *    Function: sd_create_devid
5687  *
5688  * Description: This routine will fabricate the device id and write it
5689  *		to the disk.
5690  *
5691  *   Arguments: un - driver soft state (unit) structure
5692  *
5693  * Return Code: value of the fabricated device id
5694  *
5695  *     Context: Kernel Thread
5696  */
5697 
5698 static ddi_devid_t
5699 sd_create_devid(sd_ssc_t *ssc)
5700 {
5701 	struct sd_lun	*un;
5702 
5703 	ASSERT(ssc != NULL);
5704 	un = ssc->ssc_un;
5705 	ASSERT(un != NULL);
5706 
5707 	/* Fabricate the devid */
5708 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
5709 	    == DDI_FAILURE) {
5710 		return (NULL);
5711 	}
5712 
5713 	/* Write the devid to disk */
5714 	if (sd_write_deviceid(ssc) != 0) {
5715 		ddi_devid_free(un->un_devid);
5716 		un->un_devid = NULL;
5717 	}
5718 
5719 	return (un->un_devid);
5720 }
5721 
5722 
5723 /*
5724  *    Function: sd_write_deviceid
5725  *
5726  * Description: This routine will write the device id to the disk
5727  *		reserved sector.
5728  *
5729  *   Arguments: un - driver soft state (unit) structure
5730  *
5731  * Return Code: EINVAL
5732  *		value returned by sd_send_scsi_cmd
5733  *
5734  *     Context: Kernel Thread
5735  */
5736 
5737 static int
5738 sd_write_deviceid(sd_ssc_t *ssc)
5739 {
5740 	struct dk_devid		*dkdevid;
5741 	uchar_t			*buf;
5742 	diskaddr_t		blk;
5743 	uint_t			*ip, chksum;
5744 	int			status;
5745 	int			i;
5746 	struct sd_lun		*un;
5747 
5748 	ASSERT(ssc != NULL);
5749 	un = ssc->ssc_un;
5750 	ASSERT(un != NULL);
5751 	ASSERT(mutex_owned(SD_MUTEX(un)));
5752 
5753 	mutex_exit(SD_MUTEX(un));
5754 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5755 	    (void *)SD_PATH_DIRECT) != 0) {
5756 		mutex_enter(SD_MUTEX(un));
5757 		return (-1);
5758 	}
5759 
5760 
5761 	/* Allocate the buffer */
5762 	buf = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5763 	dkdevid = (struct dk_devid *)buf;
5764 
5765 	/* Fill in the revision */
5766 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5767 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5768 
5769 	/* Copy in the device id */
5770 	mutex_enter(SD_MUTEX(un));
5771 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5772 	    ddi_devid_sizeof(un->un_devid));
5773 	mutex_exit(SD_MUTEX(un));
5774 
5775 	/* Calculate the checksum */
5776 	chksum = 0;
5777 	ip = (uint_t *)dkdevid;
5778 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5779 	    i++) {
5780 		chksum ^= ip[i];
5781 	}
5782 
5783 	/* Fill-in checksum */
5784 	DKD_FORMCHKSUM(chksum, dkdevid);
5785 
5786 	/* Write the reserved sector */
5787 	status = sd_send_scsi_WRITE(ssc, buf, un->un_sys_blocksize, blk,
5788 	    SD_PATH_DIRECT);
5789 	if (status != 0)
5790 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5791 
5792 	kmem_free(buf, un->un_sys_blocksize);
5793 
5794 	mutex_enter(SD_MUTEX(un));
5795 	return (status);
5796 }
5797 
5798 
5799 /*
5800  *    Function: sd_check_vpd_page_support
5801  *
5802  * Description: This routine sends an inquiry command with the EVPD bit set and
5803  *		a page code of 0x00 to the device. It is used to determine which
5804  *		vital product pages are available to find the devid. We are
5805  *		looking for pages 0x83 0x80 or 0xB1.  If we return a negative 1,
5806  *		the device does not support that command.
5807  *
5808  *   Arguments: un  - driver soft state (unit) structure
5809  *
5810  * Return Code: 0 - success
5811  *		1 - check condition
5812  *
5813  *     Context: This routine can sleep.
5814  */
5815 
5816 static int
5817 sd_check_vpd_page_support(sd_ssc_t *ssc)
5818 {
5819 	uchar_t	*page_list	= NULL;
5820 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5821 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5822 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5823 	int	rval		= 0;
5824 	int	counter;
5825 	struct sd_lun		*un;
5826 
5827 	ASSERT(ssc != NULL);
5828 	un = ssc->ssc_un;
5829 	ASSERT(un != NULL);
5830 	ASSERT(mutex_owned(SD_MUTEX(un)));
5831 
5832 	mutex_exit(SD_MUTEX(un));
5833 
5834 	/*
5835 	 * We'll set the page length to the maximum to save figuring it out
5836 	 * with an additional call.
5837 	 */
5838 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5839 
5840 	rval = sd_send_scsi_INQUIRY(ssc, page_list, page_length, evpd,
5841 	    page_code, NULL);
5842 
5843 	if (rval != 0)
5844 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5845 
5846 	mutex_enter(SD_MUTEX(un));
5847 
5848 	/*
5849 	 * Now we must validate that the device accepted the command, as some
5850 	 * drives do not support it.  If the drive does support it, we will
5851 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5852 	 * not, we return -1.
5853 	 */
5854 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5855 		/* Loop to find one of the 2 pages we need */
5856 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5857 
5858 		/*
5859 		 * Pages are returned in ascending order, and 0x83 is what we
5860 		 * are hoping for.
5861 		 */
5862 		while ((page_list[counter] <= 0xB1) &&
5863 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5864 		    VPD_HEAD_OFFSET))) {
5865 			/*
5866 			 * Add 3 because page_list[3] is the number of
5867 			 * pages minus 3
5868 			 */
5869 
5870 			switch (page_list[counter]) {
5871 			case 0x00:
5872 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5873 				break;
5874 			case 0x80:
5875 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5876 				break;
5877 			case 0x81:
5878 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5879 				break;
5880 			case 0x82:
5881 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5882 				break;
5883 			case 0x83:
5884 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5885 				break;
5886 			case 0x86:
5887 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5888 				break;
5889 			case 0xB0:
5890 				un->un_vpd_page_mask |= SD_VPD_BLK_LIMITS_PG;
5891 				break;
5892 			case 0xB1:
5893 				un->un_vpd_page_mask |= SD_VPD_DEV_CHARACTER_PG;
5894 				break;
5895 			}
5896 			counter++;
5897 		}
5898 
5899 	} else {
5900 		rval = -1;
5901 
5902 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5903 		    "sd_check_vpd_page_support: This drive does not implement "
5904 		    "VPD pages.\n");
5905 	}
5906 
5907 	kmem_free(page_list, page_length);
5908 
5909 	return (rval);
5910 }
5911 
5912 
5913 /*
5914  *    Function: sd_setup_pm
5915  *
5916  * Description: Initialize Power Management on the device
5917  *
5918  *     Context: Kernel Thread
5919  */
5920 
5921 static void
5922 sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi)
5923 {
5924 	uint_t		log_page_size;
5925 	uchar_t		*log_page_data;
5926 	int		rval = 0;
5927 	struct sd_lun	*un;
5928 
5929 	ASSERT(ssc != NULL);
5930 	un = ssc->ssc_un;
5931 	ASSERT(un != NULL);
5932 
5933 	/*
5934 	 * Since we are called from attach, holding a mutex for
5935 	 * un is unnecessary. Because some of the routines called
5936 	 * from here require SD_MUTEX to not be held, assert this
5937 	 * right up front.
5938 	 */
5939 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5940 	/*
5941 	 * Since the sd device does not have the 'reg' property,
5942 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5943 	 * The following code is to tell cpr that this device
5944 	 * DOES need to be suspended and resumed.
5945 	 */
5946 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5947 	    "pm-hardware-state", "needs-suspend-resume");
5948 
5949 	/*
5950 	 * This complies with the new power management framework
5951 	 * for certain desktop machines. Create the pm_components
5952 	 * property as a string array property.
5953 	 * If un_f_pm_supported is TRUE, that means the disk
5954 	 * attached HBA has set the "pm-capable" property and
5955 	 * the value of this property is bigger than 0.
5956 	 */
5957 	if (un->un_f_pm_supported) {
5958 		/*
5959 		 * not all devices have a motor, try it first.
5960 		 * some devices may return ILLEGAL REQUEST, some
5961 		 * will hang
5962 		 * The following START_STOP_UNIT is used to check if target
5963 		 * device has a motor.
5964 		 */
5965 		un->un_f_start_stop_supported = TRUE;
5966 
5967 		if (un->un_f_power_condition_supported) {
5968 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5969 			    SD_POWER_CONDITION, SD_TARGET_ACTIVE,
5970 			    SD_PATH_DIRECT);
5971 			if (rval != 0) {
5972 				un->un_f_power_condition_supported = FALSE;
5973 			}
5974 		}
5975 		if (!un->un_f_power_condition_supported) {
5976 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5977 			    SD_START_STOP, SD_TARGET_START, SD_PATH_DIRECT);
5978 		}
5979 		if (rval != 0) {
5980 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5981 			un->un_f_start_stop_supported = FALSE;
5982 		}
5983 
5984 		/*
5985 		 * create pm properties anyways otherwise the parent can't
5986 		 * go to sleep
5987 		 */
5988 		un->un_f_pm_is_enabled = TRUE;
5989 		(void) sd_create_pm_components(devi, un);
5990 
5991 		/*
5992 		 * If it claims that log sense is supported, check it out.
5993 		 */
5994 		if (un->un_f_log_sense_supported) {
5995 			rval = sd_log_page_supported(ssc,
5996 			    START_STOP_CYCLE_PAGE);
5997 			if (rval == 1) {
5998 				/* Page found, use it. */
5999 				un->un_start_stop_cycle_page =
6000 				    START_STOP_CYCLE_PAGE;
6001 			} else {
6002 				/*
6003 				 * Page not found or log sense is not
6004 				 * supported.
6005 				 * Notice we do not check the old style
6006 				 * START_STOP_CYCLE_VU_PAGE because this
6007 				 * code path does not apply to old disks.
6008 				 */
6009 				un->un_f_log_sense_supported = FALSE;
6010 				un->un_f_pm_log_sense_smart = FALSE;
6011 			}
6012 		}
6013 
6014 		return;
6015 	}
6016 
6017 	/*
6018 	 * For the disk whose attached HBA has not set the "pm-capable"
6019 	 * property, check if it supports the power management.
6020 	 */
6021 	if (!un->un_f_log_sense_supported) {
6022 		un->un_power_level = SD_SPINDLE_ON;
6023 		un->un_f_pm_is_enabled = FALSE;
6024 		return;
6025 	}
6026 
6027 	rval = sd_log_page_supported(ssc, START_STOP_CYCLE_PAGE);
6028 
6029 #ifdef	SDDEBUG
6030 	if (sd_force_pm_supported) {
6031 		/* Force a successful result */
6032 		rval = 1;
6033 	}
6034 #endif
6035 
6036 	/*
6037 	 * If the start-stop cycle counter log page is not supported
6038 	 * or if the pm-capable property is set to be false (0),
6039 	 * then we should not create the pm_components property.
6040 	 */
6041 	if (rval == -1) {
6042 		/*
6043 		 * Error.
6044 		 * Reading log sense failed, most likely this is
6045 		 * an older drive that does not support log sense.
6046 		 * If this fails auto-pm is not supported.
6047 		 */
6048 		un->un_power_level = SD_SPINDLE_ON;
6049 		un->un_f_pm_is_enabled = FALSE;
6050 
6051 	} else if (rval == 0) {
6052 		/*
6053 		 * Page not found.
6054 		 * The start stop cycle counter is implemented as page
6055 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
6056 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
6057 		 */
6058 		if (sd_log_page_supported(ssc, START_STOP_CYCLE_VU_PAGE) == 1) {
6059 			/*
6060 			 * Page found, use this one.
6061 			 */
6062 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
6063 			un->un_f_pm_is_enabled = TRUE;
6064 		} else {
6065 			/*
6066 			 * Error or page not found.
6067 			 * auto-pm is not supported for this device.
6068 			 */
6069 			un->un_power_level = SD_SPINDLE_ON;
6070 			un->un_f_pm_is_enabled = FALSE;
6071 		}
6072 	} else {
6073 		/*
6074 		 * Page found, use it.
6075 		 */
6076 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
6077 		un->un_f_pm_is_enabled = TRUE;
6078 	}
6079 
6080 
6081 	if (un->un_f_pm_is_enabled == TRUE) {
6082 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6083 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6084 
6085 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6086 		    log_page_size, un->un_start_stop_cycle_page,
6087 		    0x01, 0, SD_PATH_DIRECT);
6088 
6089 		if (rval != 0) {
6090 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6091 		}
6092 
6093 #ifdef	SDDEBUG
6094 		if (sd_force_pm_supported) {
6095 			/* Force a successful result */
6096 			rval = 0;
6097 		}
6098 #endif
6099 
6100 		/*
6101 		 * If the Log sense for Page( Start/stop cycle counter page)
6102 		 * succeeds, then power management is supported and we can
6103 		 * enable auto-pm.
6104 		 */
6105 		if (rval == 0)  {
6106 			(void) sd_create_pm_components(devi, un);
6107 		} else {
6108 			un->un_power_level = SD_SPINDLE_ON;
6109 			un->un_f_pm_is_enabled = FALSE;
6110 		}
6111 
6112 		kmem_free(log_page_data, log_page_size);
6113 	}
6114 }
6115 
6116 
6117 /*
6118  *    Function: sd_create_pm_components
6119  *
6120  * Description: Initialize PM property.
6121  *
6122  *     Context: Kernel thread context
6123  */
6124 
6125 static void
6126 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
6127 {
6128 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6129 
6130 	if (un->un_f_power_condition_supported) {
6131 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6132 		    "pm-components", sd_pwr_pc.pm_comp, 5)
6133 		    != DDI_PROP_SUCCESS) {
6134 			un->un_power_level = SD_SPINDLE_ACTIVE;
6135 			un->un_f_pm_is_enabled = FALSE;
6136 			return;
6137 		}
6138 	} else {
6139 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6140 		    "pm-components", sd_pwr_ss.pm_comp, 3)
6141 		    != DDI_PROP_SUCCESS) {
6142 			un->un_power_level = SD_SPINDLE_ON;
6143 			un->un_f_pm_is_enabled = FALSE;
6144 			return;
6145 		}
6146 	}
6147 	/*
6148 	 * When components are initially created they are idle,
6149 	 * power up any non-removables.
6150 	 * Note: the return value of pm_raise_power can't be used
6151 	 * for determining if PM should be enabled for this device.
6152 	 * Even if you check the return values and remove this
6153 	 * property created above, the PM framework will not honor the
6154 	 * change after the first call to pm_raise_power. Hence,
6155 	 * removal of that property does not help if pm_raise_power
6156 	 * fails. In the case of removable media, the start/stop
6157 	 * will fail if the media is not present.
6158 	 */
6159 	if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
6160 	    SD_PM_STATE_ACTIVE(un)) == DDI_SUCCESS)) {
6161 		mutex_enter(SD_MUTEX(un));
6162 		un->un_power_level = SD_PM_STATE_ACTIVE(un);
6163 		mutex_enter(&un->un_pm_mutex);
6164 		/* Set to on and not busy. */
6165 		un->un_pm_count = 0;
6166 	} else {
6167 		mutex_enter(SD_MUTEX(un));
6168 		un->un_power_level = SD_PM_STATE_STOPPED(un);
6169 		mutex_enter(&un->un_pm_mutex);
6170 		/* Set to off. */
6171 		un->un_pm_count = -1;
6172 	}
6173 	mutex_exit(&un->un_pm_mutex);
6174 	mutex_exit(SD_MUTEX(un));
6175 }
6176 
6177 
6178 /*
6179  *    Function: sd_ddi_suspend
6180  *
6181  * Description: Performs system power-down operations. This includes
6182  *		setting the drive state to indicate its suspended so
6183  *		that no new commands will be accepted. Also, wait for
6184  *		all commands that are in transport or queued to a timer
6185  *		for retry to complete. All timeout threads are cancelled.
6186  *
6187  * Return Code: DDI_FAILURE or DDI_SUCCESS
6188  *
6189  *     Context: Kernel thread context
6190  */
6191 
6192 static int
6193 sd_ddi_suspend(dev_info_t *devi)
6194 {
6195 	struct	sd_lun	*un;
6196 	clock_t		wait_cmds_complete;
6197 
6198 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6199 	if (un == NULL) {
6200 		return (DDI_FAILURE);
6201 	}
6202 
6203 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
6204 
6205 	mutex_enter(SD_MUTEX(un));
6206 
6207 	/* Return success if the device is already suspended. */
6208 	if (un->un_state == SD_STATE_SUSPENDED) {
6209 		mutex_exit(SD_MUTEX(un));
6210 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6211 		    "device already suspended, exiting\n");
6212 		return (DDI_SUCCESS);
6213 	}
6214 
6215 	/* Return failure if the device is being used by HA */
6216 	if (un->un_resvd_status &
6217 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
6218 		mutex_exit(SD_MUTEX(un));
6219 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6220 		    "device in use by HA, exiting\n");
6221 		return (DDI_FAILURE);
6222 	}
6223 
6224 	/*
6225 	 * Return failure if the device is in a resource wait
6226 	 * or power changing state.
6227 	 */
6228 	if ((un->un_state == SD_STATE_RWAIT) ||
6229 	    (un->un_state == SD_STATE_PM_CHANGING)) {
6230 		mutex_exit(SD_MUTEX(un));
6231 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6232 		    "device in resource wait state, exiting\n");
6233 		return (DDI_FAILURE);
6234 	}
6235 
6236 
6237 	un->un_save_state = un->un_last_state;
6238 	New_state(un, SD_STATE_SUSPENDED);
6239 
6240 	/*
6241 	 * Wait for all commands that are in transport or queued to a timer
6242 	 * for retry to complete.
6243 	 *
6244 	 * While waiting, no new commands will be accepted or sent because of
6245 	 * the new state we set above.
6246 	 *
6247 	 * Wait till current operation has completed. If we are in the resource
6248 	 * wait state (with an intr outstanding) then we need to wait till the
6249 	 * intr completes and starts the next cmd. We want to wait for
6250 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
6251 	 */
6252 	wait_cmds_complete = ddi_get_lbolt() +
6253 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
6254 
6255 	while (un->un_ncmds_in_transport != 0) {
6256 		/*
6257 		 * Fail if commands do not finish in the specified time.
6258 		 */
6259 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
6260 		    wait_cmds_complete) == -1) {
6261 			/*
6262 			 * Undo the state changes made above. Everything
6263 			 * must go back to it's original value.
6264 			 */
6265 			Restore_state(un);
6266 			un->un_last_state = un->un_save_state;
6267 			/* Wake up any threads that might be waiting. */
6268 			cv_broadcast(&un->un_suspend_cv);
6269 			mutex_exit(SD_MUTEX(un));
6270 			SD_ERROR(SD_LOG_IO_PM, un,
6271 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
6272 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
6273 			return (DDI_FAILURE);
6274 		}
6275 	}
6276 
6277 	/*
6278 	 * Cancel SCSI watch thread and timeouts, if any are active
6279 	 */
6280 
6281 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
6282 		opaque_t temp_token = un->un_swr_token;
6283 		mutex_exit(SD_MUTEX(un));
6284 		scsi_watch_suspend(temp_token);
6285 		mutex_enter(SD_MUTEX(un));
6286 	}
6287 
6288 	if (un->un_reset_throttle_timeid != NULL) {
6289 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
6290 		un->un_reset_throttle_timeid = NULL;
6291 		mutex_exit(SD_MUTEX(un));
6292 		(void) untimeout(temp_id);
6293 		mutex_enter(SD_MUTEX(un));
6294 	}
6295 
6296 	if (un->un_dcvb_timeid != NULL) {
6297 		timeout_id_t temp_id = un->un_dcvb_timeid;
6298 		un->un_dcvb_timeid = NULL;
6299 		mutex_exit(SD_MUTEX(un));
6300 		(void) untimeout(temp_id);
6301 		mutex_enter(SD_MUTEX(un));
6302 	}
6303 
6304 	mutex_enter(&un->un_pm_mutex);
6305 	if (un->un_pm_timeid != NULL) {
6306 		timeout_id_t temp_id = un->un_pm_timeid;
6307 		un->un_pm_timeid = NULL;
6308 		mutex_exit(&un->un_pm_mutex);
6309 		mutex_exit(SD_MUTEX(un));
6310 		(void) untimeout(temp_id);
6311 		mutex_enter(SD_MUTEX(un));
6312 	} else {
6313 		mutex_exit(&un->un_pm_mutex);
6314 	}
6315 
6316 	if (un->un_rmw_msg_timeid != NULL) {
6317 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
6318 		un->un_rmw_msg_timeid = NULL;
6319 		mutex_exit(SD_MUTEX(un));
6320 		(void) untimeout(temp_id);
6321 		mutex_enter(SD_MUTEX(un));
6322 	}
6323 
6324 	if (un->un_retry_timeid != NULL) {
6325 		timeout_id_t temp_id = un->un_retry_timeid;
6326 		un->un_retry_timeid = NULL;
6327 		mutex_exit(SD_MUTEX(un));
6328 		(void) untimeout(temp_id);
6329 		mutex_enter(SD_MUTEX(un));
6330 
6331 		if (un->un_retry_bp != NULL) {
6332 			un->un_retry_bp->av_forw = un->un_waitq_headp;
6333 			un->un_waitq_headp = un->un_retry_bp;
6334 			if (un->un_waitq_tailp == NULL) {
6335 				un->un_waitq_tailp = un->un_retry_bp;
6336 			}
6337 			un->un_retry_bp = NULL;
6338 			un->un_retry_statp = NULL;
6339 		}
6340 	}
6341 
6342 	if (un->un_direct_priority_timeid != NULL) {
6343 		timeout_id_t temp_id = un->un_direct_priority_timeid;
6344 		un->un_direct_priority_timeid = NULL;
6345 		mutex_exit(SD_MUTEX(un));
6346 		(void) untimeout(temp_id);
6347 		mutex_enter(SD_MUTEX(un));
6348 	}
6349 
6350 	if (un->un_f_is_fibre == TRUE) {
6351 		/*
6352 		 * Remove callbacks for insert and remove events
6353 		 */
6354 		if (un->un_insert_event != NULL) {
6355 			mutex_exit(SD_MUTEX(un));
6356 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
6357 			mutex_enter(SD_MUTEX(un));
6358 			un->un_insert_event = NULL;
6359 		}
6360 
6361 		if (un->un_remove_event != NULL) {
6362 			mutex_exit(SD_MUTEX(un));
6363 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
6364 			mutex_enter(SD_MUTEX(un));
6365 			un->un_remove_event = NULL;
6366 		}
6367 	}
6368 
6369 	mutex_exit(SD_MUTEX(un));
6370 
6371 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
6372 
6373 	return (DDI_SUCCESS);
6374 }
6375 
6376 
6377 /*
6378  *    Function: sd_ddi_resume
6379  *
6380  * Description: Performs system power-up operations..
6381  *
6382  * Return Code: DDI_SUCCESS
6383  *		DDI_FAILURE
6384  *
6385  *     Context: Kernel thread context
6386  */
6387 
6388 static int
6389 sd_ddi_resume(dev_info_t *devi)
6390 {
6391 	struct	sd_lun	*un;
6392 
6393 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6394 	if (un == NULL) {
6395 		return (DDI_FAILURE);
6396 	}
6397 
6398 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6399 
6400 	mutex_enter(SD_MUTEX(un));
6401 	Restore_state(un);
6402 
6403 	/*
6404 	 * Restore the state which was saved to give the
6405 	 * the right state in un_last_state
6406 	 */
6407 	un->un_last_state = un->un_save_state;
6408 	/*
6409 	 * Note: throttle comes back at full.
6410 	 * Also note: this MUST be done before calling pm_raise_power
6411 	 * otherwise the system can get hung in biowait. The scenario where
6412 	 * this'll happen is under cpr suspend. Writing of the system
6413 	 * state goes through sddump, which writes 0 to un_throttle. If
6414 	 * writing the system state then fails, example if the partition is
6415 	 * too small, then cpr attempts a resume. If throttle isn't restored
6416 	 * from the saved value until after calling pm_raise_power then
6417 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6418 	 * in biowait.
6419 	 */
6420 	un->un_throttle = un->un_saved_throttle;
6421 
6422 	/*
6423 	 * The chance of failure is very rare as the only command done in power
6424 	 * entry point is START command when you transition from 0->1 or
6425 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6426 	 * which suspend was done. Ignore the return value as the resume should
6427 	 * not be failed. In the case of removable media the media need not be
6428 	 * inserted and hence there is a chance that raise power will fail with
6429 	 * media not present.
6430 	 */
6431 	if (un->un_f_attach_spinup) {
6432 		mutex_exit(SD_MUTEX(un));
6433 		(void) pm_raise_power(SD_DEVINFO(un), 0,
6434 		    SD_PM_STATE_ACTIVE(un));
6435 		mutex_enter(SD_MUTEX(un));
6436 	}
6437 
6438 	/*
6439 	 * Don't broadcast to the suspend cv and therefore possibly
6440 	 * start I/O until after power has been restored.
6441 	 */
6442 	cv_broadcast(&un->un_suspend_cv);
6443 	cv_broadcast(&un->un_state_cv);
6444 
6445 	/* restart thread */
6446 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6447 		scsi_watch_resume(un->un_swr_token);
6448 	}
6449 
6450 #if (defined(__fibre))
6451 	if (un->un_f_is_fibre == TRUE) {
6452 		/*
6453 		 * Add callbacks for insert and remove events
6454 		 */
6455 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6456 			sd_init_event_callbacks(un);
6457 		}
6458 	}
6459 #endif
6460 
6461 	/*
6462 	 * Transport any pending commands to the target.
6463 	 *
6464 	 * If this is a low-activity device commands in queue will have to wait
6465 	 * until new commands come in, which may take awhile. Also, we
6466 	 * specifically don't check un_ncmds_in_transport because we know that
6467 	 * there really are no commands in progress after the unit was
6468 	 * suspended and we could have reached the throttle level, been
6469 	 * suspended, and have no new commands coming in for awhile. Highly
6470 	 * unlikely, but so is the low-activity disk scenario.
6471 	 */
6472 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6473 
6474 	sd_start_cmds(un, NULL);
6475 	mutex_exit(SD_MUTEX(un));
6476 
6477 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6478 
6479 	return (DDI_SUCCESS);
6480 }
6481 
6482 
6483 /*
6484  *    Function: sd_pm_state_change
6485  *
6486  * Description: Change the driver power state.
6487  *		Someone else is required to actually change the driver
6488  *		power level.
6489  *
6490  *   Arguments: un - driver soft state (unit) structure
6491  *              level - the power level that is changed to
6492  *              flag - to decide how to change the power state
6493  *
6494  * Return Code: DDI_SUCCESS
6495  *
6496  *     Context: Kernel thread context
6497  */
6498 static int
6499 sd_pm_state_change(struct sd_lun *un, int level, int flag)
6500 {
6501 	ASSERT(un != NULL);
6502 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: entry\n");
6503 
6504 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6505 	mutex_enter(SD_MUTEX(un));
6506 
6507 	if (flag == SD_PM_STATE_ROLLBACK || SD_PM_IS_IO_CAPABLE(un, level)) {
6508 		un->un_power_level = level;
6509 		ASSERT(!mutex_owned(&un->un_pm_mutex));
6510 		mutex_enter(&un->un_pm_mutex);
6511 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6512 			un->un_pm_count++;
6513 			ASSERT(un->un_pm_count == 0);
6514 		}
6515 		mutex_exit(&un->un_pm_mutex);
6516 	} else {
6517 		/*
6518 		 * Exit if power management is not enabled for this device,
6519 		 * or if the device is being used by HA.
6520 		 */
6521 		if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
6522 		    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
6523 			mutex_exit(SD_MUTEX(un));
6524 			SD_TRACE(SD_LOG_POWER, un,
6525 			    "sd_pm_state_change: exiting\n");
6526 			return (DDI_FAILURE);
6527 		}
6528 
6529 		SD_INFO(SD_LOG_POWER, un, "sd_pm_state_change: "
6530 		    "un_ncmds_in_driver=%ld\n", un->un_ncmds_in_driver);
6531 
6532 		/*
6533 		 * See if the device is not busy, ie.:
6534 		 *    - we have no commands in the driver for this device
6535 		 *    - not waiting for resources
6536 		 */
6537 		if ((un->un_ncmds_in_driver == 0) &&
6538 		    (un->un_state != SD_STATE_RWAIT)) {
6539 			/*
6540 			 * The device is not busy, so it is OK to go to low
6541 			 * power state. Indicate low power, but rely on someone
6542 			 * else to actually change it.
6543 			 */
6544 			mutex_enter(&un->un_pm_mutex);
6545 			un->un_pm_count = -1;
6546 			mutex_exit(&un->un_pm_mutex);
6547 			un->un_power_level = level;
6548 		}
6549 	}
6550 
6551 	mutex_exit(SD_MUTEX(un));
6552 
6553 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: exit\n");
6554 
6555 	return (DDI_SUCCESS);
6556 }
6557 
6558 
6559 /*
6560  *    Function: sd_pm_idletimeout_handler
6561  *
6562  * Description: A timer routine that's active only while a device is busy.
6563  *		The purpose is to extend slightly the pm framework's busy
6564  *		view of the device to prevent busy/idle thrashing for
6565  *		back-to-back commands. Do this by comparing the current time
6566  *		to the time at which the last command completed and when the
6567  *		difference is greater than sd_pm_idletime, call
6568  *		pm_idle_component. In addition to indicating idle to the pm
6569  *		framework, update the chain type to again use the internal pm
6570  *		layers of the driver.
6571  *
6572  *   Arguments: arg - driver soft state (unit) structure
6573  *
6574  *     Context: Executes in a timeout(9F) thread context
6575  */
6576 
6577 static void
6578 sd_pm_idletimeout_handler(void *arg)
6579 {
6580 	const hrtime_t idletime = sd_pm_idletime * NANOSEC;
6581 	struct sd_lun *un = arg;
6582 
6583 	mutex_enter(&sd_detach_mutex);
6584 	if (un->un_detach_count != 0) {
6585 		/* Abort if the instance is detaching */
6586 		mutex_exit(&sd_detach_mutex);
6587 		return;
6588 	}
6589 	mutex_exit(&sd_detach_mutex);
6590 
6591 	/*
6592 	 * Grab both mutexes, in the proper order, since we're accessing
6593 	 * both PM and softstate variables.
6594 	 */
6595 	mutex_enter(SD_MUTEX(un));
6596 	mutex_enter(&un->un_pm_mutex);
6597 	if (((gethrtime() - un->un_pm_idle_time) > idletime) &&
6598 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
6599 		/*
6600 		 * Update the chain types.
6601 		 * This takes affect on the next new command received.
6602 		 */
6603 		if (un->un_f_non_devbsize_supported) {
6604 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6605 		} else {
6606 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6607 		}
6608 		un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD;
6609 
6610 		SD_TRACE(SD_LOG_IO_PM, un,
6611 		    "sd_pm_idletimeout_handler: idling device\n");
6612 		(void) pm_idle_component(SD_DEVINFO(un), 0);
6613 		un->un_pm_idle_timeid = NULL;
6614 	} else {
6615 		un->un_pm_idle_timeid =
6616 		    timeout(sd_pm_idletimeout_handler, un,
6617 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
6618 	}
6619 	mutex_exit(&un->un_pm_mutex);
6620 	mutex_exit(SD_MUTEX(un));
6621 }
6622 
6623 
6624 /*
6625  *    Function: sd_pm_timeout_handler
6626  *
6627  * Description: Callback to tell framework we are idle.
6628  *
6629  *     Context: timeout(9f) thread context.
6630  */
6631 
6632 static void
6633 sd_pm_timeout_handler(void *arg)
6634 {
6635 	struct sd_lun *un = arg;
6636 
6637 	(void) pm_idle_component(SD_DEVINFO(un), 0);
6638 	mutex_enter(&un->un_pm_mutex);
6639 	un->un_pm_timeid = NULL;
6640 	mutex_exit(&un->un_pm_mutex);
6641 }
6642 
6643 
6644 /*
6645  *    Function: sdpower
6646  *
6647  * Description: PM entry point.
6648  *
6649  * Return Code: DDI_SUCCESS
6650  *		DDI_FAILURE
6651  *
6652  *     Context: Kernel thread context
6653  */
6654 
6655 static int
6656 sdpower(dev_info_t *devi, int component, int level)
6657 {
6658 	struct sd_lun	*un;
6659 	int		instance;
6660 	int		rval = DDI_SUCCESS;
6661 	uint_t		i, log_page_size, maxcycles, ncycles;
6662 	uchar_t		*log_page_data;
6663 	int		log_sense_page;
6664 	int		medium_present;
6665 	time_t		intvlp;
6666 	struct pm_trans_data	sd_pm_tran_data;
6667 	uchar_t		save_state = SD_STATE_NORMAL;
6668 	int		sval;
6669 	uchar_t		state_before_pm;
6670 	int		got_semaphore_here;
6671 	sd_ssc_t	*ssc;
6672 	int	last_power_level = SD_SPINDLE_UNINIT;
6673 
6674 	instance = ddi_get_instance(devi);
6675 
6676 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
6677 	    !SD_PM_IS_LEVEL_VALID(un, level) || component != 0) {
6678 		return (DDI_FAILURE);
6679 	}
6680 
6681 	ssc = sd_ssc_init(un);
6682 
6683 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
6684 
6685 	/*
6686 	 * Must synchronize power down with close.
6687 	 * Attempt to decrement/acquire the open/close semaphore,
6688 	 * but do NOT wait on it. If it's not greater than zero,
6689 	 * ie. it can't be decremented without waiting, then
6690 	 * someone else, either open or close, already has it
6691 	 * and the try returns 0. Use that knowledge here to determine
6692 	 * if it's OK to change the device power level.
6693 	 * Also, only increment it on exit if it was decremented, ie. gotten,
6694 	 * here.
6695 	 */
6696 	got_semaphore_here = sema_tryp(&un->un_semoclose);
6697 
6698 	mutex_enter(SD_MUTEX(un));
6699 
6700 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
6701 	    un->un_ncmds_in_driver);
6702 
6703 	/*
6704 	 * If un_ncmds_in_driver is non-zero it indicates commands are
6705 	 * already being processed in the driver, or if the semaphore was
6706 	 * not gotten here it indicates an open or close is being processed.
6707 	 * At the same time somebody is requesting to go to a lower power
6708 	 * that can't perform I/O, which can't happen, therefore we need to
6709 	 * return failure.
6710 	 */
6711 	if ((!SD_PM_IS_IO_CAPABLE(un, level)) &&
6712 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
6713 		mutex_exit(SD_MUTEX(un));
6714 
6715 		if (got_semaphore_here != 0) {
6716 			sema_v(&un->un_semoclose);
6717 		}
6718 		SD_TRACE(SD_LOG_IO_PM, un,
6719 		    "sdpower: exit, device has queued cmds.\n");
6720 
6721 		goto sdpower_failed;
6722 	}
6723 
6724 	/*
6725 	 * if it is OFFLINE that means the disk is completely dead
6726 	 * in our case we have to put the disk in on or off by sending commands
6727 	 * Of course that will fail anyway so return back here.
6728 	 *
6729 	 * Power changes to a device that's OFFLINE or SUSPENDED
6730 	 * are not allowed.
6731 	 */
6732 	if ((un->un_state == SD_STATE_OFFLINE) ||
6733 	    (un->un_state == SD_STATE_SUSPENDED)) {
6734 		mutex_exit(SD_MUTEX(un));
6735 
6736 		if (got_semaphore_here != 0) {
6737 			sema_v(&un->un_semoclose);
6738 		}
6739 		SD_TRACE(SD_LOG_IO_PM, un,
6740 		    "sdpower: exit, device is off-line.\n");
6741 
6742 		goto sdpower_failed;
6743 	}
6744 
6745 	/*
6746 	 * Change the device's state to indicate it's power level
6747 	 * is being changed. Do this to prevent a power off in the
6748 	 * middle of commands, which is especially bad on devices
6749 	 * that are really powered off instead of just spun down.
6750 	 */
6751 	state_before_pm = un->un_state;
6752 	un->un_state = SD_STATE_PM_CHANGING;
6753 
6754 	mutex_exit(SD_MUTEX(un));
6755 
6756 	/*
6757 	 * If log sense command is not supported, bypass the
6758 	 * following checking, otherwise, check the log sense
6759 	 * information for this device.
6760 	 */
6761 	if (SD_PM_STOP_MOTOR_NEEDED(un, level) &&
6762 	    un->un_f_log_sense_supported) {
6763 		/*
6764 		 * Get the log sense information to understand whether the
6765 		 * the powercycle counts have gone beyond the threshhold.
6766 		 */
6767 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6768 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6769 
6770 		mutex_enter(SD_MUTEX(un));
6771 		log_sense_page = un->un_start_stop_cycle_page;
6772 		mutex_exit(SD_MUTEX(un));
6773 
6774 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6775 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
6776 
6777 		if (rval != 0) {
6778 			if (rval == EIO)
6779 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6780 			else
6781 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6782 		}
6783 
6784 #ifdef	SDDEBUG
6785 		if (sd_force_pm_supported) {
6786 			/* Force a successful result */
6787 			rval = 0;
6788 		}
6789 #endif
6790 		if (rval != 0) {
6791 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
6792 			    "Log Sense Failed\n");
6793 
6794 			kmem_free(log_page_data, log_page_size);
6795 			/* Cannot support power management on those drives */
6796 
6797 			if (got_semaphore_here != 0) {
6798 				sema_v(&un->un_semoclose);
6799 			}
6800 			/*
6801 			 * On exit put the state back to it's original value
6802 			 * and broadcast to anyone waiting for the power
6803 			 * change completion.
6804 			 */
6805 			mutex_enter(SD_MUTEX(un));
6806 			un->un_state = state_before_pm;
6807 			cv_broadcast(&un->un_suspend_cv);
6808 			mutex_exit(SD_MUTEX(un));
6809 			SD_TRACE(SD_LOG_IO_PM, un,
6810 			    "sdpower: exit, Log Sense Failed.\n");
6811 
6812 			goto sdpower_failed;
6813 		}
6814 
6815 		/*
6816 		 * From the page data - Convert the essential information to
6817 		 * pm_trans_data
6818 		 */
6819 		maxcycles =
6820 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
6821 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
6822 
6823 		ncycles =
6824 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6825 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6826 
6827 		if (un->un_f_pm_log_sense_smart) {
6828 			sd_pm_tran_data.un.smart_count.allowed = maxcycles;
6829 			sd_pm_tran_data.un.smart_count.consumed = ncycles;
6830 			sd_pm_tran_data.un.smart_count.flag = 0;
6831 			sd_pm_tran_data.format = DC_SMART_FORMAT;
6832 		} else {
6833 			sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6834 			sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6835 			for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6836 				sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6837 				    log_page_data[8+i];
6838 			}
6839 			sd_pm_tran_data.un.scsi_cycles.flag = 0;
6840 			sd_pm_tran_data.format = DC_SCSI_FORMAT;
6841 		}
6842 
6843 		kmem_free(log_page_data, log_page_size);
6844 
6845 		/*
6846 		 * Call pm_trans_check routine to get the Ok from
6847 		 * the global policy
6848 		 */
6849 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6850 #ifdef	SDDEBUG
6851 		if (sd_force_pm_supported) {
6852 			/* Force a successful result */
6853 			rval = 1;
6854 		}
6855 #endif
6856 		switch (rval) {
6857 		case 0:
6858 			/*
6859 			 * Not Ok to Power cycle or error in parameters passed
6860 			 * Would have given the advised time to consider power
6861 			 * cycle. Based on the new intvlp parameter we are
6862 			 * supposed to pretend we are busy so that pm framework
6863 			 * will never call our power entry point. Because of
6864 			 * that install a timeout handler and wait for the
6865 			 * recommended time to elapse so that power management
6866 			 * can be effective again.
6867 			 *
6868 			 * To effect this behavior, call pm_busy_component to
6869 			 * indicate to the framework this device is busy.
6870 			 * By not adjusting un_pm_count the rest of PM in
6871 			 * the driver will function normally, and independent
6872 			 * of this but because the framework is told the device
6873 			 * is busy it won't attempt powering down until it gets
6874 			 * a matching idle. The timeout handler sends this.
6875 			 * Note: sd_pm_entry can't be called here to do this
6876 			 * because sdpower may have been called as a result
6877 			 * of a call to pm_raise_power from within sd_pm_entry.
6878 			 *
6879 			 * If a timeout handler is already active then
6880 			 * don't install another.
6881 			 */
6882 			mutex_enter(&un->un_pm_mutex);
6883 			if (un->un_pm_timeid == NULL) {
6884 				un->un_pm_timeid =
6885 				    timeout(sd_pm_timeout_handler,
6886 				    un, intvlp * drv_usectohz(1000000));
6887 				mutex_exit(&un->un_pm_mutex);
6888 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6889 			} else {
6890 				mutex_exit(&un->un_pm_mutex);
6891 			}
6892 			if (got_semaphore_here != 0) {
6893 				sema_v(&un->un_semoclose);
6894 			}
6895 			/*
6896 			 * On exit put the state back to it's original value
6897 			 * and broadcast to anyone waiting for the power
6898 			 * change completion.
6899 			 */
6900 			mutex_enter(SD_MUTEX(un));
6901 			un->un_state = state_before_pm;
6902 			cv_broadcast(&un->un_suspend_cv);
6903 			mutex_exit(SD_MUTEX(un));
6904 
6905 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6906 			    "trans check Failed, not ok to power cycle.\n");
6907 
6908 			goto sdpower_failed;
6909 		case -1:
6910 			if (got_semaphore_here != 0) {
6911 				sema_v(&un->un_semoclose);
6912 			}
6913 			/*
6914 			 * On exit put the state back to it's original value
6915 			 * and broadcast to anyone waiting for the power
6916 			 * change completion.
6917 			 */
6918 			mutex_enter(SD_MUTEX(un));
6919 			un->un_state = state_before_pm;
6920 			cv_broadcast(&un->un_suspend_cv);
6921 			mutex_exit(SD_MUTEX(un));
6922 			SD_TRACE(SD_LOG_IO_PM, un,
6923 			    "sdpower: exit, trans check command Failed.\n");
6924 
6925 			goto sdpower_failed;
6926 		}
6927 	}
6928 
6929 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6930 		/*
6931 		 * Save the last state... if the STOP FAILS we need it
6932 		 * for restoring
6933 		 */
6934 		mutex_enter(SD_MUTEX(un));
6935 		save_state = un->un_last_state;
6936 		last_power_level = un->un_power_level;
6937 		/*
6938 		 * There must not be any cmds. getting processed
6939 		 * in the driver when we get here. Power to the
6940 		 * device is potentially going off.
6941 		 */
6942 		ASSERT(un->un_ncmds_in_driver == 0);
6943 		mutex_exit(SD_MUTEX(un));
6944 
6945 		/*
6946 		 * For now PM suspend the device completely before spindle is
6947 		 * turned off
6948 		 */
6949 		if ((rval = sd_pm_state_change(un, level, SD_PM_STATE_CHANGE))
6950 		    == DDI_FAILURE) {
6951 			if (got_semaphore_here != 0) {
6952 				sema_v(&un->un_semoclose);
6953 			}
6954 			/*
6955 			 * On exit put the state back to it's original value
6956 			 * and broadcast to anyone waiting for the power
6957 			 * change completion.
6958 			 */
6959 			mutex_enter(SD_MUTEX(un));
6960 			un->un_state = state_before_pm;
6961 			un->un_power_level = last_power_level;
6962 			cv_broadcast(&un->un_suspend_cv);
6963 			mutex_exit(SD_MUTEX(un));
6964 			SD_TRACE(SD_LOG_IO_PM, un,
6965 			    "sdpower: exit, PM suspend Failed.\n");
6966 
6967 			goto sdpower_failed;
6968 		}
6969 	}
6970 
6971 	/*
6972 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6973 	 * close, or strategy. Dump no long uses this routine, it uses it's
6974 	 * own code so it can be done in polled mode.
6975 	 */
6976 
6977 	medium_present = TRUE;
6978 
6979 	/*
6980 	 * When powering up, issue a TUR in case the device is at unit
6981 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6982 	 * a deadlock on un_pm_busy_cv will occur.
6983 	 */
6984 	if (SD_PM_IS_IO_CAPABLE(un, level)) {
6985 		sval = sd_send_scsi_TEST_UNIT_READY(ssc,
6986 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6987 		if (sval != 0)
6988 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6989 	}
6990 
6991 	if (un->un_f_power_condition_supported) {
6992 		char *pm_condition_name[] = {"STOPPED", "STANDBY",
6993 		    "IDLE", "ACTIVE"};
6994 		SD_TRACE(SD_LOG_IO_PM, un,
6995 		    "sdpower: sending \'%s\' power condition",
6996 		    pm_condition_name[level]);
6997 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
6998 		    sd_pl2pc[level], SD_PATH_DIRECT);
6999 	} else {
7000 		SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
7001 		    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
7002 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
7003 		    ((level == SD_SPINDLE_ON) ? SD_TARGET_START :
7004 		    SD_TARGET_STOP), SD_PATH_DIRECT);
7005 	}
7006 	if (sval != 0) {
7007 		if (sval == EIO)
7008 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
7009 		else
7010 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7011 	}
7012 
7013 	/* Command failed, check for media present. */
7014 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
7015 		medium_present = FALSE;
7016 	}
7017 
7018 	/*
7019 	 * The conditions of interest here are:
7020 	 *   if a spindle off with media present fails,
7021 	 *	then restore the state and return an error.
7022 	 *   else if a spindle on fails,
7023 	 *	then return an error (there's no state to restore).
7024 	 * In all other cases we setup for the new state
7025 	 * and return success.
7026 	 */
7027 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
7028 		if ((medium_present == TRUE) && (sval != 0)) {
7029 			/* The stop command from above failed */
7030 			rval = DDI_FAILURE;
7031 			/*
7032 			 * The stop command failed, and we have media
7033 			 * present. Put the level back by calling the
7034 			 * sd_pm_resume() and set the state back to
7035 			 * it's previous value.
7036 			 */
7037 			(void) sd_pm_state_change(un, last_power_level,
7038 			    SD_PM_STATE_ROLLBACK);
7039 			mutex_enter(SD_MUTEX(un));
7040 			un->un_last_state = save_state;
7041 			mutex_exit(SD_MUTEX(un));
7042 		} else if (un->un_f_monitor_media_state) {
7043 			/*
7044 			 * The stop command from above succeeded.
7045 			 * Terminate watch thread in case of removable media
7046 			 * devices going into low power state. This is as per
7047 			 * the requirements of pm framework, otherwise commands
7048 			 * will be generated for the device (through watch
7049 			 * thread), even when the device is in low power state.
7050 			 */
7051 			mutex_enter(SD_MUTEX(un));
7052 			un->un_f_watcht_stopped = FALSE;
7053 			if (un->un_swr_token != NULL) {
7054 				opaque_t temp_token = un->un_swr_token;
7055 				un->un_f_watcht_stopped = TRUE;
7056 				un->un_swr_token = NULL;
7057 				mutex_exit(SD_MUTEX(un));
7058 				(void) scsi_watch_request_terminate(temp_token,
7059 				    SCSI_WATCH_TERMINATE_ALL_WAIT);
7060 			} else {
7061 				mutex_exit(SD_MUTEX(un));
7062 			}
7063 		}
7064 	} else {
7065 		/*
7066 		 * The level requested is I/O capable.
7067 		 * Legacy behavior: return success on a failed spinup
7068 		 * if there is no media in the drive.
7069 		 * Do this by looking at medium_present here.
7070 		 */
7071 		if ((sval != 0) && medium_present) {
7072 			/* The start command from above failed */
7073 			rval = DDI_FAILURE;
7074 		} else {
7075 			/*
7076 			 * The start command from above succeeded
7077 			 * PM resume the devices now that we have
7078 			 * started the disks
7079 			 */
7080 			(void) sd_pm_state_change(un, level,
7081 			    SD_PM_STATE_CHANGE);
7082 
7083 			/*
7084 			 * Resume the watch thread since it was suspended
7085 			 * when the device went into low power mode.
7086 			 */
7087 			if (un->un_f_monitor_media_state) {
7088 				mutex_enter(SD_MUTEX(un));
7089 				if (un->un_f_watcht_stopped == TRUE) {
7090 					opaque_t temp_token;
7091 
7092 					un->un_f_watcht_stopped = FALSE;
7093 					mutex_exit(SD_MUTEX(un));
7094 					temp_token =
7095 					    sd_watch_request_submit(un);
7096 					mutex_enter(SD_MUTEX(un));
7097 					un->un_swr_token = temp_token;
7098 				}
7099 				mutex_exit(SD_MUTEX(un));
7100 			}
7101 		}
7102 	}
7103 
7104 	if (got_semaphore_here != 0) {
7105 		sema_v(&un->un_semoclose);
7106 	}
7107 	/*
7108 	 * On exit put the state back to it's original value
7109 	 * and broadcast to anyone waiting for the power
7110 	 * change completion.
7111 	 */
7112 	mutex_enter(SD_MUTEX(un));
7113 	un->un_state = state_before_pm;
7114 	cv_broadcast(&un->un_suspend_cv);
7115 	mutex_exit(SD_MUTEX(un));
7116 
7117 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
7118 
7119 	sd_ssc_fini(ssc);
7120 	return (rval);
7121 
7122 sdpower_failed:
7123 
7124 	sd_ssc_fini(ssc);
7125 	return (DDI_FAILURE);
7126 }
7127 
7128 
7129 
7130 /*
7131  *    Function: sdattach
7132  *
7133  * Description: Driver's attach(9e) entry point function.
7134  *
7135  *   Arguments: devi - opaque device info handle
7136  *		cmd  - attach  type
7137  *
7138  * Return Code: DDI_SUCCESS
7139  *		DDI_FAILURE
7140  *
7141  *     Context: Kernel thread context
7142  */
7143 
7144 static int
7145 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
7146 {
7147 	switch (cmd) {
7148 	case DDI_ATTACH:
7149 		return (sd_unit_attach(devi));
7150 	case DDI_RESUME:
7151 		return (sd_ddi_resume(devi));
7152 	default:
7153 		break;
7154 	}
7155 	return (DDI_FAILURE);
7156 }
7157 
7158 
7159 /*
7160  *    Function: sddetach
7161  *
7162  * Description: Driver's detach(9E) entry point function.
7163  *
7164  *   Arguments: devi - opaque device info handle
7165  *		cmd  - detach  type
7166  *
7167  * Return Code: DDI_SUCCESS
7168  *		DDI_FAILURE
7169  *
7170  *     Context: Kernel thread context
7171  */
7172 
7173 static int
7174 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
7175 {
7176 	switch (cmd) {
7177 	case DDI_DETACH:
7178 		return (sd_unit_detach(devi));
7179 	case DDI_SUSPEND:
7180 		return (sd_ddi_suspend(devi));
7181 	default:
7182 		break;
7183 	}
7184 	return (DDI_FAILURE);
7185 }
7186 
7187 
7188 /*
7189  *     Function: sd_sync_with_callback
7190  *
7191  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
7192  *		 state while the callback routine is active.
7193  *
7194  *    Arguments: un: softstate structure for the instance
7195  *
7196  *	Context: Kernel thread context
7197  */
7198 
7199 static void
7200 sd_sync_with_callback(struct sd_lun *un)
7201 {
7202 	ASSERT(un != NULL);
7203 
7204 	mutex_enter(SD_MUTEX(un));
7205 
7206 	ASSERT(un->un_in_callback >= 0);
7207 
7208 	while (un->un_in_callback > 0) {
7209 		mutex_exit(SD_MUTEX(un));
7210 		delay(2);
7211 		mutex_enter(SD_MUTEX(un));
7212 	}
7213 
7214 	mutex_exit(SD_MUTEX(un));
7215 }
7216 
7217 /*
7218  *    Function: sd_unit_attach
7219  *
7220  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
7221  *		the soft state structure for the device and performs
7222  *		all necessary structure and device initializations.
7223  *
7224  *   Arguments: devi: the system's dev_info_t for the device.
7225  *
7226  * Return Code: DDI_SUCCESS if attach is successful.
7227  *		DDI_FAILURE if any part of the attach fails.
7228  *
7229  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
7230  *		Kernel thread context only.  Can sleep.
7231  */
7232 
7233 static int
7234 sd_unit_attach(dev_info_t *devi)
7235 {
7236 	struct	scsi_device	*devp;
7237 	struct	sd_lun		*un;
7238 	char			*variantp;
7239 	char			name_str[48];
7240 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
7241 	int	instance;
7242 	int	rval;
7243 	int	wc_enabled;
7244 	int	wc_changeable;
7245 	int	tgt;
7246 	uint64_t	capacity;
7247 	uint_t		lbasize = 0;
7248 	dev_info_t	*pdip = ddi_get_parent(devi);
7249 	int		offbyone = 0;
7250 	int		geom_label_valid = 0;
7251 	sd_ssc_t	*ssc;
7252 	int		status;
7253 	struct sd_fm_internal	*sfip = NULL;
7254 	int		max_xfer_size;
7255 
7256 	/*
7257 	 * Retrieve the target driver's private data area. This was set
7258 	 * up by the HBA.
7259 	 */
7260 	devp = ddi_get_driver_private(devi);
7261 
7262 	/*
7263 	 * Retrieve the target ID of the device.
7264 	 */
7265 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7266 	    SCSI_ADDR_PROP_TARGET, -1);
7267 
7268 	/*
7269 	 * Since we have no idea what state things were left in by the last
7270 	 * user of the device, set up some 'default' settings, ie. turn 'em
7271 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
7272 	 * Do this before the scsi_probe, which sends an inquiry.
7273 	 * This is a fix for bug (4430280).
7274 	 * Of special importance is wide-xfer. The drive could have been left
7275 	 * in wide transfer mode by the last driver to communicate with it,
7276 	 * this includes us. If that's the case, and if the following is not
7277 	 * setup properly or we don't re-negotiate with the drive prior to
7278 	 * transferring data to/from the drive, it causes bus parity errors,
7279 	 * data overruns, and unexpected interrupts. This first occurred when
7280 	 * the fix for bug (4378686) was made.
7281 	 */
7282 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
7283 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
7284 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
7285 
7286 	/*
7287 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
7288 	 * on a target. Setting it per lun instance actually sets the
7289 	 * capability of this target, which affects those luns already
7290 	 * attached on the same target. So during attach, we can only disable
7291 	 * this capability only when no other lun has been attached on this
7292 	 * target. By doing this, we assume a target has the same tagged-qing
7293 	 * capability for every lun. The condition can be removed when HBA
7294 	 * is changed to support per lun based tagged-qing capability.
7295 	 */
7296 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7297 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
7298 	}
7299 
7300 	/*
7301 	 * Use scsi_probe() to issue an INQUIRY command to the device.
7302 	 * This call will allocate and fill in the scsi_inquiry structure
7303 	 * and point the sd_inq member of the scsi_device structure to it.
7304 	 * If the attach succeeds, then this memory will not be de-allocated
7305 	 * (via scsi_unprobe()) until the instance is detached.
7306 	 */
7307 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
7308 		goto probe_failed;
7309 	}
7310 
7311 	/*
7312 	 * Check the device type as specified in the inquiry data and
7313 	 * claim it if it is of a type that we support.
7314 	 */
7315 	switch (devp->sd_inq->inq_dtype) {
7316 	case DTYPE_DIRECT:
7317 		break;
7318 	case DTYPE_RODIRECT:
7319 		break;
7320 	case DTYPE_OPTICAL:
7321 		break;
7322 	case DTYPE_NOTPRESENT:
7323 	default:
7324 		/* Unsupported device type; fail the attach. */
7325 		goto probe_failed;
7326 	}
7327 
7328 	/*
7329 	 * Allocate the soft state structure for this unit.
7330 	 *
7331 	 * We rely upon this memory being set to all zeroes by
7332 	 * ddi_soft_state_zalloc().  We assume that any member of the
7333 	 * soft state structure that is not explicitly initialized by
7334 	 * this routine will have a value of zero.
7335 	 */
7336 	instance = ddi_get_instance(devp->sd_dev);
7337 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
7338 		goto probe_failed;
7339 	}
7340 
7341 	/*
7342 	 * Retrieve a pointer to the newly-allocated soft state.
7343 	 *
7344 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
7345 	 * was successful, unless something has gone horribly wrong and the
7346 	 * ddi's soft state internals are corrupt (in which case it is
7347 	 * probably better to halt here than just fail the attach....)
7348 	 */
7349 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
7350 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
7351 		    instance);
7352 		/*NOTREACHED*/
7353 	}
7354 
7355 	/*
7356 	 * Link the back ptr of the driver soft state to the scsi_device
7357 	 * struct for this lun.
7358 	 * Save a pointer to the softstate in the driver-private area of
7359 	 * the scsi_device struct.
7360 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
7361 	 * we first set un->un_sd below.
7362 	 */
7363 	un->un_sd = devp;
7364 	devp->sd_private = (opaque_t)un;
7365 
7366 	/*
7367 	 * The following must be after devp is stored in the soft state struct.
7368 	 */
7369 #ifdef SDDEBUG
7370 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7371 	    "%s_unit_attach: un:0x%p instance:%d\n",
7372 	    ddi_driver_name(devi), un, instance);
7373 #endif
7374 
7375 	/*
7376 	 * Set up the device type and node type (for the minor nodes).
7377 	 * By default we assume that the device can at least support the
7378 	 * Common Command Set. Call it a CD-ROM if it reports itself
7379 	 * as a RODIRECT device.
7380 	 */
7381 	switch (devp->sd_inq->inq_dtype) {
7382 	case DTYPE_RODIRECT:
7383 		un->un_node_type = DDI_NT_CD_CHAN;
7384 		un->un_ctype	 = CTYPE_CDROM;
7385 		break;
7386 	case DTYPE_OPTICAL:
7387 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7388 		un->un_ctype	 = CTYPE_ROD;
7389 		break;
7390 	default:
7391 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7392 		un->un_ctype	 = CTYPE_CCS;
7393 		break;
7394 	}
7395 
7396 	/*
7397 	 * Try to read the interconnect type from the HBA.
7398 	 *
7399 	 * Note: This driver is currently compiled as two binaries, a parallel
7400 	 * scsi version (sd) and a fibre channel version (ssd). All functional
7401 	 * differences are determined at compile time. In the future a single
7402 	 * binary will be provided and the interconnect type will be used to
7403 	 * differentiate between fibre and parallel scsi behaviors. At that time
7404 	 * it will be necessary for all fibre channel HBAs to support this
7405 	 * property.
7406 	 *
7407 	 * set un_f_is_fiber to TRUE ( default fiber )
7408 	 */
7409 	un->un_f_is_fibre = TRUE;
7410 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
7411 	case INTERCONNECT_SSA:
7412 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
7413 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7414 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
7415 		break;
7416 	case INTERCONNECT_PARALLEL:
7417 		un->un_f_is_fibre = FALSE;
7418 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7419 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7420 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
7421 		break;
7422 	case INTERCONNECT_SAS:
7423 		un->un_f_is_fibre = FALSE;
7424 		un->un_interconnect_type = SD_INTERCONNECT_SAS;
7425 		un->un_node_type = DDI_NT_BLOCK_SAS;
7426 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7427 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SAS\n", un);
7428 		break;
7429 	case INTERCONNECT_SATA:
7430 		un->un_f_is_fibre = FALSE;
7431 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
7432 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7433 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
7434 		break;
7435 	case INTERCONNECT_FIBRE:
7436 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7437 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7438 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7439 		break;
7440 	case INTERCONNECT_FABRIC:
7441 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7442 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7443 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7444 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7445 		break;
7446 	default:
7447 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7448 		/*
7449 		 * The HBA does not support the "interconnect-type" property
7450 		 * (or did not provide a recognized type).
7451 		 *
7452 		 * Note: This will be obsoleted when a single fibre channel
7453 		 * and parallel scsi driver is delivered. In the meantime the
7454 		 * interconnect type will be set to the platform default.If that
7455 		 * type is not parallel SCSI, it means that we should be
7456 		 * assuming "ssd" semantics. However, here this also means that
7457 		 * the FC HBA is not supporting the "interconnect-type" property
7458 		 * like we expect it to, so log this occurrence.
7459 		 */
7460 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7461 		if (!SD_IS_PARALLEL_SCSI(un)) {
7462 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7463 			    "sd_unit_attach: un:0x%p Assuming "
7464 			    "INTERCONNECT_FIBRE\n", un);
7465 		} else {
7466 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7467 			    "sd_unit_attach: un:0x%p Assuming "
7468 			    "INTERCONNECT_PARALLEL\n", un);
7469 			un->un_f_is_fibre = FALSE;
7470 		}
7471 #else
7472 		/*
7473 		 * Note: This source will be implemented when a single fibre
7474 		 * channel and parallel scsi driver is delivered. The default
7475 		 * will be to assume that if a device does not support the
7476 		 * "interconnect-type" property it is a parallel SCSI HBA and
7477 		 * we will set the interconnect type for parallel scsi.
7478 		 */
7479 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7480 		un->un_f_is_fibre = FALSE;
7481 #endif
7482 		break;
7483 	}
7484 
7485 	if (un->un_f_is_fibre == TRUE) {
7486 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7487 		    SCSI_VERSION_3) {
7488 			switch (un->un_interconnect_type) {
7489 			case SD_INTERCONNECT_FIBRE:
7490 			case SD_INTERCONNECT_SSA:
7491 				un->un_node_type = DDI_NT_BLOCK_WWN;
7492 				break;
7493 			default:
7494 				break;
7495 			}
7496 		}
7497 	}
7498 
7499 	/*
7500 	 * Initialize the Request Sense command for the target
7501 	 */
7502 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7503 		goto alloc_rqs_failed;
7504 	}
7505 
7506 	/*
7507 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7508 	 * with separate binary for sd and ssd.
7509 	 *
7510 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7511 	 * The hardcoded values will go away when Sparc uses 1 binary
7512 	 * for sd and ssd.  This hardcoded values need to match
7513 	 * SD_RETRY_COUNT in sddef.h
7514 	 * The value used is base on interconnect type.
7515 	 * fibre = 3, parallel = 5
7516 	 */
7517 #if defined(__x86)
7518 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7519 #else
7520 	un->un_retry_count = SD_RETRY_COUNT;
7521 #endif
7522 
7523 	/*
7524 	 * Set the per disk retry count to the default number of retries
7525 	 * for disks and CDROMs. This value can be overridden by the
7526 	 * disk property list or an entry in sd.conf.
7527 	 */
7528 	un->un_notready_retry_count =
7529 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7530 	    : DISK_NOT_READY_RETRY_COUNT(un);
7531 
7532 	/*
7533 	 * Set the busy retry count to the default value of un_retry_count.
7534 	 * This can be overridden by entries in sd.conf or the device
7535 	 * config table.
7536 	 */
7537 	un->un_busy_retry_count = un->un_retry_count;
7538 
7539 	/*
7540 	 * Init the reset threshold for retries.  This number determines
7541 	 * how many retries must be performed before a reset can be issued
7542 	 * (for certain error conditions). This can be overridden by entries
7543 	 * in sd.conf or the device config table.
7544 	 */
7545 	un->un_reset_retry_count = (un->un_retry_count / 2);
7546 
7547 	/*
7548 	 * Set the victim_retry_count to the default un_retry_count
7549 	 */
7550 	un->un_victim_retry_count = (2 * un->un_retry_count);
7551 
7552 	/*
7553 	 * Set the reservation release timeout to the default value of
7554 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7555 	 * device config table.
7556 	 */
7557 	un->un_reserve_release_time = 5;
7558 
7559 	/*
7560 	 * Set up the default maximum transfer size. Note that this may
7561 	 * get updated later in the attach, when setting up default wide
7562 	 * operations for disks.
7563 	 */
7564 #if defined(__x86)
7565 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7566 	un->un_partial_dma_supported = 1;
7567 #else
7568 	un->un_max_xfer_size = (uint_t)maxphys;
7569 #endif
7570 
7571 	/*
7572 	 * Get "allow bus device reset" property (defaults to "enabled" if
7573 	 * the property was not defined). This is to disable bus resets for
7574 	 * certain kinds of error recovery. Note: In the future when a run-time
7575 	 * fibre check is available the soft state flag should default to
7576 	 * enabled.
7577 	 */
7578 	if (un->un_f_is_fibre == TRUE) {
7579 		un->un_f_allow_bus_device_reset = TRUE;
7580 	} else {
7581 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7582 		    "allow-bus-device-reset", 1) != 0) {
7583 			un->un_f_allow_bus_device_reset = TRUE;
7584 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7585 			    "sd_unit_attach: un:0x%p Bus device reset "
7586 			    "enabled\n", un);
7587 		} else {
7588 			un->un_f_allow_bus_device_reset = FALSE;
7589 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7590 			    "sd_unit_attach: un:0x%p Bus device reset "
7591 			    "disabled\n", un);
7592 		}
7593 	}
7594 
7595 	/*
7596 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7597 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7598 	 *
7599 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7600 	 * property. The new "variant" property with a value of "atapi" has been
7601 	 * introduced so that future 'variants' of standard SCSI behavior (like
7602 	 * atapi) could be specified by the underlying HBA drivers by supplying
7603 	 * a new value for the "variant" property, instead of having to define a
7604 	 * new property.
7605 	 */
7606 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7607 		un->un_f_cfg_is_atapi = TRUE;
7608 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7609 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7610 	}
7611 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7612 	    &variantp) == DDI_PROP_SUCCESS) {
7613 		if (strcmp(variantp, "atapi") == 0) {
7614 			un->un_f_cfg_is_atapi = TRUE;
7615 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7616 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7617 		}
7618 		ddi_prop_free(variantp);
7619 	}
7620 
7621 	un->un_cmd_timeout	= SD_IO_TIME;
7622 
7623 	un->un_busy_timeout  = SD_BSY_TIMEOUT;
7624 
7625 	/* Info on current states, statuses, etc. (Updated frequently) */
7626 	un->un_state		= SD_STATE_NORMAL;
7627 	un->un_last_state	= SD_STATE_NORMAL;
7628 
7629 	/* Control & status info for command throttling */
7630 	un->un_throttle		= sd_max_throttle;
7631 	un->un_saved_throttle	= sd_max_throttle;
7632 	un->un_min_throttle	= sd_min_throttle;
7633 
7634 	if (un->un_f_is_fibre == TRUE) {
7635 		un->un_f_use_adaptive_throttle = TRUE;
7636 	} else {
7637 		un->un_f_use_adaptive_throttle = FALSE;
7638 	}
7639 
7640 	/* Removable media support. */
7641 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7642 	un->un_mediastate		= DKIO_NONE;
7643 	un->un_specified_mediastate	= DKIO_NONE;
7644 
7645 	/* CVs for suspend/resume (PM or DR) */
7646 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7647 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7648 
7649 	/* Power management support. */
7650 	un->un_power_level = SD_SPINDLE_UNINIT;
7651 
7652 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
7653 	un->un_f_wcc_inprog = 0;
7654 
7655 	/*
7656 	 * The open/close semaphore is used to serialize threads executing
7657 	 * in the driver's open & close entry point routines for a given
7658 	 * instance.
7659 	 */
7660 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
7661 
7662 	/*
7663 	 * The conf file entry and softstate variable is a forceful override,
7664 	 * meaning a non-zero value must be entered to change the default.
7665 	 */
7666 	un->un_f_disksort_disabled = FALSE;
7667 	un->un_f_rmw_type = SD_RMW_TYPE_DEFAULT;
7668 	un->un_f_enable_rmw = FALSE;
7669 
7670 	/*
7671 	 * GET EVENT STATUS NOTIFICATION media polling enabled by default, but
7672 	 * can be overridden via [s]sd-config-list "mmc-gesn-polling" property.
7673 	 */
7674 	un->un_f_mmc_gesn_polling = TRUE;
7675 
7676 	/*
7677 	 * physical sector size defaults to DEV_BSIZE currently. We can
7678 	 * override this value via the driver configuration file so we must
7679 	 * set it before calling sd_read_unit_properties().
7680 	 */
7681 	un->un_phy_blocksize = DEV_BSIZE;
7682 
7683 	/*
7684 	 * Retrieve the properties from the static driver table or the driver
7685 	 * configuration file (.conf) for this unit and update the soft state
7686 	 * for the device as needed for the indicated properties.
7687 	 * Note: the property configuration needs to occur here as some of the
7688 	 * following routines may have dependencies on soft state flags set
7689 	 * as part of the driver property configuration.
7690 	 */
7691 	sd_read_unit_properties(un);
7692 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7693 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
7694 
7695 	/*
7696 	 * Only if a device has "hotpluggable" property, it is
7697 	 * treated as hotpluggable device. Otherwise, it is
7698 	 * regarded as non-hotpluggable one.
7699 	 */
7700 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
7701 	    -1) != -1) {
7702 		un->un_f_is_hotpluggable = TRUE;
7703 	}
7704 
7705 	/*
7706 	 * set unit's attributes(flags) according to "hotpluggable" and
7707 	 * RMB bit in INQUIRY data.
7708 	 */
7709 	sd_set_unit_attributes(un, devi);
7710 
7711 	/*
7712 	 * By default, we mark the capacity, lbasize, and geometry
7713 	 * as invalid. Only if we successfully read a valid capacity
7714 	 * will we update the un_blockcount and un_tgt_blocksize with the
7715 	 * valid values (the geometry will be validated later).
7716 	 */
7717 	un->un_f_blockcount_is_valid	= FALSE;
7718 	un->un_f_tgt_blocksize_is_valid	= FALSE;
7719 
7720 	/*
7721 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
7722 	 * otherwise.
7723 	 */
7724 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
7725 	un->un_blockcount = 0;
7726 
7727 	/*
7728 	 * Set up the per-instance info needed to determine the correct
7729 	 * CDBs and other info for issuing commands to the target.
7730 	 */
7731 	sd_init_cdb_limits(un);
7732 
7733 	/*
7734 	 * Set up the IO chains to use, based upon the target type.
7735 	 */
7736 	if (un->un_f_non_devbsize_supported) {
7737 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7738 	} else {
7739 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7740 	}
7741 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7742 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
7743 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
7744 
7745 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
7746 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
7747 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
7748 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
7749 
7750 
7751 	if (ISCD(un)) {
7752 		un->un_additional_codes = sd_additional_codes;
7753 	} else {
7754 		un->un_additional_codes = NULL;
7755 	}
7756 
7757 	/*
7758 	 * Create the kstats here so they can be available for attach-time
7759 	 * routines that send commands to the unit (either polled or via
7760 	 * sd_send_scsi_cmd).
7761 	 *
7762 	 * Note: This is a critical sequence that needs to be maintained:
7763 	 *	1) Instantiate the kstats here, before any routines using the
7764 	 *	   iopath (i.e. sd_send_scsi_cmd).
7765 	 *	2) Instantiate and initialize the partition stats
7766 	 *	   (sd_set_pstats).
7767 	 *	3) Initialize the error stats (sd_set_errstats), following
7768 	 *	   sd_validate_geometry(),sd_register_devid(),
7769 	 *	   and sd_cache_control().
7770 	 */
7771 
7772 	un->un_stats = kstat_create(sd_label, instance,
7773 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
7774 	if (un->un_stats != NULL) {
7775 		un->un_stats->ks_lock = SD_MUTEX(un);
7776 		kstat_install(un->un_stats);
7777 	}
7778 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7779 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
7780 
7781 	un->un_unmapstats_ks = kstat_create(sd_label, instance, "unmapstats",
7782 	    "misc", KSTAT_TYPE_NAMED, sizeof (*un->un_unmapstats) /
7783 	    sizeof (kstat_named_t), 0);
7784 	if (un->un_unmapstats_ks) {
7785 		un->un_unmapstats = un->un_unmapstats_ks->ks_data;
7786 
7787 		kstat_named_init(&un->un_unmapstats->us_cmds,
7788 		    "commands", KSTAT_DATA_UINT64);
7789 		kstat_named_init(&un->un_unmapstats->us_errs,
7790 		    "errors", KSTAT_DATA_UINT64);
7791 		kstat_named_init(&un->un_unmapstats->us_extents,
7792 		    "extents", KSTAT_DATA_UINT64);
7793 		kstat_named_init(&un->un_unmapstats->us_bytes,
7794 		    "bytes", KSTAT_DATA_UINT64);
7795 
7796 		kstat_install(un->un_unmapstats_ks);
7797 	} else {
7798 		cmn_err(CE_NOTE, "!Cannot create unmap kstats for disk %d",
7799 		    instance);
7800 	}
7801 
7802 	sd_create_errstats(un, instance);
7803 	if (un->un_errstats == NULL) {
7804 		goto create_errstats_failed;
7805 	}
7806 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7807 	    "sd_unit_attach: un:0x%p errstats created\n", un);
7808 
7809 	/*
7810 	 * The following if/else code was relocated here from below as part
7811 	 * of the fix for bug (4430280). However with the default setup added
7812 	 * on entry to this routine, it's no longer absolutely necessary for
7813 	 * this to be before the call to sd_spin_up_unit.
7814 	 */
7815 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
7816 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
7817 		    (devp->sd_inq->inq_ansi == 5)) &&
7818 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
7819 
7820 		/*
7821 		 * If tagged queueing is supported by the target
7822 		 * and by the host adapter then we will enable it
7823 		 */
7824 		un->un_tagflags = 0;
7825 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
7826 		    (un->un_f_arq_enabled == TRUE)) {
7827 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
7828 			    1, 1) == 1) {
7829 				un->un_tagflags = FLAG_STAG;
7830 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7831 				    "sd_unit_attach: un:0x%p tag queueing "
7832 				    "enabled\n", un);
7833 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
7834 			    "untagged-qing", 0) == 1) {
7835 				un->un_f_opt_queueing = TRUE;
7836 				un->un_saved_throttle = un->un_throttle =
7837 				    min(un->un_throttle, 3);
7838 			} else {
7839 				un->un_f_opt_queueing = FALSE;
7840 				un->un_saved_throttle = un->un_throttle = 1;
7841 			}
7842 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
7843 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
7844 			/* The Host Adapter supports internal queueing. */
7845 			un->un_f_opt_queueing = TRUE;
7846 			un->un_saved_throttle = un->un_throttle =
7847 			    min(un->un_throttle, 3);
7848 		} else {
7849 			un->un_f_opt_queueing = FALSE;
7850 			un->un_saved_throttle = un->un_throttle = 1;
7851 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7852 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
7853 		}
7854 
7855 		/*
7856 		 * Enable large transfers for SATA/SAS drives
7857 		 */
7858 		if (SD_IS_SERIAL(un)) {
7859 			un->un_max_xfer_size =
7860 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7861 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7862 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7863 			    "sd_unit_attach: un:0x%p max transfer "
7864 			    "size=0x%x\n", un, un->un_max_xfer_size);
7865 
7866 		}
7867 
7868 		/* Setup or tear down default wide operations for disks */
7869 
7870 		/*
7871 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
7872 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
7873 		 * system and be set to different values. In the future this
7874 		 * code may need to be updated when the ssd module is
7875 		 * obsoleted and removed from the system. (4299588)
7876 		 */
7877 		if (SD_IS_PARALLEL_SCSI(un) &&
7878 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
7879 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
7880 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7881 			    1, 1) == 1) {
7882 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7883 				    "sd_unit_attach: un:0x%p Wide Transfer "
7884 				    "enabled\n", un);
7885 			}
7886 
7887 			/*
7888 			 * If tagged queuing has also been enabled, then
7889 			 * enable large xfers
7890 			 */
7891 			if (un->un_saved_throttle == sd_max_throttle) {
7892 				un->un_max_xfer_size =
7893 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7894 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7895 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7896 				    "sd_unit_attach: un:0x%p max transfer "
7897 				    "size=0x%x\n", un, un->un_max_xfer_size);
7898 			}
7899 		} else {
7900 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7901 			    0, 1) == 1) {
7902 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7903 				    "sd_unit_attach: un:0x%p "
7904 				    "Wide Transfer disabled\n", un);
7905 			}
7906 		}
7907 	} else {
7908 		un->un_tagflags = FLAG_STAG;
7909 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7910 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7911 	}
7912 
7913 	/*
7914 	 * If this target supports LUN reset, try to enable it.
7915 	 */
7916 	if (un->un_f_lun_reset_enabled) {
7917 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7918 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7919 			    "un:0x%p lun_reset capability set\n", un);
7920 		} else {
7921 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7922 			    "un:0x%p lun-reset capability not set\n", un);
7923 		}
7924 	}
7925 
7926 	/*
7927 	 * Adjust the maximum transfer size. This is to fix
7928 	 * the problem of partial DMA support on SPARC. Some
7929 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7930 	 * size, which requires partial DMA support on SPARC.
7931 	 * In the future the SPARC pci nexus driver may solve
7932 	 * the problem instead of this fix.
7933 	 */
7934 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7935 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7936 		/* We need DMA partial even on sparc to ensure sddump() works */
7937 		un->un_max_xfer_size = max_xfer_size;
7938 		if (un->un_partial_dma_supported == 0)
7939 			un->un_partial_dma_supported = 1;
7940 	}
7941 	if (ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7942 	    DDI_PROP_DONTPASS, "buf_break", 0) == 1) {
7943 		if (ddi_xbuf_attr_setup_brk(un->un_xbuf_attr,
7944 		    un->un_max_xfer_size) == 1) {
7945 			un->un_buf_breakup_supported = 1;
7946 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7947 			    "un:0x%p Buf breakup enabled\n", un);
7948 		}
7949 	}
7950 
7951 	/*
7952 	 * Set PKT_DMA_PARTIAL flag.
7953 	 */
7954 	if (un->un_partial_dma_supported == 1) {
7955 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7956 	} else {
7957 		un->un_pkt_flags = 0;
7958 	}
7959 
7960 	/* Initialize sd_ssc_t for internal uscsi commands */
7961 	ssc = sd_ssc_init(un);
7962 	scsi_fm_init(devp);
7963 
7964 	/*
7965 	 * Allocate memory for SCSI FMA stuffs.
7966 	 */
7967 	un->un_fm_private =
7968 	    kmem_zalloc(sizeof (struct sd_fm_internal), KM_SLEEP);
7969 	sfip = (struct sd_fm_internal *)un->un_fm_private;
7970 	sfip->fm_ssc.ssc_uscsi_cmd = &sfip->fm_ucmd;
7971 	sfip->fm_ssc.ssc_uscsi_info = &sfip->fm_uinfo;
7972 	sfip->fm_ssc.ssc_un = un;
7973 
7974 	if (ISCD(un) ||
7975 	    un->un_f_has_removable_media ||
7976 	    devp->sd_fm_capable == DDI_FM_NOT_CAPABLE) {
7977 		/*
7978 		 * We don't touch CDROM or the DDI_FM_NOT_CAPABLE device.
7979 		 * Their log are unchanged.
7980 		 */
7981 		sfip->fm_log_level = SD_FM_LOG_NSUP;
7982 	} else {
7983 		/*
7984 		 * If enter here, it should be non-CDROM and FM-capable
7985 		 * device, and it will not keep the old scsi_log as before
7986 		 * in /var/adm/messages. However, the property
7987 		 * "fm-scsi-log" will control whether the FM telemetry will
7988 		 * be logged in /var/adm/messages.
7989 		 */
7990 		int fm_scsi_log;
7991 		fm_scsi_log = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7992 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "fm-scsi-log", 0);
7993 
7994 		if (fm_scsi_log)
7995 			sfip->fm_log_level = SD_FM_LOG_EREPORT;
7996 		else
7997 			sfip->fm_log_level = SD_FM_LOG_SILENT;
7998 	}
7999 
8000 	/*
8001 	 * At this point in the attach, we have enough info in the
8002 	 * soft state to be able to issue commands to the target.
8003 	 *
8004 	 * All command paths used below MUST issue their commands as
8005 	 * SD_PATH_DIRECT. This is important as intermediate layers
8006 	 * are not all initialized yet (such as PM).
8007 	 */
8008 
8009 	/*
8010 	 * Send a TEST UNIT READY command to the device. This should clear
8011 	 * any outstanding UNIT ATTENTION that may be present.
8012 	 *
8013 	 * Note: Don't check for success, just track if there is a reservation,
8014 	 * this is a throw away command to clear any unit attentions.
8015 	 *
8016 	 * Note: This MUST be the first command issued to the target during
8017 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
8018 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
8019 	 * with attempts at spinning up a device with no media.
8020 	 */
8021 	status = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
8022 	if (status != 0) {
8023 		if (status == EACCES)
8024 			reservation_flag = SD_TARGET_IS_RESERVED;
8025 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8026 	}
8027 
8028 	/*
8029 	 * If the device is NOT a removable media device, attempt to spin
8030 	 * it up (using the START_STOP_UNIT command) and read its capacity
8031 	 * (using the READ CAPACITY command).  Note, however, that either
8032 	 * of these could fail and in some cases we would continue with
8033 	 * the attach despite the failure (see below).
8034 	 */
8035 	if (un->un_f_descr_format_supported) {
8036 
8037 		switch (sd_spin_up_unit(ssc)) {
8038 		case 0:
8039 			/*
8040 			 * Spin-up was successful; now try to read the
8041 			 * capacity.  If successful then save the results
8042 			 * and mark the capacity & lbasize as valid.
8043 			 */
8044 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8045 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
8046 
8047 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
8048 			    &lbasize, SD_PATH_DIRECT);
8049 
8050 			switch (status) {
8051 			case 0: {
8052 				if (capacity > DK_MAX_BLOCKS) {
8053 #ifdef _LP64
8054 					if ((capacity + 1) >
8055 					    SD_GROUP1_MAX_ADDRESS) {
8056 						/*
8057 						 * Enable descriptor format
8058 						 * sense data so that we can
8059 						 * get 64 bit sense data
8060 						 * fields.
8061 						 */
8062 						sd_enable_descr_sense(ssc);
8063 					}
8064 #else
8065 					/* 32-bit kernels can't handle this */
8066 					scsi_log(SD_DEVINFO(un),
8067 					    sd_label, CE_WARN,
8068 					    "disk has %llu blocks, which "
8069 					    "is too large for a 32-bit "
8070 					    "kernel", capacity);
8071 
8072 #if defined(__x86)
8073 					/*
8074 					 * 1TB disk was treated as (1T - 512)B
8075 					 * in the past, so that it might have
8076 					 * valid VTOC and solaris partitions,
8077 					 * we have to allow it to continue to
8078 					 * work.
8079 					 */
8080 					if (capacity - 1 > DK_MAX_BLOCKS)
8081 #endif
8082 					goto spinup_failed;
8083 #endif
8084 				}
8085 
8086 				/*
8087 				 * Here it's not necessary to check the case:
8088 				 * the capacity of the device is bigger than
8089 				 * what the max hba cdb can support. Because
8090 				 * sd_send_scsi_READ_CAPACITY will retrieve
8091 				 * the capacity by sending USCSI command, which
8092 				 * is constrained by the max hba cdb. Actually,
8093 				 * sd_send_scsi_READ_CAPACITY will return
8094 				 * EINVAL when using bigger cdb than required
8095 				 * cdb length. Will handle this case in
8096 				 * "case EINVAL".
8097 				 */
8098 
8099 				/*
8100 				 * The following relies on
8101 				 * sd_send_scsi_READ_CAPACITY never
8102 				 * returning 0 for capacity and/or lbasize.
8103 				 */
8104 				sd_update_block_info(un, lbasize, capacity);
8105 
8106 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8107 				    "sd_unit_attach: un:0x%p capacity = %ld "
8108 				    "blocks; lbasize= %ld.\n", un,
8109 				    un->un_blockcount, un->un_tgt_blocksize);
8110 
8111 				break;
8112 			}
8113 			case EINVAL:
8114 				/*
8115 				 * In the case where the max-cdb-length property
8116 				 * is smaller than the required CDB length for
8117 				 * a SCSI device, a target driver can fail to
8118 				 * attach to that device.
8119 				 */
8120 				scsi_log(SD_DEVINFO(un),
8121 				    sd_label, CE_WARN,
8122 				    "disk capacity is too large "
8123 				    "for current cdb length");
8124 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8125 
8126 				goto spinup_failed;
8127 			case EACCES:
8128 				/*
8129 				 * Should never get here if the spin-up
8130 				 * succeeded, but code it in anyway.
8131 				 * From here, just continue with the attach...
8132 				 */
8133 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8134 				    "sd_unit_attach: un:0x%p "
8135 				    "sd_send_scsi_READ_CAPACITY "
8136 				    "returned reservation conflict\n", un);
8137 				reservation_flag = SD_TARGET_IS_RESERVED;
8138 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8139 				break;
8140 			default:
8141 				/*
8142 				 * Likewise, should never get here if the
8143 				 * spin-up succeeded. Just continue with
8144 				 * the attach...
8145 				 */
8146 				if (status == EIO)
8147 					sd_ssc_assessment(ssc,
8148 					    SD_FMT_STATUS_CHECK);
8149 				else
8150 					sd_ssc_assessment(ssc,
8151 					    SD_FMT_IGNORE);
8152 				break;
8153 			}
8154 			break;
8155 		case EACCES:
8156 			/*
8157 			 * Device is reserved by another host.  In this case
8158 			 * we could not spin it up or read the capacity, but
8159 			 * we continue with the attach anyway.
8160 			 */
8161 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8162 			    "sd_unit_attach: un:0x%p spin-up reservation "
8163 			    "conflict.\n", un);
8164 			reservation_flag = SD_TARGET_IS_RESERVED;
8165 			break;
8166 		default:
8167 			/* Fail the attach if the spin-up failed. */
8168 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8169 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
8170 			goto spinup_failed;
8171 		}
8172 
8173 	}
8174 
8175 	/*
8176 	 * Check to see if this is a MMC drive
8177 	 */
8178 	if (ISCD(un)) {
8179 		sd_set_mmc_caps(ssc);
8180 	}
8181 
8182 	/*
8183 	 * Add a zero-length attribute to tell the world we support
8184 	 * kernel ioctls (for layered drivers)
8185 	 */
8186 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8187 	    DDI_KERNEL_IOCTL, NULL, 0);
8188 
8189 	/*
8190 	 * Add a boolean property to tell the world we support
8191 	 * the B_FAILFAST flag (for layered drivers)
8192 	 */
8193 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8194 	    "ddi-failfast-supported", NULL, 0);
8195 
8196 	/*
8197 	 * Initialize power management
8198 	 */
8199 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
8200 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
8201 	sd_setup_pm(ssc, devi);
8202 	if (un->un_f_pm_is_enabled == FALSE) {
8203 		/*
8204 		 * For performance, point to a jump table that does
8205 		 * not include pm.
8206 		 * The direct and priority chains don't change with PM.
8207 		 *
8208 		 * Note: this is currently done based on individual device
8209 		 * capabilities. When an interface for determining system
8210 		 * power enabled state becomes available, or when additional
8211 		 * layers are added to the command chain, these values will
8212 		 * have to be re-evaluated for correctness.
8213 		 */
8214 		if (un->un_f_non_devbsize_supported) {
8215 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
8216 		} else {
8217 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
8218 		}
8219 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8220 	}
8221 
8222 	/*
8223 	 * This property is set to 0 by HA software to avoid retries
8224 	 * on a reserved disk. (The preferred property name is
8225 	 * "retry-on-reservation-conflict") (1189689)
8226 	 *
8227 	 * Note: The use of a global here can have unintended consequences. A
8228 	 * per instance variable is preferable to match the capabilities of
8229 	 * different underlying hba's (4402600)
8230 	 */
8231 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
8232 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
8233 	    sd_retry_on_reservation_conflict);
8234 	if (sd_retry_on_reservation_conflict != 0) {
8235 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
8236 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
8237 		    sd_retry_on_reservation_conflict);
8238 	}
8239 
8240 	/* Set up options for QFULL handling. */
8241 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8242 	    "qfull-retries", -1)) != -1) {
8243 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
8244 		    rval, 1);
8245 	}
8246 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8247 	    "qfull-retry-interval", -1)) != -1) {
8248 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
8249 		    rval, 1);
8250 	}
8251 
8252 	/*
8253 	 * This just prints a message that announces the existence of the
8254 	 * device. The message is always printed in the system logfile, but
8255 	 * only appears on the console if the system is booted with the
8256 	 * -v (verbose) argument.
8257 	 */
8258 	ddi_report_dev(devi);
8259 
8260 	un->un_mediastate = DKIO_NONE;
8261 
8262 	/*
8263 	 * Check Block Device Characteristics VPD.
8264 	 */
8265 	sd_check_bdc_vpd(ssc);
8266 
8267 	/*
8268 	 * Check whether the drive is in emulation mode.
8269 	 */
8270 	sd_check_emulation_mode(ssc);
8271 
8272 	cmlb_alloc_handle(&un->un_cmlbhandle);
8273 
8274 #if defined(__x86)
8275 	/*
8276 	 * On x86, compensate for off-by-1 legacy error
8277 	 */
8278 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
8279 	    (lbasize == un->un_sys_blocksize))
8280 		offbyone = CMLB_OFF_BY_ONE;
8281 #endif
8282 
8283 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
8284 	    VOID2BOOLEAN(un->un_f_has_removable_media != 0),
8285 	    VOID2BOOLEAN(un->un_f_is_hotpluggable != 0),
8286 	    un->un_node_type, offbyone, un->un_cmlbhandle,
8287 	    (void *)SD_PATH_DIRECT) != 0) {
8288 		goto cmlb_attach_failed;
8289 	}
8290 
8291 
8292 	/*
8293 	 * Read and validate the device's geometry (ie, disk label)
8294 	 * A new unformatted drive will not have a valid geometry, but
8295 	 * the driver needs to successfully attach to this device so
8296 	 * the drive can be formatted via ioctls.
8297 	 */
8298 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
8299 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
8300 
8301 	mutex_enter(SD_MUTEX(un));
8302 
8303 	/*
8304 	 * Read and initialize the devid for the unit.
8305 	 */
8306 	if (un->un_f_devid_supported) {
8307 		sd_register_devid(ssc, devi, reservation_flag);
8308 	}
8309 	mutex_exit(SD_MUTEX(un));
8310 
8311 #if (defined(__fibre))
8312 	/*
8313 	 * Register callbacks for fibre only.  You can't do this solely
8314 	 * on the basis of the devid_type because this is hba specific.
8315 	 * We need to query our hba capabilities to find out whether to
8316 	 * register or not.
8317 	 */
8318 	if (un->un_f_is_fibre) {
8319 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
8320 			sd_init_event_callbacks(un);
8321 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8322 			    "sd_unit_attach: un:0x%p event callbacks inserted",
8323 			    un);
8324 		}
8325 	}
8326 #endif
8327 
8328 	if (un->un_f_opt_disable_cache == TRUE) {
8329 		/*
8330 		 * Disable both read cache and write cache.  This is
8331 		 * the historic behavior of the keywords in the config file.
8332 		 */
8333 		if (sd_cache_control(ssc, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
8334 		    0) {
8335 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8336 			    "sd_unit_attach: un:0x%p Could not disable "
8337 			    "caching", un);
8338 			goto devid_failed;
8339 		}
8340 	}
8341 
8342 	/*
8343 	 * Check the value of the WCE bit and if it's allowed to be changed,
8344 	 * set un_f_write_cache_enabled and un_f_cache_mode_changeable
8345 	 * accordingly.
8346 	 */
8347 	(void) sd_get_write_cache_enabled(ssc, &wc_enabled);
8348 	sd_get_write_cache_changeable(ssc, &wc_changeable);
8349 	mutex_enter(SD_MUTEX(un));
8350 	un->un_f_write_cache_enabled = (wc_enabled != 0);
8351 	un->un_f_cache_mode_changeable = (wc_changeable != 0);
8352 	mutex_exit(SD_MUTEX(un));
8353 
8354 	if ((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR &&
8355 	    un->un_tgt_blocksize != DEV_BSIZE) ||
8356 	    un->un_f_enable_rmw) {
8357 		if (!(un->un_wm_cache)) {
8358 			(void) snprintf(name_str, sizeof (name_str),
8359 			    "%s%d_cache",
8360 			    ddi_driver_name(SD_DEVINFO(un)),
8361 			    ddi_get_instance(SD_DEVINFO(un)));
8362 			un->un_wm_cache = kmem_cache_create(
8363 			    name_str, sizeof (struct sd_w_map),
8364 			    8, sd_wm_cache_constructor,
8365 			    sd_wm_cache_destructor, NULL,
8366 			    (void *)un, NULL, 0);
8367 			if (!(un->un_wm_cache)) {
8368 				goto wm_cache_failed;
8369 			}
8370 		}
8371 	}
8372 
8373 	/*
8374 	 * Check the value of the NV_SUP bit and set
8375 	 * un_f_suppress_cache_flush accordingly.
8376 	 */
8377 	sd_get_nv_sup(ssc);
8378 
8379 	/*
8380 	 * Find out what type of reservation this disk supports.
8381 	 */
8382 	status = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS, 0, NULL);
8383 
8384 	switch (status) {
8385 	case 0:
8386 		/*
8387 		 * SCSI-3 reservations are supported.
8388 		 */
8389 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8390 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8391 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
8392 		break;
8393 	case ENOTSUP:
8394 		/*
8395 		 * The PERSISTENT RESERVE IN command would not be recognized by
8396 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
8397 		 */
8398 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8399 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
8400 		un->un_reservation_type = SD_SCSI2_RESERVATION;
8401 
8402 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8403 		break;
8404 	default:
8405 		/*
8406 		 * default to SCSI-3 reservations
8407 		 */
8408 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8409 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
8410 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8411 
8412 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8413 		break;
8414 	}
8415 
8416 	/*
8417 	 * Set the pstat and error stat values here, so data obtained during the
8418 	 * previous attach-time routines is available.
8419 	 *
8420 	 * Note: This is a critical sequence that needs to be maintained:
8421 	 *	1) Instantiate the kstats before any routines using the iopath
8422 	 *	   (i.e. sd_send_scsi_cmd).
8423 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8424 	 *	   stats (sd_set_pstats)here, following
8425 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
8426 	 *	   sd_cache_control().
8427 	 */
8428 
8429 	if (un->un_f_pkstats_enabled && geom_label_valid) {
8430 		sd_set_pstats(un);
8431 		SD_TRACE(SD_LOG_IO_PARTITION, un,
8432 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
8433 	}
8434 
8435 	sd_set_errstats(un);
8436 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8437 	    "sd_unit_attach: un:0x%p errstats set\n", un);
8438 
8439 	sd_setup_blk_limits(ssc);
8440 
8441 	/*
8442 	 * After successfully attaching an instance, we record the information
8443 	 * of how many luns have been attached on the relative target and
8444 	 * controller for parallel SCSI. This information is used when sd tries
8445 	 * to set the tagged queuing capability in HBA.
8446 	 */
8447 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8448 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
8449 	}
8450 
8451 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8452 	    "sd_unit_attach: un:0x%p exit success\n", un);
8453 
8454 	/* Uninitialize sd_ssc_t pointer */
8455 	sd_ssc_fini(ssc);
8456 
8457 	return (DDI_SUCCESS);
8458 
8459 	/*
8460 	 * An error occurred during the attach; clean up & return failure.
8461 	 */
8462 wm_cache_failed:
8463 devid_failed:
8464 	ddi_remove_minor_node(devi, NULL);
8465 
8466 cmlb_attach_failed:
8467 	/*
8468 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8469 	 */
8470 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8471 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8472 
8473 	/*
8474 	 * Refer to the comments of setting tagged-qing in the beginning of
8475 	 * sd_unit_attach. We can only disable tagged queuing when there is
8476 	 * no lun attached on the target.
8477 	 */
8478 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
8479 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8480 	}
8481 
8482 	if (un->un_f_is_fibre == FALSE) {
8483 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8484 	}
8485 
8486 spinup_failed:
8487 
8488 	/* Uninitialize sd_ssc_t pointer */
8489 	sd_ssc_fini(ssc);
8490 
8491 	mutex_enter(SD_MUTEX(un));
8492 
8493 	/* Deallocate SCSI FMA memory spaces */
8494 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8495 
8496 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
8497 	if (un->un_direct_priority_timeid != NULL) {
8498 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8499 		un->un_direct_priority_timeid = NULL;
8500 		mutex_exit(SD_MUTEX(un));
8501 		(void) untimeout(temp_id);
8502 		mutex_enter(SD_MUTEX(un));
8503 	}
8504 
8505 	/* Cancel any pending start/stop timeouts */
8506 	if (un->un_startstop_timeid != NULL) {
8507 		timeout_id_t temp_id = un->un_startstop_timeid;
8508 		un->un_startstop_timeid = NULL;
8509 		mutex_exit(SD_MUTEX(un));
8510 		(void) untimeout(temp_id);
8511 		mutex_enter(SD_MUTEX(un));
8512 	}
8513 
8514 	/* Cancel any pending reset-throttle timeouts */
8515 	if (un->un_reset_throttle_timeid != NULL) {
8516 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8517 		un->un_reset_throttle_timeid = NULL;
8518 		mutex_exit(SD_MUTEX(un));
8519 		(void) untimeout(temp_id);
8520 		mutex_enter(SD_MUTEX(un));
8521 	}
8522 
8523 	/* Cancel rmw warning message timeouts */
8524 	if (un->un_rmw_msg_timeid != NULL) {
8525 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8526 		un->un_rmw_msg_timeid = NULL;
8527 		mutex_exit(SD_MUTEX(un));
8528 		(void) untimeout(temp_id);
8529 		mutex_enter(SD_MUTEX(un));
8530 	}
8531 
8532 	/* Cancel any pending retry timeouts */
8533 	if (un->un_retry_timeid != NULL) {
8534 		timeout_id_t temp_id = un->un_retry_timeid;
8535 		un->un_retry_timeid = NULL;
8536 		mutex_exit(SD_MUTEX(un));
8537 		(void) untimeout(temp_id);
8538 		mutex_enter(SD_MUTEX(un));
8539 	}
8540 
8541 	/* Cancel any pending delayed cv broadcast timeouts */
8542 	if (un->un_dcvb_timeid != NULL) {
8543 		timeout_id_t temp_id = un->un_dcvb_timeid;
8544 		un->un_dcvb_timeid = NULL;
8545 		mutex_exit(SD_MUTEX(un));
8546 		(void) untimeout(temp_id);
8547 		mutex_enter(SD_MUTEX(un));
8548 	}
8549 
8550 	mutex_exit(SD_MUTEX(un));
8551 
8552 	/* There should not be any in-progress I/O so ASSERT this check */
8553 	ASSERT(un->un_ncmds_in_transport == 0);
8554 	ASSERT(un->un_ncmds_in_driver == 0);
8555 
8556 	/* Do not free the softstate if the callback routine is active */
8557 	sd_sync_with_callback(un);
8558 
8559 	/*
8560 	 * Partition stats apparently are not used with removables. These would
8561 	 * not have been created during attach, so no need to clean them up...
8562 	 */
8563 	if (un->un_errstats != NULL) {
8564 		kstat_delete(un->un_errstats);
8565 		un->un_errstats = NULL;
8566 	}
8567 
8568 create_errstats_failed:
8569 
8570 	if (un->un_stats != NULL) {
8571 		kstat_delete(un->un_stats);
8572 		un->un_stats = NULL;
8573 	}
8574 
8575 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8576 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8577 
8578 	ddi_prop_remove_all(devi);
8579 	sema_destroy(&un->un_semoclose);
8580 	cv_destroy(&un->un_state_cv);
8581 
8582 	sd_free_rqs(un);
8583 
8584 alloc_rqs_failed:
8585 
8586 	devp->sd_private = NULL;
8587 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8588 
8589 	/*
8590 	 * Note: the man pages are unclear as to whether or not doing a
8591 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8592 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8593 	 * ddi_get_soft_state() fails.  The implication seems to be
8594 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8595 	 */
8596 #ifndef XPV_HVM_DRIVER
8597 	ddi_soft_state_free(sd_state, instance);
8598 #endif /* !XPV_HVM_DRIVER */
8599 
8600 probe_failed:
8601 	scsi_unprobe(devp);
8602 
8603 	return (DDI_FAILURE);
8604 }
8605 
8606 
8607 /*
8608  *    Function: sd_unit_detach
8609  *
8610  * Description: Performs DDI_DETACH processing for sddetach().
8611  *
8612  * Return Code: DDI_SUCCESS
8613  *		DDI_FAILURE
8614  *
8615  *     Context: Kernel thread context
8616  */
8617 
8618 static int
8619 sd_unit_detach(dev_info_t *devi)
8620 {
8621 	struct scsi_device	*devp;
8622 	struct sd_lun		*un;
8623 	int			i;
8624 	int			tgt;
8625 	dev_t			dev;
8626 	dev_info_t		*pdip = ddi_get_parent(devi);
8627 	int			instance = ddi_get_instance(devi);
8628 
8629 	mutex_enter(&sd_detach_mutex);
8630 
8631 	/*
8632 	 * Fail the detach for any of the following:
8633 	 *  - Unable to get the sd_lun struct for the instance
8634 	 *  - A layered driver has an outstanding open on the instance
8635 	 *  - Another thread is already detaching this instance
8636 	 *  - Another thread is currently performing an open
8637 	 */
8638 	devp = ddi_get_driver_private(devi);
8639 	if ((devp == NULL) ||
8640 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8641 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
8642 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
8643 		mutex_exit(&sd_detach_mutex);
8644 		return (DDI_FAILURE);
8645 	}
8646 
8647 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8648 
8649 	/*
8650 	 * Mark this instance as currently in a detach, to inhibit any
8651 	 * opens from a layered driver.
8652 	 */
8653 	un->un_detach_count++;
8654 	mutex_exit(&sd_detach_mutex);
8655 
8656 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
8657 	    SCSI_ADDR_PROP_TARGET, -1);
8658 
8659 	dev = sd_make_device(SD_DEVINFO(un));
8660 
8661 #ifndef lint
8662 	_NOTE(COMPETING_THREADS_NOW);
8663 #endif
8664 
8665 	mutex_enter(SD_MUTEX(un));
8666 
8667 	/*
8668 	 * Fail the detach if there are any outstanding layered
8669 	 * opens on this device.
8670 	 */
8671 	for (i = 0; i < NDKMAP; i++) {
8672 		if (un->un_ocmap.lyropen[i] != 0) {
8673 			goto err_notclosed;
8674 		}
8675 	}
8676 
8677 	/*
8678 	 * Verify there are NO outstanding commands issued to this device.
8679 	 * ie, un_ncmds_in_transport == 0.
8680 	 * It's possible to have outstanding commands through the physio
8681 	 * code path, even though everything's closed.
8682 	 */
8683 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8684 	    (un->un_direct_priority_timeid != NULL) ||
8685 	    (un->un_state == SD_STATE_RWAIT)) {
8686 		mutex_exit(SD_MUTEX(un));
8687 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8688 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8689 		goto err_stillbusy;
8690 	}
8691 
8692 	/*
8693 	 * If we have the device reserved, release the reservation.
8694 	 */
8695 	if ((un->un_resvd_status & SD_RESERVE) &&
8696 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8697 		mutex_exit(SD_MUTEX(un));
8698 		/*
8699 		 * Note: sd_reserve_release sends a command to the device
8700 		 * via the sd_ioctlcmd() path, and can sleep.
8701 		 */
8702 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8703 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8704 			    "sd_dr_detach: Cannot release reservation \n");
8705 		}
8706 	} else {
8707 		mutex_exit(SD_MUTEX(un));
8708 	}
8709 
8710 	/*
8711 	 * Untimeout any reserve recover, throttle reset, restart unit
8712 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8713 	 * from getting nulled by their callback functions.
8714 	 */
8715 	mutex_enter(SD_MUTEX(un));
8716 	if (un->un_resvd_timeid != NULL) {
8717 		timeout_id_t temp_id = un->un_resvd_timeid;
8718 		un->un_resvd_timeid = NULL;
8719 		mutex_exit(SD_MUTEX(un));
8720 		(void) untimeout(temp_id);
8721 		mutex_enter(SD_MUTEX(un));
8722 	}
8723 
8724 	if (un->un_reset_throttle_timeid != NULL) {
8725 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8726 		un->un_reset_throttle_timeid = NULL;
8727 		mutex_exit(SD_MUTEX(un));
8728 		(void) untimeout(temp_id);
8729 		mutex_enter(SD_MUTEX(un));
8730 	}
8731 
8732 	if (un->un_startstop_timeid != NULL) {
8733 		timeout_id_t temp_id = un->un_startstop_timeid;
8734 		un->un_startstop_timeid = NULL;
8735 		mutex_exit(SD_MUTEX(un));
8736 		(void) untimeout(temp_id);
8737 		mutex_enter(SD_MUTEX(un));
8738 	}
8739 
8740 	if (un->un_rmw_msg_timeid != NULL) {
8741 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8742 		un->un_rmw_msg_timeid = NULL;
8743 		mutex_exit(SD_MUTEX(un));
8744 		(void) untimeout(temp_id);
8745 		mutex_enter(SD_MUTEX(un));
8746 	}
8747 
8748 	if (un->un_dcvb_timeid != NULL) {
8749 		timeout_id_t temp_id = un->un_dcvb_timeid;
8750 		un->un_dcvb_timeid = NULL;
8751 		mutex_exit(SD_MUTEX(un));
8752 		(void) untimeout(temp_id);
8753 	} else {
8754 		mutex_exit(SD_MUTEX(un));
8755 	}
8756 
8757 	/* Remove any pending reservation reclaim requests for this device */
8758 	sd_rmv_resv_reclaim_req(dev);
8759 
8760 	mutex_enter(SD_MUTEX(un));
8761 
8762 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8763 	if (un->un_direct_priority_timeid != NULL) {
8764 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8765 		un->un_direct_priority_timeid = NULL;
8766 		mutex_exit(SD_MUTEX(un));
8767 		(void) untimeout(temp_id);
8768 		mutex_enter(SD_MUTEX(un));
8769 	}
8770 
8771 	/* Cancel any active multi-host disk watch thread requests */
8772 	if (un->un_mhd_token != NULL) {
8773 		mutex_exit(SD_MUTEX(un));
8774 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8775 		if (scsi_watch_request_terminate(un->un_mhd_token,
8776 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8777 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8778 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8779 			/*
8780 			 * Note: We are returning here after having removed
8781 			 * some driver timeouts above. This is consistent with
8782 			 * the legacy implementation but perhaps the watch
8783 			 * terminate call should be made with the wait flag set.
8784 			 */
8785 			goto err_stillbusy;
8786 		}
8787 		mutex_enter(SD_MUTEX(un));
8788 		un->un_mhd_token = NULL;
8789 	}
8790 
8791 	if (un->un_swr_token != NULL) {
8792 		mutex_exit(SD_MUTEX(un));
8793 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8794 		if (scsi_watch_request_terminate(un->un_swr_token,
8795 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8796 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8797 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8798 			/*
8799 			 * Note: We are returning here after having removed
8800 			 * some driver timeouts above. This is consistent with
8801 			 * the legacy implementation but perhaps the watch
8802 			 * terminate call should be made with the wait flag set.
8803 			 */
8804 			goto err_stillbusy;
8805 		}
8806 		mutex_enter(SD_MUTEX(un));
8807 		un->un_swr_token = NULL;
8808 	}
8809 
8810 	mutex_exit(SD_MUTEX(un));
8811 
8812 	/*
8813 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8814 	 * if we have not registered one.
8815 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8816 	 */
8817 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8818 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8819 
8820 	/*
8821 	 * protect the timeout pointers from getting nulled by
8822 	 * their callback functions during the cancellation process.
8823 	 * In such a scenario untimeout can be invoked with a null value.
8824 	 */
8825 	_NOTE(NO_COMPETING_THREADS_NOW);
8826 
8827 	mutex_enter(&un->un_pm_mutex);
8828 	if (un->un_pm_idle_timeid != NULL) {
8829 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8830 		un->un_pm_idle_timeid = NULL;
8831 		mutex_exit(&un->un_pm_mutex);
8832 
8833 		/*
8834 		 * Timeout is active; cancel it.
8835 		 * Note that it'll never be active on a device
8836 		 * that does not support PM therefore we don't
8837 		 * have to check before calling pm_idle_component.
8838 		 */
8839 		(void) untimeout(temp_id);
8840 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8841 		mutex_enter(&un->un_pm_mutex);
8842 	}
8843 
8844 	/*
8845 	 * Check whether there is already a timeout scheduled for power
8846 	 * management. If yes then don't lower the power here, that's.
8847 	 * the timeout handler's job.
8848 	 */
8849 	if (un->un_pm_timeid != NULL) {
8850 		timeout_id_t temp_id = un->un_pm_timeid;
8851 		un->un_pm_timeid = NULL;
8852 		mutex_exit(&un->un_pm_mutex);
8853 		/*
8854 		 * Timeout is active; cancel it.
8855 		 * Note that it'll never be active on a device
8856 		 * that does not support PM therefore we don't
8857 		 * have to check before calling pm_idle_component.
8858 		 */
8859 		(void) untimeout(temp_id);
8860 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8861 
8862 	} else {
8863 		mutex_exit(&un->un_pm_mutex);
8864 		if ((un->un_f_pm_is_enabled == TRUE) &&
8865 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_PM_STATE_STOPPED(un))
8866 		    != DDI_SUCCESS)) {
8867 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8868 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8869 			/*
8870 			 * Fix for bug: 4297749, item # 13
8871 			 * The above test now includes a check to see if PM is
8872 			 * supported by this device before call
8873 			 * pm_lower_power().
8874 			 * Note, the following is not dead code. The call to
8875 			 * pm_lower_power above will generate a call back into
8876 			 * our sdpower routine which might result in a timeout
8877 			 * handler getting activated. Therefore the following
8878 			 * code is valid and necessary.
8879 			 */
8880 			mutex_enter(&un->un_pm_mutex);
8881 			if (un->un_pm_timeid != NULL) {
8882 				timeout_id_t temp_id = un->un_pm_timeid;
8883 				un->un_pm_timeid = NULL;
8884 				mutex_exit(&un->un_pm_mutex);
8885 				(void) untimeout(temp_id);
8886 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8887 			} else {
8888 				mutex_exit(&un->un_pm_mutex);
8889 			}
8890 		}
8891 	}
8892 
8893 	/*
8894 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8895 	 * Relocated here from above to be after the call to
8896 	 * pm_lower_power, which was getting errors.
8897 	 */
8898 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8899 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8900 
8901 	/*
8902 	 * Currently, tagged queuing is supported per target based by HBA.
8903 	 * Setting this per lun instance actually sets the capability of this
8904 	 * target in HBA, which affects those luns already attached on the
8905 	 * same target. So during detach, we can only disable this capability
8906 	 * only when this is the only lun left on this target. By doing
8907 	 * this, we assume a target has the same tagged queuing capability
8908 	 * for every lun. The condition can be removed when HBA is changed to
8909 	 * support per lun based tagged queuing capability.
8910 	 */
8911 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
8912 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8913 	}
8914 
8915 	if (un->un_f_is_fibre == FALSE) {
8916 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8917 	}
8918 
8919 	/*
8920 	 * Remove any event callbacks, fibre only
8921 	 */
8922 	if (un->un_f_is_fibre == TRUE) {
8923 		if ((un->un_insert_event != NULL) &&
8924 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
8925 		    DDI_SUCCESS)) {
8926 			/*
8927 			 * Note: We are returning here after having done
8928 			 * substantial cleanup above. This is consistent
8929 			 * with the legacy implementation but this may not
8930 			 * be the right thing to do.
8931 			 */
8932 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8933 			    "sd_dr_detach: Cannot cancel insert event\n");
8934 			goto err_remove_event;
8935 		}
8936 		un->un_insert_event = NULL;
8937 
8938 		if ((un->un_remove_event != NULL) &&
8939 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
8940 		    DDI_SUCCESS)) {
8941 			/*
8942 			 * Note: We are returning here after having done
8943 			 * substantial cleanup above. This is consistent
8944 			 * with the legacy implementation but this may not
8945 			 * be the right thing to do.
8946 			 */
8947 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8948 			    "sd_dr_detach: Cannot cancel remove event\n");
8949 			goto err_remove_event;
8950 		}
8951 		un->un_remove_event = NULL;
8952 	}
8953 
8954 	/* Do not free the softstate if the callback routine is active */
8955 	sd_sync_with_callback(un);
8956 
8957 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
8958 	cmlb_free_handle(&un->un_cmlbhandle);
8959 
8960 	/*
8961 	 * Hold the detach mutex here, to make sure that no other threads ever
8962 	 * can access a (partially) freed soft state structure.
8963 	 */
8964 	mutex_enter(&sd_detach_mutex);
8965 
8966 	/*
8967 	 * Clean up the soft state struct.
8968 	 * Cleanup is done in reverse order of allocs/inits.
8969 	 * At this point there should be no competing threads anymore.
8970 	 */
8971 
8972 	scsi_fm_fini(devp);
8973 
8974 	/*
8975 	 * Deallocate memory for SCSI FMA.
8976 	 */
8977 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8978 
8979 	/*
8980 	 * Unregister and free device id if it was not registered
8981 	 * by the transport.
8982 	 */
8983 	if (un->un_f_devid_transport_defined == FALSE)
8984 		ddi_devid_unregister(devi);
8985 
8986 	/*
8987 	 * free the devid structure if allocated before (by ddi_devid_init()
8988 	 * or ddi_devid_get()).
8989 	 */
8990 	if (un->un_devid) {
8991 		ddi_devid_free(un->un_devid);
8992 		un->un_devid = NULL;
8993 	}
8994 
8995 	/*
8996 	 * Destroy wmap cache if it exists.
8997 	 */
8998 	if (un->un_wm_cache != NULL) {
8999 		kmem_cache_destroy(un->un_wm_cache);
9000 		un->un_wm_cache = NULL;
9001 	}
9002 
9003 	/*
9004 	 * kstat cleanup is done in detach for all device types (4363169).
9005 	 * We do not want to fail detach if the device kstats are not deleted
9006 	 * since there is a confusion about the devo_refcnt for the device.
9007 	 * We just delete the kstats and let detach complete successfully.
9008 	 */
9009 	if (un->un_stats != NULL) {
9010 		kstat_delete(un->un_stats);
9011 		un->un_stats = NULL;
9012 	}
9013 	if (un->un_unmapstats != NULL) {
9014 		kstat_delete(un->un_unmapstats_ks);
9015 		un->un_unmapstats_ks = NULL;
9016 		un->un_unmapstats = NULL;
9017 	}
9018 	if (un->un_errstats != NULL) {
9019 		kstat_delete(un->un_errstats);
9020 		un->un_errstats = NULL;
9021 	}
9022 
9023 	/* Remove partition stats */
9024 	if (un->un_f_pkstats_enabled) {
9025 		for (i = 0; i < NSDMAP; i++) {
9026 			if (un->un_pstats[i] != NULL) {
9027 				kstat_delete(un->un_pstats[i]);
9028 				un->un_pstats[i] = NULL;
9029 			}
9030 		}
9031 	}
9032 
9033 	/* Remove xbuf registration */
9034 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
9035 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
9036 
9037 	/* Remove driver properties */
9038 	ddi_prop_remove_all(devi);
9039 
9040 	mutex_destroy(&un->un_pm_mutex);
9041 	cv_destroy(&un->un_pm_busy_cv);
9042 
9043 	cv_destroy(&un->un_wcc_cv);
9044 
9045 	/* Open/close semaphore */
9046 	sema_destroy(&un->un_semoclose);
9047 
9048 	/* Removable media condvar. */
9049 	cv_destroy(&un->un_state_cv);
9050 
9051 	/* Suspend/resume condvar. */
9052 	cv_destroy(&un->un_suspend_cv);
9053 	cv_destroy(&un->un_disk_busy_cv);
9054 
9055 	sd_free_rqs(un);
9056 
9057 	/* Free up soft state */
9058 	devp->sd_private = NULL;
9059 
9060 	bzero(un, sizeof (struct sd_lun));
9061 
9062 	ddi_soft_state_free(sd_state, instance);
9063 
9064 	mutex_exit(&sd_detach_mutex);
9065 
9066 	/* This frees up the INQUIRY data associated with the device. */
9067 	scsi_unprobe(devp);
9068 
9069 	/*
9070 	 * After successfully detaching an instance, we update the information
9071 	 * of how many luns have been attached in the relative target and
9072 	 * controller for parallel SCSI. This information is used when sd tries
9073 	 * to set the tagged queuing capability in HBA.
9074 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
9075 	 * check if the device is parallel SCSI. However, we don't need to
9076 	 * check here because we've already checked during attach. No device
9077 	 * that is not parallel SCSI is in the chain.
9078 	 */
9079 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
9080 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
9081 	}
9082 
9083 	return (DDI_SUCCESS);
9084 
9085 err_notclosed:
9086 	mutex_exit(SD_MUTEX(un));
9087 
9088 err_stillbusy:
9089 	_NOTE(NO_COMPETING_THREADS_NOW);
9090 
9091 err_remove_event:
9092 	mutex_enter(&sd_detach_mutex);
9093 	un->un_detach_count--;
9094 	mutex_exit(&sd_detach_mutex);
9095 
9096 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
9097 	return (DDI_FAILURE);
9098 }
9099 
9100 
9101 /*
9102  *    Function: sd_create_errstats
9103  *
9104  * Description: This routine instantiates the device error stats.
9105  *
9106  *		Note: During attach the stats are instantiated first so they are
9107  *		available for attach-time routines that utilize the driver
9108  *		iopath to send commands to the device. The stats are initialized
9109  *		separately so data obtained during some attach-time routines is
9110  *		available. (4362483)
9111  *
9112  *   Arguments: un - driver soft state (unit) structure
9113  *		instance - driver instance
9114  *
9115  *     Context: Kernel thread context
9116  */
9117 
9118 static void
9119 sd_create_errstats(struct sd_lun *un, int instance)
9120 {
9121 	struct	sd_errstats	*stp;
9122 	char	kstatmodule_err[KSTAT_STRLEN];
9123 	char	kstatname[KSTAT_STRLEN];
9124 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
9125 
9126 	ASSERT(un != NULL);
9127 
9128 	if (un->un_errstats != NULL) {
9129 		return;
9130 	}
9131 
9132 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
9133 	    "%serr", sd_label);
9134 	(void) snprintf(kstatname, sizeof (kstatname),
9135 	    "%s%d,err", sd_label, instance);
9136 
9137 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
9138 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
9139 
9140 	if (un->un_errstats == NULL) {
9141 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
9142 		    "sd_create_errstats: Failed kstat_create\n");
9143 		return;
9144 	}
9145 
9146 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9147 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
9148 	    KSTAT_DATA_UINT32);
9149 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
9150 	    KSTAT_DATA_UINT32);
9151 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
9152 	    KSTAT_DATA_UINT32);
9153 	kstat_named_init(&stp->sd_vid,		"Vendor",
9154 	    KSTAT_DATA_CHAR);
9155 	kstat_named_init(&stp->sd_pid,		"Product",
9156 	    KSTAT_DATA_CHAR);
9157 	kstat_named_init(&stp->sd_revision,	"Revision",
9158 	    KSTAT_DATA_CHAR);
9159 	kstat_named_init(&stp->sd_serial,	"Serial No",
9160 	    KSTAT_DATA_CHAR);
9161 	kstat_named_init(&stp->sd_capacity,	"Size",
9162 	    KSTAT_DATA_ULONGLONG);
9163 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
9164 	    KSTAT_DATA_UINT32);
9165 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
9166 	    KSTAT_DATA_UINT32);
9167 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
9168 	    KSTAT_DATA_UINT32);
9169 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
9170 	    KSTAT_DATA_UINT32);
9171 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
9172 	    KSTAT_DATA_UINT32);
9173 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
9174 	    KSTAT_DATA_UINT32);
9175 
9176 	un->un_errstats->ks_private = un;
9177 	un->un_errstats->ks_update  = nulldev;
9178 
9179 	kstat_install(un->un_errstats);
9180 }
9181 
9182 
9183 /*
9184  *    Function: sd_set_errstats
9185  *
9186  * Description: This routine sets the value of the vendor id, product id,
9187  *		revision, serial number, and capacity device error stats.
9188  *
9189  *		Note: During attach the stats are instantiated first so they are
9190  *		available for attach-time routines that utilize the driver
9191  *		iopath to send commands to the device. The stats are initialized
9192  *		separately so data obtained during some attach-time routines is
9193  *		available. (4362483)
9194  *
9195  *   Arguments: un - driver soft state (unit) structure
9196  *
9197  *     Context: Kernel thread context
9198  */
9199 
9200 static void
9201 sd_set_errstats(struct sd_lun *un)
9202 {
9203 	struct	sd_errstats	*stp;
9204 	char			*sn;
9205 
9206 	ASSERT(un != NULL);
9207 	ASSERT(un->un_errstats != NULL);
9208 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9209 	ASSERT(stp != NULL);
9210 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
9211 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
9212 	(void) strncpy(stp->sd_revision.value.c,
9213 	    un->un_sd->sd_inq->inq_revision, 4);
9214 
9215 	/*
9216 	 * All the errstats are persistent across detach/attach,
9217 	 * so reset all the errstats here in case of the hot
9218 	 * replacement of disk drives, except for not changed
9219 	 * Sun qualified drives.
9220 	 */
9221 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
9222 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9223 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
9224 		stp->sd_softerrs.value.ui32 = 0;
9225 		stp->sd_harderrs.value.ui32 = 0;
9226 		stp->sd_transerrs.value.ui32 = 0;
9227 		stp->sd_rq_media_err.value.ui32 = 0;
9228 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
9229 		stp->sd_rq_nodev_err.value.ui32 = 0;
9230 		stp->sd_rq_recov_err.value.ui32 = 0;
9231 		stp->sd_rq_illrq_err.value.ui32 = 0;
9232 		stp->sd_rq_pfa_err.value.ui32 = 0;
9233 	}
9234 
9235 	/*
9236 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
9237 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
9238 	 * (4376302))
9239 	 */
9240 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
9241 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9242 		    sizeof (SD_INQUIRY(un)->inq_serial));
9243 	} else {
9244 		/*
9245 		 * Set the "Serial No" kstat for non-Sun qualified drives
9246 		 */
9247 		if (ddi_prop_lookup_string(DDI_DEV_T_ANY, SD_DEVINFO(un),
9248 		    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
9249 		    INQUIRY_SERIAL_NO, &sn) == DDI_SUCCESS) {
9250 			(void) strlcpy(stp->sd_serial.value.c, sn,
9251 			    sizeof (stp->sd_serial.value.c));
9252 			ddi_prop_free(sn);
9253 		}
9254 	}
9255 
9256 	if (un->un_f_blockcount_is_valid != TRUE) {
9257 		/*
9258 		 * Set capacity error stat to 0 for no media. This ensures
9259 		 * a valid capacity is displayed in response to 'iostat -E'
9260 		 * when no media is present in the device.
9261 		 */
9262 		stp->sd_capacity.value.ui64 = 0;
9263 	} else {
9264 		/*
9265 		 * Multiply un_blockcount by un->un_sys_blocksize to get
9266 		 * capacity.
9267 		 *
9268 		 * Note: for non-512 blocksize devices "un_blockcount" has been
9269 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
9270 		 * (un_tgt_blocksize / un->un_sys_blocksize).
9271 		 */
9272 		stp->sd_capacity.value.ui64 = (uint64_t)
9273 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
9274 	}
9275 }
9276 
9277 
9278 /*
9279  *    Function: sd_set_pstats
9280  *
9281  * Description: This routine instantiates and initializes the partition
9282  *              stats for each partition with more than zero blocks.
9283  *		(4363169)
9284  *
9285  *   Arguments: un - driver soft state (unit) structure
9286  *
9287  *     Context: Kernel thread context
9288  */
9289 
9290 static void
9291 sd_set_pstats(struct sd_lun *un)
9292 {
9293 	char	kstatname[KSTAT_STRLEN];
9294 	int	instance;
9295 	int	i;
9296 	diskaddr_t	nblks = 0;
9297 	char	*partname = NULL;
9298 
9299 	ASSERT(un != NULL);
9300 
9301 	instance = ddi_get_instance(SD_DEVINFO(un));
9302 
9303 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
9304 	for (i = 0; i < NSDMAP; i++) {
9305 
9306 		if (cmlb_partinfo(un->un_cmlbhandle, i,
9307 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
9308 			continue;
9309 		mutex_enter(SD_MUTEX(un));
9310 
9311 		if ((un->un_pstats[i] == NULL) &&
9312 		    (nblks != 0)) {
9313 
9314 			(void) snprintf(kstatname, sizeof (kstatname),
9315 			    "%s%d,%s", sd_label, instance,
9316 			    partname);
9317 
9318 			un->un_pstats[i] = kstat_create(sd_label,
9319 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
9320 			    1, KSTAT_FLAG_PERSISTENT);
9321 			if (un->un_pstats[i] != NULL) {
9322 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
9323 				kstat_install(un->un_pstats[i]);
9324 			}
9325 		}
9326 		mutex_exit(SD_MUTEX(un));
9327 	}
9328 }
9329 
9330 
9331 #if (defined(__fibre))
9332 /*
9333  *    Function: sd_init_event_callbacks
9334  *
9335  * Description: This routine initializes the insertion and removal event
9336  *		callbacks. (fibre only)
9337  *
9338  *   Arguments: un - driver soft state (unit) structure
9339  *
9340  *     Context: Kernel thread context
9341  */
9342 
9343 static void
9344 sd_init_event_callbacks(struct sd_lun *un)
9345 {
9346 	ASSERT(un != NULL);
9347 
9348 	if ((un->un_insert_event == NULL) &&
9349 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
9350 	    &un->un_insert_event) == DDI_SUCCESS)) {
9351 		/*
9352 		 * Add the callback for an insertion event
9353 		 */
9354 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9355 		    un->un_insert_event, sd_event_callback, (void *)un,
9356 		    &(un->un_insert_cb_id));
9357 	}
9358 
9359 	if ((un->un_remove_event == NULL) &&
9360 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
9361 	    &un->un_remove_event) == DDI_SUCCESS)) {
9362 		/*
9363 		 * Add the callback for a removal event
9364 		 */
9365 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9366 		    un->un_remove_event, sd_event_callback, (void *)un,
9367 		    &(un->un_remove_cb_id));
9368 	}
9369 }
9370 
9371 
9372 /*
9373  *    Function: sd_event_callback
9374  *
9375  * Description: This routine handles insert/remove events (photon). The
9376  *		state is changed to OFFLINE which can be used to supress
9377  *		error msgs. (fibre only)
9378  *
9379  *   Arguments: un - driver soft state (unit) structure
9380  *
9381  *     Context: Callout thread context
9382  */
9383 /* ARGSUSED */
9384 static void
9385 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
9386     void *bus_impldata)
9387 {
9388 	struct sd_lun *un = (struct sd_lun *)arg;
9389 
9390 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
9391 	if (event == un->un_insert_event) {
9392 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
9393 		mutex_enter(SD_MUTEX(un));
9394 		if (un->un_state == SD_STATE_OFFLINE) {
9395 			if (un->un_last_state != SD_STATE_SUSPENDED) {
9396 				un->un_state = un->un_last_state;
9397 			} else {
9398 				/*
9399 				 * We have gone through SUSPEND/RESUME while
9400 				 * we were offline. Restore the last state
9401 				 */
9402 				un->un_state = un->un_save_state;
9403 			}
9404 		}
9405 		mutex_exit(SD_MUTEX(un));
9406 
9407 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
9408 	} else if (event == un->un_remove_event) {
9409 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
9410 		mutex_enter(SD_MUTEX(un));
9411 		/*
9412 		 * We need to handle an event callback that occurs during
9413 		 * the suspend operation, since we don't prevent it.
9414 		 */
9415 		if (un->un_state != SD_STATE_OFFLINE) {
9416 			if (un->un_state != SD_STATE_SUSPENDED) {
9417 				New_state(un, SD_STATE_OFFLINE);
9418 			} else {
9419 				un->un_last_state = SD_STATE_OFFLINE;
9420 			}
9421 		}
9422 		mutex_exit(SD_MUTEX(un));
9423 	} else {
9424 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
9425 		    "!Unknown event\n");
9426 	}
9427 
9428 }
9429 #endif
9430 
9431 /*
9432  * Values related to caching mode page depending on whether the unit is ATAPI.
9433  */
9434 #define	SDC_CDB_GROUP(un) ((un->un_f_cfg_is_atapi == TRUE) ? \
9435 	CDB_GROUP1 : CDB_GROUP0)
9436 #define	SDC_HDRLEN(un) ((un->un_f_cfg_is_atapi == TRUE) ? \
9437 	MODE_HEADER_LENGTH_GRP2 : MODE_HEADER_LENGTH)
9438 /*
9439  * Use mode_cache_scsi3 to ensure we get all of the mode sense data, otherwise
9440  * the mode select will fail (mode_cache_scsi3 is a superset of mode_caching).
9441  */
9442 #define	SDC_BUFLEN(un) (SDC_HDRLEN(un) + MODE_BLK_DESC_LENGTH + \
9443 	sizeof (struct mode_cache_scsi3))
9444 
9445 static int
9446 sd_get_caching_mode_page(sd_ssc_t *ssc, uchar_t page_control, uchar_t **header,
9447     int *bdlen)
9448 {
9449 	struct sd_lun	*un = ssc->ssc_un;
9450 	struct mode_caching *mode_caching_page;
9451 	size_t		buflen = SDC_BUFLEN(un);
9452 	int		hdrlen = SDC_HDRLEN(un);
9453 	int		rval;
9454 
9455 	/*
9456 	 * Do a test unit ready, otherwise a mode sense may not work if this
9457 	 * is the first command sent to the device after boot.
9458 	 */
9459 	if (sd_send_scsi_TEST_UNIT_READY(ssc, 0) != 0)
9460 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9461 
9462 	/*
9463 	 * Allocate memory for the retrieved mode page and its headers.  Set
9464 	 * a pointer to the page itself.
9465 	 */
9466 	*header = kmem_zalloc(buflen, KM_SLEEP);
9467 
9468 	/* Get the information from the device */
9469 	rval = sd_send_scsi_MODE_SENSE(ssc, SDC_CDB_GROUP(un), *header, buflen,
9470 	    page_control | MODEPAGE_CACHING, SD_PATH_DIRECT);
9471 	if (rval != 0) {
9472 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un, "%s: Mode Sense Failed\n",
9473 		    __func__);
9474 		goto mode_sense_failed;
9475 	}
9476 
9477 	/*
9478 	 * Determine size of Block Descriptors in order to locate
9479 	 * the mode page data. ATAPI devices return 0, SCSI devices
9480 	 * should return MODE_BLK_DESC_LENGTH.
9481 	 */
9482 	if (un->un_f_cfg_is_atapi == TRUE) {
9483 		struct mode_header_grp2 *mhp =
9484 		    (struct mode_header_grp2 *)(*header);
9485 		*bdlen = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9486 	} else {
9487 		*bdlen = ((struct mode_header *)(*header))->bdesc_length;
9488 	}
9489 
9490 	if (*bdlen > MODE_BLK_DESC_LENGTH) {
9491 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9492 		    "%s: Mode Sense returned invalid block descriptor length\n",
9493 		    __func__);
9494 		rval = EIO;
9495 		goto mode_sense_failed;
9496 	}
9497 
9498 	mode_caching_page = (struct mode_caching *)(*header + hdrlen + *bdlen);
9499 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9500 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9501 		    "%s: Mode Sense caching page code mismatch %d\n",
9502 		    __func__, mode_caching_page->mode_page.code);
9503 		rval = EIO;
9504 	}
9505 
9506 mode_sense_failed:
9507 	if (rval != 0) {
9508 		kmem_free(*header, buflen);
9509 		*header = NULL;
9510 		*bdlen = 0;
9511 	}
9512 	return (rval);
9513 }
9514 
9515 /*
9516  *    Function: sd_cache_control()
9517  *
9518  * Description: This routine is the driver entry point for setting
9519  *		read and write caching by modifying the WCE (write cache
9520  *		enable) and RCD (read cache disable) bits of mode
9521  *		page 8 (MODEPAGE_CACHING).
9522  *
9523  *   Arguments: ssc		- ssc contains pointer to driver soft state
9524  *				  (unit) structure for this target.
9525  *		rcd_flag	- flag for controlling the read cache
9526  *		wce_flag	- flag for controlling the write cache
9527  *
9528  * Return Code: EIO
9529  *		code returned by sd_send_scsi_MODE_SENSE and
9530  *		sd_send_scsi_MODE_SELECT
9531  *
9532  *     Context: Kernel Thread
9533  */
9534 
9535 static int
9536 sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag)
9537 {
9538 	struct sd_lun	*un = ssc->ssc_un;
9539 	struct mode_caching *mode_caching_page;
9540 	uchar_t		*header;
9541 	size_t		buflen = SDC_BUFLEN(un);
9542 	int		hdrlen = SDC_HDRLEN(un);
9543 	int		bdlen;
9544 	int		rval;
9545 
9546 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CURRENT, &header, &bdlen);
9547 	switch (rval) {
9548 	case 0:
9549 		/* Check the relevant bits on successful mode sense */
9550 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9551 		    bdlen);
9552 		if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
9553 		    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
9554 		    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
9555 		    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
9556 			size_t sbuflen;
9557 			uchar_t save_pg;
9558 
9559 			/*
9560 			 * Construct select buffer length based on the
9561 			 * length of the sense data returned.
9562 			 */
9563 			sbuflen = hdrlen + bdlen + sizeof (struct mode_page) +
9564 			    (int)mode_caching_page->mode_page.length;
9565 
9566 			/* Set the caching bits as requested */
9567 			if (rcd_flag == SD_CACHE_ENABLE)
9568 				mode_caching_page->rcd = 0;
9569 			else if (rcd_flag == SD_CACHE_DISABLE)
9570 				mode_caching_page->rcd = 1;
9571 
9572 			if (wce_flag == SD_CACHE_ENABLE)
9573 				mode_caching_page->wce = 1;
9574 			else if (wce_flag == SD_CACHE_DISABLE)
9575 				mode_caching_page->wce = 0;
9576 
9577 			/*
9578 			 * Save the page if the mode sense says the
9579 			 * drive supports it.
9580 			 */
9581 			save_pg = mode_caching_page->mode_page.ps ?
9582 			    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
9583 
9584 			/* Clear reserved bits before mode select */
9585 			mode_caching_page->mode_page.ps = 0;
9586 
9587 			/*
9588 			 * Clear out mode header for mode select.
9589 			 * The rest of the retrieved page will be reused.
9590 			 */
9591 			bzero(header, hdrlen);
9592 
9593 			if (un->un_f_cfg_is_atapi == TRUE) {
9594 				struct mode_header_grp2 *mhp =
9595 				    (struct mode_header_grp2 *)header;
9596 				mhp->bdesc_length_hi = bdlen >> 8;
9597 				mhp->bdesc_length_lo = (uchar_t)bdlen & 0xff;
9598 			} else {
9599 				((struct mode_header *)header)->bdesc_length =
9600 				    bdlen;
9601 			}
9602 
9603 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9604 
9605 			/* Issue mode select to change the cache settings */
9606 			rval = sd_send_scsi_MODE_SELECT(ssc, SDC_CDB_GROUP(un),
9607 			    header, sbuflen, save_pg, SD_PATH_DIRECT);
9608 		}
9609 		kmem_free(header, buflen);
9610 		break;
9611 	case EIO:
9612 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9613 		break;
9614 	default:
9615 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9616 		break;
9617 	}
9618 
9619 	return (rval);
9620 }
9621 
9622 
9623 /*
9624  *    Function: sd_get_write_cache_enabled()
9625  *
9626  * Description: This routine is the driver entry point for determining if write
9627  *		caching is enabled.  It examines the WCE (write cache enable)
9628  *		bits of mode page 8 (MODEPAGE_CACHING) with Page Control field
9629  *		bits set to MODEPAGE_CURRENT.
9630  *
9631  *   Arguments: ssc		- ssc contains pointer to driver soft state
9632  *				  (unit) structure for this target.
9633  *		is_enabled	- pointer to int where write cache enabled state
9634  *				  is returned (non-zero -> write cache enabled)
9635  *
9636  * Return Code: EIO
9637  *		code returned by sd_send_scsi_MODE_SENSE
9638  *
9639  *     Context: Kernel Thread
9640  *
9641  * NOTE: If ioctl is added to disable write cache, this sequence should
9642  * be followed so that no locking is required for accesses to
9643  * un->un_f_write_cache_enabled:
9644  *	do mode select to clear wce
9645  *	do synchronize cache to flush cache
9646  *	set un->un_f_write_cache_enabled = FALSE
9647  *
9648  * Conversely, an ioctl to enable the write cache should be done
9649  * in this order:
9650  *	set un->un_f_write_cache_enabled = TRUE
9651  *	do mode select to set wce
9652  */
9653 
9654 static int
9655 sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled)
9656 {
9657 	struct sd_lun	*un = ssc->ssc_un;
9658 	struct mode_caching *mode_caching_page;
9659 	uchar_t		*header;
9660 	size_t		buflen = SDC_BUFLEN(un);
9661 	int		hdrlen = SDC_HDRLEN(un);
9662 	int		bdlen;
9663 	int		rval;
9664 
9665 	/* In case of error, flag as enabled */
9666 	*is_enabled = TRUE;
9667 
9668 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CURRENT, &header, &bdlen);
9669 	switch (rval) {
9670 	case 0:
9671 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9672 		    bdlen);
9673 		*is_enabled = mode_caching_page->wce;
9674 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9675 		kmem_free(header, buflen);
9676 		break;
9677 	case EIO: {
9678 		/*
9679 		 * Some disks do not support Mode Sense(6), we
9680 		 * should ignore this kind of error (sense key is
9681 		 * 0x5 - illegal request).
9682 		 */
9683 		uint8_t *sensep;
9684 		int senlen;
9685 
9686 		sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
9687 		senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
9688 		    ssc->ssc_uscsi_cmd->uscsi_rqresid);
9689 
9690 		if (senlen > 0 &&
9691 		    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
9692 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
9693 		} else {
9694 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9695 		}
9696 		break;
9697 	}
9698 	default:
9699 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9700 		break;
9701 	}
9702 
9703 	return (rval);
9704 }
9705 
9706 /*
9707  *    Function: sd_get_write_cache_changeable()
9708  *
9709  * Description: This routine is the driver entry point for determining if write
9710  *		caching is changeable.  It examines the WCE (write cache enable)
9711  *		bits of mode page 8 (MODEPAGE_CACHING) with Page Control field
9712  *		bits set to MODEPAGE_CHANGEABLE.
9713  *
9714  *   Arguments: ssc		- ssc contains pointer to driver soft state
9715  *				  (unit) structure for this target.
9716  *		is_changeable	- pointer to int where write cache changeable
9717  *				  state is returned (non-zero -> write cache
9718  *				  changeable)
9719  *
9720  *     Context: Kernel Thread
9721  */
9722 
9723 static void
9724 sd_get_write_cache_changeable(sd_ssc_t *ssc, int *is_changeable)
9725 {
9726 	struct sd_lun	*un = ssc->ssc_un;
9727 	struct mode_caching *mode_caching_page;
9728 	uchar_t		*header;
9729 	size_t		buflen = SDC_BUFLEN(un);
9730 	int		hdrlen = SDC_HDRLEN(un);
9731 	int		bdlen;
9732 	int		rval;
9733 
9734 	/* In case of error, flag as enabled */
9735 	*is_changeable = TRUE;
9736 
9737 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CHANGEABLE, &header,
9738 	    &bdlen);
9739 	switch (rval) {
9740 	case 0:
9741 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9742 		    bdlen);
9743 		*is_changeable = mode_caching_page->wce;
9744 		kmem_free(header, buflen);
9745 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9746 		break;
9747 	case EIO:
9748 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9749 		break;
9750 	default:
9751 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9752 		break;
9753 	}
9754 }
9755 
9756 /*
9757  *    Function: sd_get_nv_sup()
9758  *
9759  * Description: This routine is the driver entry point for
9760  * determining whether non-volatile cache is supported. This
9761  * determination process works as follows:
9762  *
9763  * 1. sd first queries sd.conf on whether
9764  * suppress_cache_flush bit is set for this device.
9765  *
9766  * 2. if not there, then queries the internal disk table.
9767  *
9768  * 3. if either sd.conf or internal disk table specifies
9769  * cache flush be suppressed, we don't bother checking
9770  * NV_SUP bit.
9771  *
9772  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
9773  * the optional INQUIRY VPD page 0x86. If the device
9774  * supports VPD page 0x86, sd examines the NV_SUP
9775  * (non-volatile cache support) bit in the INQUIRY VPD page
9776  * 0x86:
9777  *   o If NV_SUP bit is set, sd assumes the device has a
9778  *   non-volatile cache and set the
9779  *   un_f_sync_nv_supported to TRUE.
9780  *   o Otherwise cache is not non-volatile,
9781  *   un_f_sync_nv_supported is set to FALSE.
9782  *
9783  * Arguments: un - driver soft state (unit) structure
9784  *
9785  * Return Code:
9786  *
9787  *     Context: Kernel Thread
9788  */
9789 
9790 static void
9791 sd_get_nv_sup(sd_ssc_t *ssc)
9792 {
9793 	int		rval		= 0;
9794 	uchar_t		*inq86		= NULL;
9795 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
9796 	size_t		inq86_resid	= 0;
9797 	struct		dk_callback *dkc;
9798 	struct sd_lun	*un;
9799 
9800 	ASSERT(ssc != NULL);
9801 	un = ssc->ssc_un;
9802 	ASSERT(un != NULL);
9803 
9804 	mutex_enter(SD_MUTEX(un));
9805 
9806 	/*
9807 	 * Be conservative on the device's support of
9808 	 * SYNC_NV bit: un_f_sync_nv_supported is
9809 	 * initialized to be false.
9810 	 */
9811 	un->un_f_sync_nv_supported = FALSE;
9812 
9813 	/*
9814 	 * If either sd.conf or internal disk table
9815 	 * specifies cache flush be suppressed, then
9816 	 * we don't bother checking NV_SUP bit.
9817 	 */
9818 	if (un->un_f_suppress_cache_flush == TRUE) {
9819 		mutex_exit(SD_MUTEX(un));
9820 		return;
9821 	}
9822 
9823 	if (sd_check_vpd_page_support(ssc) == 0 &&
9824 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
9825 		mutex_exit(SD_MUTEX(un));
9826 		/* collect page 86 data if available */
9827 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
9828 
9829 		rval = sd_send_scsi_INQUIRY(ssc, inq86, inq86_len,
9830 		    0x01, 0x86, &inq86_resid);
9831 
9832 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
9833 			SD_TRACE(SD_LOG_COMMON, un,
9834 			    "sd_get_nv_sup: \
9835 			    successfully get VPD page: %x \
9836 			    PAGE LENGTH: %x BYTE 6: %x\n",
9837 			    inq86[1], inq86[3], inq86[6]);
9838 
9839 			mutex_enter(SD_MUTEX(un));
9840 			/*
9841 			 * check the value of NV_SUP bit: only if the device
9842 			 * reports NV_SUP bit to be 1, the
9843 			 * un_f_sync_nv_supported bit will be set to true.
9844 			 */
9845 			if (inq86[6] & SD_VPD_NV_SUP) {
9846 				un->un_f_sync_nv_supported = TRUE;
9847 			}
9848 			mutex_exit(SD_MUTEX(un));
9849 		} else if (rval != 0) {
9850 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9851 		}
9852 
9853 		kmem_free(inq86, inq86_len);
9854 	} else {
9855 		mutex_exit(SD_MUTEX(un));
9856 	}
9857 
9858 	/*
9859 	 * Send a SYNC CACHE command to check whether
9860 	 * SYNC_NV bit is supported. This command should have
9861 	 * un_f_sync_nv_supported set to correct value.
9862 	 */
9863 	mutex_enter(SD_MUTEX(un));
9864 	if (un->un_f_sync_nv_supported) {
9865 		mutex_exit(SD_MUTEX(un));
9866 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
9867 		dkc->dkc_flag = FLUSH_VOLATILE;
9868 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
9869 
9870 		/*
9871 		 * Send a TEST UNIT READY command to the device. This should
9872 		 * clear any outstanding UNIT ATTENTION that may be present.
9873 		 */
9874 		rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
9875 		if (rval != 0)
9876 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9877 
9878 		kmem_free(dkc, sizeof (struct dk_callback));
9879 	} else {
9880 		mutex_exit(SD_MUTEX(un));
9881 	}
9882 
9883 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
9884 	    un_f_suppress_cache_flush is set to %d\n",
9885 	    un->un_f_suppress_cache_flush);
9886 }
9887 
9888 /*
9889  *    Function: sd_make_device
9890  *
9891  * Description: Utility routine to return the Solaris device number from
9892  *		the data in the device's dev_info structure.
9893  *
9894  * Return Code: The Solaris device number
9895  *
9896  *     Context: Any
9897  */
9898 
9899 static dev_t
9900 sd_make_device(dev_info_t *devi)
9901 {
9902 	return (makedevice(ddi_driver_major(devi),
9903 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9904 }
9905 
9906 
9907 /*
9908  *    Function: sd_pm_entry
9909  *
9910  * Description: Called at the start of a new command to manage power
9911  *		and busy status of a device. This includes determining whether
9912  *		the current power state of the device is sufficient for
9913  *		performing the command or whether it must be changed.
9914  *		The PM framework is notified appropriately.
9915  *		Only with a return status of DDI_SUCCESS will the
9916  *		component be busy to the framework.
9917  *
9918  *		All callers of sd_pm_entry must check the return status
9919  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9920  *		of DDI_FAILURE indicates the device failed to power up.
9921  *		In this case un_pm_count has been adjusted so the result
9922  *		on exit is still powered down, ie. count is less than 0.
9923  *		Calling sd_pm_exit with this count value hits an ASSERT.
9924  *
9925  * Return Code: DDI_SUCCESS or DDI_FAILURE
9926  *
9927  *     Context: Kernel thread context.
9928  */
9929 
9930 static int
9931 sd_pm_entry(struct sd_lun *un)
9932 {
9933 	int return_status = DDI_SUCCESS;
9934 
9935 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9936 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9937 
9938 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9939 
9940 	if (un->un_f_pm_is_enabled == FALSE) {
9941 		SD_TRACE(SD_LOG_IO_PM, un,
9942 		    "sd_pm_entry: exiting, PM not enabled\n");
9943 		return (return_status);
9944 	}
9945 
9946 	/*
9947 	 * Just increment a counter if PM is enabled. On the transition from
9948 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9949 	 * the count with each IO and mark the device as idle when the count
9950 	 * hits 0.
9951 	 *
9952 	 * If the count is less than 0 the device is powered down. If a powered
9953 	 * down device is successfully powered up then the count must be
9954 	 * incremented to reflect the power up. Note that it'll get incremented
9955 	 * a second time to become busy.
9956 	 *
9957 	 * Because the following has the potential to change the device state
9958 	 * and must release the un_pm_mutex to do so, only one thread can be
9959 	 * allowed through at a time.
9960 	 */
9961 
9962 	mutex_enter(&un->un_pm_mutex);
9963 	while (un->un_pm_busy == TRUE) {
9964 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9965 	}
9966 	un->un_pm_busy = TRUE;
9967 
9968 	if (un->un_pm_count < 1) {
9969 
9970 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9971 
9972 		/*
9973 		 * Indicate we are now busy so the framework won't attempt to
9974 		 * power down the device. This call will only fail if either
9975 		 * we passed a bad component number or the device has no
9976 		 * components. Neither of these should ever happen.
9977 		 */
9978 		mutex_exit(&un->un_pm_mutex);
9979 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9980 		ASSERT(return_status == DDI_SUCCESS);
9981 
9982 		mutex_enter(&un->un_pm_mutex);
9983 
9984 		if (un->un_pm_count < 0) {
9985 			mutex_exit(&un->un_pm_mutex);
9986 
9987 			SD_TRACE(SD_LOG_IO_PM, un,
9988 			    "sd_pm_entry: power up component\n");
9989 
9990 			/*
9991 			 * pm_raise_power will cause sdpower to be called
9992 			 * which brings the device power level to the
9993 			 * desired state, If successful, un_pm_count and
9994 			 * un_power_level will be updated appropriately.
9995 			 */
9996 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9997 			    SD_PM_STATE_ACTIVE(un));
9998 
9999 			mutex_enter(&un->un_pm_mutex);
10000 
10001 			if (return_status != DDI_SUCCESS) {
10002 				/*
10003 				 * Power up failed.
10004 				 * Idle the device and adjust the count
10005 				 * so the result on exit is that we're
10006 				 * still powered down, ie. count is less than 0.
10007 				 */
10008 				SD_TRACE(SD_LOG_IO_PM, un,
10009 				    "sd_pm_entry: power up failed,"
10010 				    " idle the component\n");
10011 
10012 				(void) pm_idle_component(SD_DEVINFO(un), 0);
10013 				un->un_pm_count--;
10014 			} else {
10015 				/*
10016 				 * Device is powered up, verify the
10017 				 * count is non-negative.
10018 				 * This is debug only.
10019 				 */
10020 				ASSERT(un->un_pm_count == 0);
10021 			}
10022 		}
10023 
10024 		if (return_status == DDI_SUCCESS) {
10025 			/*
10026 			 * For performance, now that the device has been tagged
10027 			 * as busy, and it's known to be powered up, update the
10028 			 * chain types to use jump tables that do not include
10029 			 * pm. This significantly lowers the overhead and
10030 			 * therefore improves performance.
10031 			 */
10032 
10033 			mutex_exit(&un->un_pm_mutex);
10034 			mutex_enter(SD_MUTEX(un));
10035 			SD_TRACE(SD_LOG_IO_PM, un,
10036 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
10037 			    un->un_uscsi_chain_type);
10038 
10039 			if (un->un_f_non_devbsize_supported) {
10040 				un->un_buf_chain_type =
10041 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
10042 			} else {
10043 				un->un_buf_chain_type =
10044 				    SD_CHAIN_INFO_DISK_NO_PM;
10045 			}
10046 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
10047 
10048 			SD_TRACE(SD_LOG_IO_PM, un,
10049 			    "             changed  uscsi_chain_type to   %d\n",
10050 			    un->un_uscsi_chain_type);
10051 			mutex_exit(SD_MUTEX(un));
10052 			mutex_enter(&un->un_pm_mutex);
10053 
10054 			if (un->un_pm_idle_timeid == NULL) {
10055 				/* 300 ms. */
10056 				un->un_pm_idle_timeid =
10057 				    timeout(sd_pm_idletimeout_handler, un,
10058 				    (drv_usectohz((clock_t)300000)));
10059 				/*
10060 				 * Include an extra call to busy which keeps the
10061 				 * device busy with-respect-to the PM layer
10062 				 * until the timer fires, at which time it'll
10063 				 * get the extra idle call.
10064 				 */
10065 				(void) pm_busy_component(SD_DEVINFO(un), 0);
10066 			}
10067 		}
10068 	}
10069 	un->un_pm_busy = FALSE;
10070 	/* Next... */
10071 	cv_signal(&un->un_pm_busy_cv);
10072 
10073 	un->un_pm_count++;
10074 
10075 	SD_TRACE(SD_LOG_IO_PM, un,
10076 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
10077 
10078 	mutex_exit(&un->un_pm_mutex);
10079 
10080 	return (return_status);
10081 }
10082 
10083 
10084 /*
10085  *    Function: sd_pm_exit
10086  *
10087  * Description: Called at the completion of a command to manage busy
10088  *		status for the device. If the device becomes idle the
10089  *		PM framework is notified.
10090  *
10091  *     Context: Kernel thread context
10092  */
10093 
10094 static void
10095 sd_pm_exit(struct sd_lun *un)
10096 {
10097 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10098 	ASSERT(!mutex_owned(&un->un_pm_mutex));
10099 
10100 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
10101 
10102 	/*
10103 	 * After attach the following flag is only read, so don't
10104 	 * take the penalty of acquiring a mutex for it.
10105 	 */
10106 	if (un->un_f_pm_is_enabled == TRUE) {
10107 
10108 		mutex_enter(&un->un_pm_mutex);
10109 		un->un_pm_count--;
10110 
10111 		SD_TRACE(SD_LOG_IO_PM, un,
10112 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
10113 
10114 		ASSERT(un->un_pm_count >= 0);
10115 		if (un->un_pm_count == 0) {
10116 			mutex_exit(&un->un_pm_mutex);
10117 
10118 			SD_TRACE(SD_LOG_IO_PM, un,
10119 			    "sd_pm_exit: idle component\n");
10120 
10121 			(void) pm_idle_component(SD_DEVINFO(un), 0);
10122 
10123 		} else {
10124 			mutex_exit(&un->un_pm_mutex);
10125 		}
10126 	}
10127 
10128 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
10129 }
10130 
10131 
10132 /*
10133  *    Function: sdopen
10134  *
10135  * Description: Driver's open(9e) entry point function.
10136  *
10137  *   Arguments: dev_i   - pointer to device number
10138  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
10139  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10140  *		cred_p  - user credential pointer
10141  *
10142  * Return Code: EINVAL
10143  *		ENXIO
10144  *		EIO
10145  *		EROFS
10146  *		EBUSY
10147  *
10148  *     Context: Kernel thread context
10149  */
10150 /* ARGSUSED */
10151 static int
10152 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
10153 {
10154 	struct sd_lun	*un;
10155 	int		nodelay;
10156 	int		part;
10157 	uint64_t	partmask;
10158 	int		instance;
10159 	dev_t		dev;
10160 	int		rval = EIO;
10161 	diskaddr_t	nblks = 0;
10162 	diskaddr_t	label_cap;
10163 
10164 	/* Validate the open type */
10165 	if (otyp >= OTYPCNT) {
10166 		return (EINVAL);
10167 	}
10168 
10169 	dev = *dev_p;
10170 	instance = SDUNIT(dev);
10171 	mutex_enter(&sd_detach_mutex);
10172 
10173 	/*
10174 	 * Fail the open if there is no softstate for the instance, or
10175 	 * if another thread somewhere is trying to detach the instance.
10176 	 */
10177 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
10178 	    (un->un_detach_count != 0)) {
10179 		mutex_exit(&sd_detach_mutex);
10180 		/*
10181 		 * The probe cache only needs to be cleared when open (9e) fails
10182 		 * with ENXIO (4238046).
10183 		 */
10184 		/*
10185 		 * un-conditionally clearing probe cache is ok with
10186 		 * separate sd/ssd binaries
10187 		 * x86 platform can be an issue with both parallel
10188 		 * and fibre in 1 binary
10189 		 */
10190 		sd_scsi_clear_probe_cache();
10191 		return (ENXIO);
10192 	}
10193 
10194 	/*
10195 	 * The un_layer_count is to prevent another thread in specfs from
10196 	 * trying to detach the instance, which can happen when we are
10197 	 * called from a higher-layer driver instead of thru specfs.
10198 	 * This will not be needed when DDI provides a layered driver
10199 	 * interface that allows specfs to know that an instance is in
10200 	 * use by a layered driver & should not be detached.
10201 	 *
10202 	 * Note: the semantics for layered driver opens are exactly one
10203 	 * close for every open.
10204 	 */
10205 	if (otyp == OTYP_LYR) {
10206 		un->un_layer_count++;
10207 	}
10208 
10209 	/*
10210 	 * Keep a count of the current # of opens in progress. This is because
10211 	 * some layered drivers try to call us as a regular open. This can
10212 	 * cause problems that we cannot prevent, however by keeping this count
10213 	 * we can at least keep our open and detach routines from racing against
10214 	 * each other under such conditions.
10215 	 */
10216 	un->un_opens_in_progress++;
10217 	mutex_exit(&sd_detach_mutex);
10218 
10219 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
10220 	part	 = SDPART(dev);
10221 	partmask = 1 << part;
10222 
10223 	/*
10224 	 * We use a semaphore here in order to serialize
10225 	 * open and close requests on the device.
10226 	 */
10227 	sema_p(&un->un_semoclose);
10228 
10229 	mutex_enter(SD_MUTEX(un));
10230 
10231 	/*
10232 	 * All device accesses go thru sdstrategy() where we check
10233 	 * on suspend status but there could be a scsi_poll command,
10234 	 * which bypasses sdstrategy(), so we need to check pm
10235 	 * status.
10236 	 */
10237 
10238 	if (!nodelay) {
10239 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10240 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10241 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10242 		}
10243 
10244 		mutex_exit(SD_MUTEX(un));
10245 		if (sd_pm_entry(un) != DDI_SUCCESS) {
10246 			rval = EIO;
10247 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
10248 			    "sdopen: sd_pm_entry failed\n");
10249 			goto open_failed_with_pm;
10250 		}
10251 		mutex_enter(SD_MUTEX(un));
10252 	}
10253 
10254 	/* check for previous exclusive open */
10255 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
10256 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10257 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
10258 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
10259 
10260 	if (un->un_exclopen & (partmask)) {
10261 		goto excl_open_fail;
10262 	}
10263 
10264 	if (flag & FEXCL) {
10265 		int i;
10266 		if (un->un_ocmap.lyropen[part]) {
10267 			goto excl_open_fail;
10268 		}
10269 		for (i = 0; i < (OTYPCNT - 1); i++) {
10270 			if (un->un_ocmap.regopen[i] & (partmask)) {
10271 				goto excl_open_fail;
10272 			}
10273 		}
10274 	}
10275 
10276 	/*
10277 	 * Check the write permission if this is a removable media device,
10278 	 * NDELAY has not been set, and writable permission is requested.
10279 	 *
10280 	 * Note: If NDELAY was set and this is write-protected media the WRITE
10281 	 * attempt will fail with EIO as part of the I/O processing. This is a
10282 	 * more permissive implementation that allows the open to succeed and
10283 	 * WRITE attempts to fail when appropriate.
10284 	 */
10285 	if (un->un_f_chk_wp_open) {
10286 		if ((flag & FWRITE) && (!nodelay)) {
10287 			mutex_exit(SD_MUTEX(un));
10288 			/*
10289 			 * Defer the check for write permission on writable
10290 			 * DVD drive till sdstrategy and will not fail open even
10291 			 * if FWRITE is set as the device can be writable
10292 			 * depending upon the media and the media can change
10293 			 * after the call to open().
10294 			 */
10295 			if (un->un_f_dvdram_writable_device == FALSE) {
10296 				if (ISCD(un) || sr_check_wp(dev)) {
10297 				rval = EROFS;
10298 				mutex_enter(SD_MUTEX(un));
10299 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10300 				    "write to cd or write protected media\n");
10301 				goto open_fail;
10302 				}
10303 			}
10304 			mutex_enter(SD_MUTEX(un));
10305 		}
10306 	}
10307 
10308 	/*
10309 	 * If opening in NDELAY/NONBLOCK mode, just return.
10310 	 * Check if disk is ready and has a valid geometry later.
10311 	 */
10312 	if (!nodelay) {
10313 		sd_ssc_t	*ssc;
10314 
10315 		mutex_exit(SD_MUTEX(un));
10316 		ssc = sd_ssc_init(un);
10317 		rval = sd_ready_and_valid(ssc, part);
10318 		sd_ssc_fini(ssc);
10319 		mutex_enter(SD_MUTEX(un));
10320 		/*
10321 		 * Fail if device is not ready or if the number of disk
10322 		 * blocks is zero or negative for non CD devices.
10323 		 */
10324 
10325 		nblks = 0;
10326 
10327 		if (rval == SD_READY_VALID && (!ISCD(un))) {
10328 			/* if cmlb_partinfo fails, nblks remains 0 */
10329 			mutex_exit(SD_MUTEX(un));
10330 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
10331 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
10332 			mutex_enter(SD_MUTEX(un));
10333 		}
10334 
10335 		if ((rval != SD_READY_VALID) ||
10336 		    (!ISCD(un) && nblks <= 0)) {
10337 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
10338 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10339 			    "device not ready or invalid disk block value\n");
10340 			goto open_fail;
10341 		}
10342 #if defined(__x86)
10343 	} else {
10344 		uchar_t *cp;
10345 		/*
10346 		 * x86 requires special nodelay handling, so that p0 is
10347 		 * always defined and accessible.
10348 		 * Invalidate geometry only if device is not already open.
10349 		 */
10350 		cp = &un->un_ocmap.chkd[0];
10351 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10352 			if (*cp != (uchar_t)0) {
10353 				break;
10354 			}
10355 			cp++;
10356 		}
10357 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10358 			mutex_exit(SD_MUTEX(un));
10359 			cmlb_invalidate(un->un_cmlbhandle,
10360 			    (void *)SD_PATH_DIRECT);
10361 			mutex_enter(SD_MUTEX(un));
10362 		}
10363 
10364 #endif
10365 	}
10366 
10367 	if (otyp == OTYP_LYR) {
10368 		un->un_ocmap.lyropen[part]++;
10369 	} else {
10370 		un->un_ocmap.regopen[otyp] |= partmask;
10371 	}
10372 
10373 	/* Set up open and exclusive open flags */
10374 	if (flag & FEXCL) {
10375 		un->un_exclopen |= (partmask);
10376 	}
10377 
10378 	/*
10379 	 * If the lun is EFI labeled and lun capacity is greater than the
10380 	 * capacity contained in the label, log a sys-event to notify the
10381 	 * interested module.
10382 	 * To avoid an infinite loop of logging sys-event, we only log the
10383 	 * event when the lun is not opened in NDELAY mode. The event handler
10384 	 * should open the lun in NDELAY mode.
10385 	 */
10386 	if (!nodelay) {
10387 		mutex_exit(SD_MUTEX(un));
10388 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
10389 		    (void*)SD_PATH_DIRECT) == 0) {
10390 			mutex_enter(SD_MUTEX(un));
10391 			if (un->un_f_blockcount_is_valid &&
10392 			    un->un_blockcount > label_cap &&
10393 			    un->un_f_expnevent == B_FALSE) {
10394 				un->un_f_expnevent = B_TRUE;
10395 				mutex_exit(SD_MUTEX(un));
10396 				sd_log_lun_expansion_event(un,
10397 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
10398 				mutex_enter(SD_MUTEX(un));
10399 			}
10400 		} else {
10401 			mutex_enter(SD_MUTEX(un));
10402 		}
10403 	}
10404 
10405 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10406 	    "open of part %d type %d\n", part, otyp);
10407 
10408 	mutex_exit(SD_MUTEX(un));
10409 	if (!nodelay) {
10410 		sd_pm_exit(un);
10411 	}
10412 
10413 	sema_v(&un->un_semoclose);
10414 
10415 	mutex_enter(&sd_detach_mutex);
10416 	un->un_opens_in_progress--;
10417 	mutex_exit(&sd_detach_mutex);
10418 
10419 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
10420 	return (DDI_SUCCESS);
10421 
10422 excl_open_fail:
10423 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
10424 	rval = EBUSY;
10425 
10426 open_fail:
10427 	mutex_exit(SD_MUTEX(un));
10428 
10429 	/*
10430 	 * On a failed open we must exit the pm management.
10431 	 */
10432 	if (!nodelay) {
10433 		sd_pm_exit(un);
10434 	}
10435 open_failed_with_pm:
10436 	sema_v(&un->un_semoclose);
10437 
10438 	mutex_enter(&sd_detach_mutex);
10439 	un->un_opens_in_progress--;
10440 	if (otyp == OTYP_LYR) {
10441 		un->un_layer_count--;
10442 	}
10443 	mutex_exit(&sd_detach_mutex);
10444 
10445 	return (rval);
10446 }
10447 
10448 
10449 /*
10450  *    Function: sdclose
10451  *
10452  * Description: Driver's close(9e) entry point function.
10453  *
10454  *   Arguments: dev    - device number
10455  *		flag   - file status flag, informational only
10456  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10457  *		cred_p - user credential pointer
10458  *
10459  * Return Code: ENXIO
10460  *
10461  *     Context: Kernel thread context
10462  */
10463 /* ARGSUSED */
10464 static int
10465 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
10466 {
10467 	struct sd_lun	*un;
10468 	uchar_t		*cp;
10469 	int		part;
10470 	int		nodelay;
10471 	int		rval = 0;
10472 
10473 	/* Validate the open type */
10474 	if (otyp >= OTYPCNT) {
10475 		return (ENXIO);
10476 	}
10477 
10478 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10479 		return (ENXIO);
10480 	}
10481 
10482 	part = SDPART(dev);
10483 	nodelay = flag & (FNDELAY | FNONBLOCK);
10484 
10485 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10486 	    "sdclose: close of part %d type %d\n", part, otyp);
10487 
10488 	/*
10489 	 * We use a semaphore here in order to serialize
10490 	 * open and close requests on the device.
10491 	 */
10492 	sema_p(&un->un_semoclose);
10493 
10494 	mutex_enter(SD_MUTEX(un));
10495 
10496 	/* Don't proceed if power is being changed. */
10497 	while (un->un_state == SD_STATE_PM_CHANGING) {
10498 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10499 	}
10500 
10501 	if (un->un_exclopen & (1 << part)) {
10502 		un->un_exclopen &= ~(1 << part);
10503 	}
10504 
10505 	/* Update the open partition map */
10506 	if (otyp == OTYP_LYR) {
10507 		un->un_ocmap.lyropen[part] -= 1;
10508 	} else {
10509 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
10510 	}
10511 
10512 	cp = &un->un_ocmap.chkd[0];
10513 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10514 		if (*cp != '\0') {
10515 			break;
10516 		}
10517 		cp++;
10518 	}
10519 
10520 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10521 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
10522 
10523 		/*
10524 		 * We avoid persistance upon the last close, and set
10525 		 * the throttle back to the maximum.
10526 		 */
10527 		un->un_throttle = un->un_saved_throttle;
10528 
10529 		if (un->un_state == SD_STATE_OFFLINE) {
10530 			if (un->un_f_is_fibre == FALSE) {
10531 				scsi_log(SD_DEVINFO(un), sd_label,
10532 				    CE_WARN, "offline\n");
10533 			}
10534 			mutex_exit(SD_MUTEX(un));
10535 			cmlb_invalidate(un->un_cmlbhandle,
10536 			    (void *)SD_PATH_DIRECT);
10537 			mutex_enter(SD_MUTEX(un));
10538 
10539 		} else {
10540 			/*
10541 			 * Flush any outstanding writes in NVRAM cache.
10542 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10543 			 * cmd, it may not work for non-Pluto devices.
10544 			 * SYNCHRONIZE CACHE is not required for removables,
10545 			 * except DVD-RAM drives.
10546 			 *
10547 			 * Also note: because SYNCHRONIZE CACHE is currently
10548 			 * the only command issued here that requires the
10549 			 * drive be powered up, only do the power up before
10550 			 * sending the Sync Cache command. If additional
10551 			 * commands are added which require a powered up
10552 			 * drive, the following sequence may have to change.
10553 			 *
10554 			 * And finally, note that parallel SCSI on SPARC
10555 			 * only issues a Sync Cache to DVD-RAM, a newly
10556 			 * supported device.
10557 			 */
10558 #if defined(__x86)
10559 			if ((un->un_f_sync_cache_supported &&
10560 			    un->un_f_sync_cache_required) ||
10561 			    un->un_f_dvdram_writable_device == TRUE) {
10562 #else
10563 			if (un->un_f_dvdram_writable_device == TRUE) {
10564 #endif
10565 				mutex_exit(SD_MUTEX(un));
10566 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10567 					rval =
10568 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10569 					    NULL);
10570 					/* ignore error if not supported */
10571 					if (rval == ENOTSUP) {
10572 						rval = 0;
10573 					} else if (rval != 0) {
10574 						rval = EIO;
10575 					}
10576 					sd_pm_exit(un);
10577 				} else {
10578 					rval = EIO;
10579 				}
10580 				mutex_enter(SD_MUTEX(un));
10581 			}
10582 
10583 			/*
10584 			 * For devices which supports DOOR_LOCK, send an ALLOW
10585 			 * MEDIA REMOVAL command, but don't get upset if it
10586 			 * fails. We need to raise the power of the drive before
10587 			 * we can call sd_send_scsi_DOORLOCK()
10588 			 */
10589 			if (un->un_f_doorlock_supported) {
10590 				mutex_exit(SD_MUTEX(un));
10591 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10592 					sd_ssc_t	*ssc;
10593 
10594 					ssc = sd_ssc_init(un);
10595 					rval = sd_send_scsi_DOORLOCK(ssc,
10596 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10597 					if (rval != 0)
10598 						sd_ssc_assessment(ssc,
10599 						    SD_FMT_IGNORE);
10600 					sd_ssc_fini(ssc);
10601 
10602 					sd_pm_exit(un);
10603 					if (ISCD(un) && (rval != 0) &&
10604 					    (nodelay != 0)) {
10605 						rval = ENXIO;
10606 					}
10607 				} else {
10608 					rval = EIO;
10609 				}
10610 				mutex_enter(SD_MUTEX(un));
10611 			}
10612 
10613 			/*
10614 			 * If a device has removable media, invalidate all
10615 			 * parameters related to media, such as geometry,
10616 			 * blocksize, and blockcount.
10617 			 */
10618 			if (un->un_f_has_removable_media) {
10619 				sr_ejected(un);
10620 			}
10621 
10622 			/*
10623 			 * Destroy the cache (if it exists) which was
10624 			 * allocated for the write maps since this is
10625 			 * the last close for this media.
10626 			 */
10627 			if (un->un_wm_cache) {
10628 				/*
10629 				 * Check if there are pending commands.
10630 				 * and if there are give a warning and
10631 				 * do not destroy the cache.
10632 				 */
10633 				if (un->un_ncmds_in_driver > 0) {
10634 					scsi_log(SD_DEVINFO(un),
10635 					    sd_label, CE_WARN,
10636 					    "Unable to clean up memory "
10637 					    "because of pending I/O\n");
10638 				} else {
10639 					kmem_cache_destroy(
10640 					    un->un_wm_cache);
10641 					un->un_wm_cache = NULL;
10642 				}
10643 			}
10644 		}
10645 	}
10646 
10647 	mutex_exit(SD_MUTEX(un));
10648 	sema_v(&un->un_semoclose);
10649 
10650 	if (otyp == OTYP_LYR) {
10651 		mutex_enter(&sd_detach_mutex);
10652 		/*
10653 		 * The detach routine may run when the layer count
10654 		 * drops to zero.
10655 		 */
10656 		un->un_layer_count--;
10657 		mutex_exit(&sd_detach_mutex);
10658 	}
10659 
10660 	return (rval);
10661 }
10662 
10663 
10664 /*
10665  *    Function: sd_ready_and_valid
10666  *
10667  * Description: Test if device is ready and has a valid geometry.
10668  *
10669  *   Arguments: ssc - sd_ssc_t will contain un
10670  *		un  - driver soft state (unit) structure
10671  *
10672  * Return Code: SD_READY_VALID		ready and valid label
10673  *		SD_NOT_READY_VALID	not ready, no label
10674  *		SD_RESERVED_BY_OTHERS	reservation conflict
10675  *
10676  *     Context: Never called at interrupt context.
10677  */
10678 
10679 static int
10680 sd_ready_and_valid(sd_ssc_t *ssc, int part)
10681 {
10682 	struct sd_errstats	*stp;
10683 	uint64_t		capacity;
10684 	uint_t			lbasize;
10685 	int			rval = SD_READY_VALID;
10686 	char			name_str[48];
10687 	boolean_t		is_valid;
10688 	struct sd_lun		*un;
10689 	int			status;
10690 
10691 	ASSERT(ssc != NULL);
10692 	un = ssc->ssc_un;
10693 	ASSERT(un != NULL);
10694 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10695 
10696 	mutex_enter(SD_MUTEX(un));
10697 	/*
10698 	 * If a device has removable media, we must check if media is
10699 	 * ready when checking if this device is ready and valid.
10700 	 */
10701 	if (un->un_f_has_removable_media) {
10702 		mutex_exit(SD_MUTEX(un));
10703 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10704 
10705 		if (status != 0) {
10706 			rval = SD_NOT_READY_VALID;
10707 			mutex_enter(SD_MUTEX(un));
10708 
10709 			/* Ignore all failed status for removalbe media */
10710 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10711 
10712 			goto done;
10713 		}
10714 
10715 		is_valid = SD_IS_VALID_LABEL(un);
10716 		mutex_enter(SD_MUTEX(un));
10717 		if (!is_valid ||
10718 		    (un->un_f_blockcount_is_valid == FALSE) ||
10719 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10720 
10721 			/* capacity has to be read every open. */
10722 			mutex_exit(SD_MUTEX(un));
10723 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
10724 			    &lbasize, SD_PATH_DIRECT);
10725 
10726 			if (status != 0) {
10727 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10728 
10729 				cmlb_invalidate(un->un_cmlbhandle,
10730 				    (void *)SD_PATH_DIRECT);
10731 				mutex_enter(SD_MUTEX(un));
10732 				rval = SD_NOT_READY_VALID;
10733 
10734 				goto done;
10735 			} else {
10736 				mutex_enter(SD_MUTEX(un));
10737 				sd_update_block_info(un, lbasize, capacity);
10738 			}
10739 		}
10740 
10741 		/*
10742 		 * Check if the media in the device is writable or not.
10743 		 */
10744 		if (!is_valid && ISCD(un)) {
10745 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
10746 		}
10747 
10748 	} else {
10749 		/*
10750 		 * Do a test unit ready to clear any unit attention from non-cd
10751 		 * devices.
10752 		 */
10753 		mutex_exit(SD_MUTEX(un));
10754 
10755 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10756 		if (status != 0) {
10757 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10758 		}
10759 
10760 		mutex_enter(SD_MUTEX(un));
10761 	}
10762 
10763 
10764 	/*
10765 	 * If this is a non 512 block device, allocate space for
10766 	 * the wmap cache. This is being done here since every time
10767 	 * a media is changed this routine will be called and the
10768 	 * block size is a function of media rather than device.
10769 	 */
10770 	if (((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR ||
10771 	    un->un_f_non_devbsize_supported) &&
10772 	    un->un_tgt_blocksize != DEV_BSIZE) ||
10773 	    un->un_f_enable_rmw) {
10774 		if (!(un->un_wm_cache)) {
10775 			(void) snprintf(name_str, sizeof (name_str),
10776 			    "%s%d_cache",
10777 			    ddi_driver_name(SD_DEVINFO(un)),
10778 			    ddi_get_instance(SD_DEVINFO(un)));
10779 			un->un_wm_cache = kmem_cache_create(
10780 			    name_str, sizeof (struct sd_w_map),
10781 			    8, sd_wm_cache_constructor,
10782 			    sd_wm_cache_destructor, NULL,
10783 			    (void *)un, NULL, 0);
10784 			if (!(un->un_wm_cache)) {
10785 				rval = ENOMEM;
10786 				goto done;
10787 			}
10788 		}
10789 	}
10790 
10791 	if (un->un_state == SD_STATE_NORMAL) {
10792 		/*
10793 		 * If the target is not yet ready here (defined by a TUR
10794 		 * failure), invalidate the geometry and print an 'offline'
10795 		 * message. This is a legacy message, as the state of the
10796 		 * target is not actually changed to SD_STATE_OFFLINE.
10797 		 *
10798 		 * If the TUR fails for EACCES (Reservation Conflict),
10799 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
10800 		 * reservation conflict. If the TUR fails for other
10801 		 * reasons, SD_NOT_READY_VALID will be returned.
10802 		 */
10803 		int err;
10804 
10805 		mutex_exit(SD_MUTEX(un));
10806 		err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10807 		mutex_enter(SD_MUTEX(un));
10808 
10809 		if (err != 0) {
10810 			mutex_exit(SD_MUTEX(un));
10811 			cmlb_invalidate(un->un_cmlbhandle,
10812 			    (void *)SD_PATH_DIRECT);
10813 			mutex_enter(SD_MUTEX(un));
10814 			if (err == EACCES) {
10815 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10816 				    "reservation conflict\n");
10817 				rval = SD_RESERVED_BY_OTHERS;
10818 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10819 			} else {
10820 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10821 				    "drive offline\n");
10822 				rval = SD_NOT_READY_VALID;
10823 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
10824 			}
10825 			goto done;
10826 		}
10827 	}
10828 
10829 	if (un->un_f_format_in_progress == FALSE) {
10830 		mutex_exit(SD_MUTEX(un));
10831 
10832 		(void) cmlb_validate(un->un_cmlbhandle, 0,
10833 		    (void *)SD_PATH_DIRECT);
10834 		if (cmlb_partinfo(un->un_cmlbhandle, part, NULL, NULL, NULL,
10835 		    NULL, (void *) SD_PATH_DIRECT) != 0) {
10836 			rval = SD_NOT_READY_VALID;
10837 			mutex_enter(SD_MUTEX(un));
10838 
10839 			goto done;
10840 		}
10841 		if (un->un_f_pkstats_enabled) {
10842 			sd_set_pstats(un);
10843 			SD_TRACE(SD_LOG_IO_PARTITION, un,
10844 			    "sd_ready_and_valid: un:0x%p pstats created and "
10845 			    "set\n", un);
10846 		}
10847 		mutex_enter(SD_MUTEX(un));
10848 	}
10849 
10850 	/*
10851 	 * If this device supports DOOR_LOCK command, try and send
10852 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10853 	 * if it fails. For a CD, however, it is an error
10854 	 */
10855 	if (un->un_f_doorlock_supported) {
10856 		mutex_exit(SD_MUTEX(un));
10857 		status = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
10858 		    SD_PATH_DIRECT);
10859 
10860 		if ((status != 0) && ISCD(un)) {
10861 			rval = SD_NOT_READY_VALID;
10862 			mutex_enter(SD_MUTEX(un));
10863 
10864 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10865 
10866 			goto done;
10867 		} else if (status != 0)
10868 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10869 		mutex_enter(SD_MUTEX(un));
10870 	}
10871 
10872 	/* The state has changed, inform the media watch routines */
10873 	un->un_mediastate = DKIO_INSERTED;
10874 	cv_broadcast(&un->un_state_cv);
10875 	rval = SD_READY_VALID;
10876 
10877 done:
10878 
10879 	/*
10880 	 * Initialize the capacity kstat value, if no media previously
10881 	 * (capacity kstat is 0) and a media has been inserted
10882 	 * (un_blockcount > 0).
10883 	 */
10884 	if (un->un_errstats != NULL) {
10885 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10886 		if ((stp->sd_capacity.value.ui64 == 0) &&
10887 		    (un->un_f_blockcount_is_valid == TRUE)) {
10888 			stp->sd_capacity.value.ui64 =
10889 			    (uint64_t)((uint64_t)un->un_blockcount *
10890 			    un->un_sys_blocksize);
10891 		}
10892 	}
10893 
10894 	mutex_exit(SD_MUTEX(un));
10895 	return (rval);
10896 }
10897 
10898 
10899 /*
10900  *    Function: sdmin
10901  *
10902  * Description: Routine to limit the size of a data transfer. Used in
10903  *		conjunction with physio(9F).
10904  *
10905  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10906  *
10907  *     Context: Kernel thread context.
10908  */
10909 
10910 static void
10911 sdmin(struct buf *bp)
10912 {
10913 	struct sd_lun	*un;
10914 	int		instance;
10915 
10916 	instance = SDUNIT(bp->b_edev);
10917 
10918 	un = ddi_get_soft_state(sd_state, instance);
10919 	ASSERT(un != NULL);
10920 
10921 	/*
10922 	 * We depend on buf breakup to restrict
10923 	 * IO size if it is enabled.
10924 	 */
10925 	if (un->un_buf_breakup_supported) {
10926 		return;
10927 	}
10928 
10929 	if (bp->b_bcount > un->un_max_xfer_size) {
10930 		bp->b_bcount = un->un_max_xfer_size;
10931 	}
10932 }
10933 
10934 
10935 /*
10936  *    Function: sdread
10937  *
10938  * Description: Driver's read(9e) entry point function.
10939  *
10940  *   Arguments: dev   - device number
10941  *		uio   - structure pointer describing where data is to be stored
10942  *			in user's space
10943  *		cred_p  - user credential pointer
10944  *
10945  * Return Code: ENXIO
10946  *		EIO
10947  *		EINVAL
10948  *		value returned by physio
10949  *
10950  *     Context: Kernel thread context.
10951  */
10952 /* ARGSUSED */
10953 static int
10954 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10955 {
10956 	struct sd_lun	*un = NULL;
10957 	int		secmask;
10958 	int		err = 0;
10959 	sd_ssc_t	*ssc;
10960 
10961 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10962 		return (ENXIO);
10963 	}
10964 
10965 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10966 
10967 
10968 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10969 		mutex_enter(SD_MUTEX(un));
10970 		/*
10971 		 * Because the call to sd_ready_and_valid will issue I/O we
10972 		 * must wait here if either the device is suspended or
10973 		 * if it's power level is changing.
10974 		 */
10975 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10976 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10977 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10978 		}
10979 		un->un_ncmds_in_driver++;
10980 		mutex_exit(SD_MUTEX(un));
10981 
10982 		/* Initialize sd_ssc_t for internal uscsi commands */
10983 		ssc = sd_ssc_init(un);
10984 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10985 			err = EIO;
10986 		} else {
10987 			err = 0;
10988 		}
10989 		sd_ssc_fini(ssc);
10990 
10991 		mutex_enter(SD_MUTEX(un));
10992 		un->un_ncmds_in_driver--;
10993 		ASSERT(un->un_ncmds_in_driver >= 0);
10994 		mutex_exit(SD_MUTEX(un));
10995 		if (err != 0)
10996 			return (err);
10997 	}
10998 
10999 	/*
11000 	 * Read requests are restricted to multiples of the system block size.
11001 	 */
11002 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11003 	    !un->un_f_enable_rmw)
11004 		secmask = un->un_tgt_blocksize - 1;
11005 	else
11006 		secmask = DEV_BSIZE - 1;
11007 
11008 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11009 		SD_ERROR(SD_LOG_READ_WRITE, un,
11010 		    "sdread: file offset not modulo %d\n",
11011 		    secmask + 1);
11012 		err = EINVAL;
11013 	} else if (uio->uio_iov->iov_len & (secmask)) {
11014 		SD_ERROR(SD_LOG_READ_WRITE, un,
11015 		    "sdread: transfer length not modulo %d\n",
11016 		    secmask + 1);
11017 		err = EINVAL;
11018 	} else {
11019 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
11020 	}
11021 
11022 	return (err);
11023 }
11024 
11025 
11026 /*
11027  *    Function: sdwrite
11028  *
11029  * Description: Driver's write(9e) entry point function.
11030  *
11031  *   Arguments: dev   - device number
11032  *		uio   - structure pointer describing where data is stored in
11033  *			user's space
11034  *		cred_p  - user credential pointer
11035  *
11036  * Return Code: ENXIO
11037  *		EIO
11038  *		EINVAL
11039  *		value returned by physio
11040  *
11041  *     Context: Kernel thread context.
11042  */
11043 /* ARGSUSED */
11044 static int
11045 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
11046 {
11047 	struct sd_lun	*un = NULL;
11048 	int		secmask;
11049 	int		err = 0;
11050 	sd_ssc_t	*ssc;
11051 
11052 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11053 		return (ENXIO);
11054 	}
11055 
11056 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11057 
11058 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11059 		mutex_enter(SD_MUTEX(un));
11060 		/*
11061 		 * Because the call to sd_ready_and_valid will issue I/O we
11062 		 * must wait here if either the device is suspended or
11063 		 * if it's power level is changing.
11064 		 */
11065 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11066 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11067 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11068 		}
11069 		un->un_ncmds_in_driver++;
11070 		mutex_exit(SD_MUTEX(un));
11071 
11072 		/* Initialize sd_ssc_t for internal uscsi commands */
11073 		ssc = sd_ssc_init(un);
11074 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11075 			err = EIO;
11076 		} else {
11077 			err = 0;
11078 		}
11079 		sd_ssc_fini(ssc);
11080 
11081 		mutex_enter(SD_MUTEX(un));
11082 		un->un_ncmds_in_driver--;
11083 		ASSERT(un->un_ncmds_in_driver >= 0);
11084 		mutex_exit(SD_MUTEX(un));
11085 		if (err != 0)
11086 			return (err);
11087 	}
11088 
11089 	/*
11090 	 * Write requests are restricted to multiples of the system block size.
11091 	 */
11092 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11093 	    !un->un_f_enable_rmw)
11094 		secmask = un->un_tgt_blocksize - 1;
11095 	else
11096 		secmask = DEV_BSIZE - 1;
11097 
11098 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11099 		SD_ERROR(SD_LOG_READ_WRITE, un,
11100 		    "sdwrite: file offset not modulo %d\n",
11101 		    secmask + 1);
11102 		err = EINVAL;
11103 	} else if (uio->uio_iov->iov_len & (secmask)) {
11104 		SD_ERROR(SD_LOG_READ_WRITE, un,
11105 		    "sdwrite: transfer length not modulo %d\n",
11106 		    secmask + 1);
11107 		err = EINVAL;
11108 	} else {
11109 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
11110 	}
11111 
11112 	return (err);
11113 }
11114 
11115 
11116 /*
11117  *    Function: sdaread
11118  *
11119  * Description: Driver's aread(9e) entry point function.
11120  *
11121  *   Arguments: dev   - device number
11122  *		aio   - structure pointer describing where data is to be stored
11123  *		cred_p  - user credential pointer
11124  *
11125  * Return Code: ENXIO
11126  *		EIO
11127  *		EINVAL
11128  *		value returned by aphysio
11129  *
11130  *     Context: Kernel thread context.
11131  */
11132 /* ARGSUSED */
11133 static int
11134 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11135 {
11136 	struct sd_lun	*un = NULL;
11137 	struct uio	*uio = aio->aio_uio;
11138 	int		secmask;
11139 	int		err = 0;
11140 	sd_ssc_t	*ssc;
11141 
11142 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11143 		return (ENXIO);
11144 	}
11145 
11146 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11147 
11148 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11149 		mutex_enter(SD_MUTEX(un));
11150 		/*
11151 		 * Because the call to sd_ready_and_valid will issue I/O we
11152 		 * must wait here if either the device is suspended or
11153 		 * if it's power level is changing.
11154 		 */
11155 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11156 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11157 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11158 		}
11159 		un->un_ncmds_in_driver++;
11160 		mutex_exit(SD_MUTEX(un));
11161 
11162 		/* Initialize sd_ssc_t for internal uscsi commands */
11163 		ssc = sd_ssc_init(un);
11164 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11165 			err = EIO;
11166 		} else {
11167 			err = 0;
11168 		}
11169 		sd_ssc_fini(ssc);
11170 
11171 		mutex_enter(SD_MUTEX(un));
11172 		un->un_ncmds_in_driver--;
11173 		ASSERT(un->un_ncmds_in_driver >= 0);
11174 		mutex_exit(SD_MUTEX(un));
11175 		if (err != 0)
11176 			return (err);
11177 	}
11178 
11179 	/*
11180 	 * Read requests are restricted to multiples of the system block size.
11181 	 */
11182 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11183 	    !un->un_f_enable_rmw)
11184 		secmask = un->un_tgt_blocksize - 1;
11185 	else
11186 		secmask = DEV_BSIZE - 1;
11187 
11188 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11189 		SD_ERROR(SD_LOG_READ_WRITE, un,
11190 		    "sdaread: file offset not modulo %d\n",
11191 		    secmask + 1);
11192 		err = EINVAL;
11193 	} else if (uio->uio_iov->iov_len & (secmask)) {
11194 		SD_ERROR(SD_LOG_READ_WRITE, un,
11195 		    "sdaread: transfer length not modulo %d\n",
11196 		    secmask + 1);
11197 		err = EINVAL;
11198 	} else {
11199 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
11200 	}
11201 
11202 	return (err);
11203 }
11204 
11205 
11206 /*
11207  *    Function: sdawrite
11208  *
11209  * Description: Driver's awrite(9e) entry point function.
11210  *
11211  *   Arguments: dev   - device number
11212  *		aio   - structure pointer describing where data is stored
11213  *		cred_p  - user credential pointer
11214  *
11215  * Return Code: ENXIO
11216  *		EIO
11217  *		EINVAL
11218  *		value returned by aphysio
11219  *
11220  *     Context: Kernel thread context.
11221  */
11222 /* ARGSUSED */
11223 static int
11224 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11225 {
11226 	struct sd_lun	*un = NULL;
11227 	struct uio	*uio = aio->aio_uio;
11228 	int		secmask;
11229 	int		err = 0;
11230 	sd_ssc_t	*ssc;
11231 
11232 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11233 		return (ENXIO);
11234 	}
11235 
11236 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11237 
11238 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11239 		mutex_enter(SD_MUTEX(un));
11240 		/*
11241 		 * Because the call to sd_ready_and_valid will issue I/O we
11242 		 * must wait here if either the device is suspended or
11243 		 * if it's power level is changing.
11244 		 */
11245 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11246 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11247 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11248 		}
11249 		un->un_ncmds_in_driver++;
11250 		mutex_exit(SD_MUTEX(un));
11251 
11252 		/* Initialize sd_ssc_t for internal uscsi commands */
11253 		ssc = sd_ssc_init(un);
11254 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11255 			err = EIO;
11256 		} else {
11257 			err = 0;
11258 		}
11259 		sd_ssc_fini(ssc);
11260 
11261 		mutex_enter(SD_MUTEX(un));
11262 		un->un_ncmds_in_driver--;
11263 		ASSERT(un->un_ncmds_in_driver >= 0);
11264 		mutex_exit(SD_MUTEX(un));
11265 		if (err != 0)
11266 			return (err);
11267 	}
11268 
11269 	/*
11270 	 * Write requests are restricted to multiples of the system block size.
11271 	 */
11272 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11273 	    !un->un_f_enable_rmw)
11274 		secmask = un->un_tgt_blocksize - 1;
11275 	else
11276 		secmask = DEV_BSIZE - 1;
11277 
11278 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11279 		SD_ERROR(SD_LOG_READ_WRITE, un,
11280 		    "sdawrite: file offset not modulo %d\n",
11281 		    secmask + 1);
11282 		err = EINVAL;
11283 	} else if (uio->uio_iov->iov_len & (secmask)) {
11284 		SD_ERROR(SD_LOG_READ_WRITE, un,
11285 		    "sdawrite: transfer length not modulo %d\n",
11286 		    secmask + 1);
11287 		err = EINVAL;
11288 	} else {
11289 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
11290 	}
11291 
11292 	return (err);
11293 }
11294 
11295 
11296 
11297 
11298 
11299 /*
11300  * Driver IO processing follows the following sequence:
11301  *
11302  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
11303  *         |                |                     ^
11304  *         v                v                     |
11305  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
11306  *         |                |                     |                   |
11307  *         v                |                     |                   |
11308  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
11309  *         |                |                     ^                   ^
11310  *         v                v                     |                   |
11311  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
11312  *         |                |                     |                   |
11313  *     +---+                |                     +------------+      +-------+
11314  *     |                    |                                  |              |
11315  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11316  *     |                    v                                  |              |
11317  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
11318  *     |                    |                                  ^              |
11319  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11320  *     |                    v                                  |              |
11321  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
11322  *     |                    |                                  ^              |
11323  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11324  *     |                    v                                  |              |
11325  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
11326  *     |                    |                                  ^              |
11327  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
11328  *     |                    v                                  |              |
11329  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
11330  *     |                    |                                  ^              |
11331  *     |                    |                                  |              |
11332  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
11333  *                          |                           ^
11334  *                          v                           |
11335  *                   sd_core_iostart()                  |
11336  *                          |                           |
11337  *                          |                           +------>(*destroypkt)()
11338  *                          +-> sd_start_cmds() <-+     |           |
11339  *                          |                     |     |           v
11340  *                          |                     |     |  scsi_destroy_pkt(9F)
11341  *                          |                     |     |
11342  *                          +->(*initpkt)()       +- sdintr()
11343  *                          |  |                        |  |
11344  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
11345  *                          |  +-> scsi_setup_cdb(9F)   |
11346  *                          |                           |
11347  *                          +--> scsi_transport(9F)     |
11348  *                                     |                |
11349  *                                     +----> SCSA ---->+
11350  *
11351  *
11352  * This code is based upon the following presumptions:
11353  *
11354  *   - iostart and iodone functions operate on buf(9S) structures. These
11355  *     functions perform the necessary operations on the buf(9S) and pass
11356  *     them along to the next function in the chain by using the macros
11357  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
11358  *     (for iodone side functions).
11359  *
11360  *   - The iostart side functions may sleep. The iodone side functions
11361  *     are called under interrupt context and may NOT sleep. Therefore
11362  *     iodone side functions also may not call iostart side functions.
11363  *     (NOTE: iostart side functions should NOT sleep for memory, as
11364  *     this could result in deadlock.)
11365  *
11366  *   - An iostart side function may call its corresponding iodone side
11367  *     function directly (if necessary).
11368  *
11369  *   - In the event of an error, an iostart side function can return a buf(9S)
11370  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
11371  *     b_error in the usual way of course).
11372  *
11373  *   - The taskq mechanism may be used by the iodone side functions to dispatch
11374  *     requests to the iostart side functions.  The iostart side functions in
11375  *     this case would be called under the context of a taskq thread, so it's
11376  *     OK for them to block/sleep/spin in this case.
11377  *
11378  *   - iostart side functions may allocate "shadow" buf(9S) structs and
11379  *     pass them along to the next function in the chain.  The corresponding
11380  *     iodone side functions must coalesce the "shadow" bufs and return
11381  *     the "original" buf to the next higher layer.
11382  *
11383  *   - The b_private field of the buf(9S) struct holds a pointer to
11384  *     an sd_xbuf struct, which contains information needed to
11385  *     construct the scsi_pkt for the command.
11386  *
11387  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
11388  *     layer must acquire & release the SD_MUTEX(un) as needed.
11389  */
11390 
11391 
11392 /*
11393  * Create taskq for all targets in the system. This is created at
11394  * _init(9E) and destroyed at _fini(9E).
11395  *
11396  * Note: here we set the minalloc to a reasonably high number to ensure that
11397  * we will have an adequate supply of task entries available at interrupt time.
11398  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
11399  * sd_create_taskq().  Since we do not want to sleep for allocations at
11400  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
11401  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
11402  * requests any one instant in time.
11403  */
11404 #define	SD_TASKQ_NUMTHREADS	8
11405 #define	SD_TASKQ_MINALLOC	256
11406 #define	SD_TASKQ_MAXALLOC	256
11407 
11408 static taskq_t	*sd_tq = NULL;
11409 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
11410 
11411 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
11412 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
11413 
11414 /*
11415  * The following task queue is being created for the write part of
11416  * read-modify-write of non-512 block size devices.
11417  * Limit the number of threads to 1 for now. This number has been chosen
11418  * considering the fact that it applies only to dvd ram drives/MO drives
11419  * currently. Performance for which is not main criteria at this stage.
11420  * Note: It needs to be explored if we can use a single taskq in future
11421  */
11422 #define	SD_WMR_TASKQ_NUMTHREADS	1
11423 static taskq_t	*sd_wmr_tq = NULL;
11424 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
11425 
11426 /*
11427  *    Function: sd_taskq_create
11428  *
11429  * Description: Create taskq thread(s) and preallocate task entries
11430  *
11431  * Return Code: Returns a pointer to the allocated taskq_t.
11432  *
11433  *     Context: Can sleep. Requires blockable context.
11434  *
11435  *       Notes: - The taskq() facility currently is NOT part of the DDI.
11436  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
11437  *		- taskq_create() will block for memory, also it will panic
11438  *		  if it cannot create the requested number of threads.
11439  *		- Currently taskq_create() creates threads that cannot be
11440  *		  swapped.
11441  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
11442  *		  supply of taskq entries at interrupt time (ie, so that we
11443  *		  do not have to sleep for memory)
11444  */
11445 
11446 static void
11447 sd_taskq_create(void)
11448 {
11449 	char	taskq_name[TASKQ_NAMELEN];
11450 
11451 	ASSERT(sd_tq == NULL);
11452 	ASSERT(sd_wmr_tq == NULL);
11453 
11454 	(void) snprintf(taskq_name, sizeof (taskq_name),
11455 	    "%s_drv_taskq", sd_label);
11456 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
11457 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11458 	    TASKQ_PREPOPULATE));
11459 
11460 	(void) snprintf(taskq_name, sizeof (taskq_name),
11461 	    "%s_rmw_taskq", sd_label);
11462 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
11463 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11464 	    TASKQ_PREPOPULATE));
11465 }
11466 
11467 
11468 /*
11469  *    Function: sd_taskq_delete
11470  *
11471  * Description: Complementary cleanup routine for sd_taskq_create().
11472  *
11473  *     Context: Kernel thread context.
11474  */
11475 
11476 static void
11477 sd_taskq_delete(void)
11478 {
11479 	ASSERT(sd_tq != NULL);
11480 	ASSERT(sd_wmr_tq != NULL);
11481 	taskq_destroy(sd_tq);
11482 	taskq_destroy(sd_wmr_tq);
11483 	sd_tq = NULL;
11484 	sd_wmr_tq = NULL;
11485 }
11486 
11487 
11488 /*
11489  *    Function: sdstrategy
11490  *
11491  * Description: Driver's strategy (9E) entry point function.
11492  *
11493  *   Arguments: bp - pointer to buf(9S)
11494  *
11495  * Return Code: Always returns zero
11496  *
11497  *     Context: Kernel thread context.
11498  */
11499 
11500 static int
11501 sdstrategy(struct buf *bp)
11502 {
11503 	struct sd_lun *un;
11504 
11505 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11506 	if (un == NULL) {
11507 		bioerror(bp, EIO);
11508 		bp->b_resid = bp->b_bcount;
11509 		biodone(bp);
11510 		return (0);
11511 	}
11512 
11513 	/* As was done in the past, fail new cmds. if state is dumping. */
11514 	if (un->un_state == SD_STATE_DUMPING) {
11515 		bioerror(bp, ENXIO);
11516 		bp->b_resid = bp->b_bcount;
11517 		biodone(bp);
11518 		return (0);
11519 	}
11520 
11521 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11522 
11523 	/*
11524 	 * Commands may sneak in while we released the mutex in
11525 	 * DDI_SUSPEND, we should block new commands. However, old
11526 	 * commands that are still in the driver at this point should
11527 	 * still be allowed to drain.
11528 	 */
11529 	mutex_enter(SD_MUTEX(un));
11530 	/*
11531 	 * Must wait here if either the device is suspended or
11532 	 * if it's power level is changing.
11533 	 */
11534 	while ((un->un_state == SD_STATE_SUSPENDED) ||
11535 	    (un->un_state == SD_STATE_PM_CHANGING)) {
11536 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11537 	}
11538 
11539 	un->un_ncmds_in_driver++;
11540 
11541 	/*
11542 	 * atapi: Since we are running the CD for now in PIO mode we need to
11543 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11544 	 * the HBA's init_pkt routine.
11545 	 */
11546 	if (un->un_f_cfg_is_atapi == TRUE) {
11547 		mutex_exit(SD_MUTEX(un));
11548 		bp_mapin(bp);
11549 		mutex_enter(SD_MUTEX(un));
11550 	}
11551 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
11552 	    un->un_ncmds_in_driver);
11553 
11554 	if (bp->b_flags & B_WRITE)
11555 		un->un_f_sync_cache_required = TRUE;
11556 
11557 	mutex_exit(SD_MUTEX(un));
11558 
11559 	/*
11560 	 * This will (eventually) allocate the sd_xbuf area and
11561 	 * call sd_xbuf_strategy().  We just want to return the
11562 	 * result of ddi_xbuf_qstrategy so that we have an opt-
11563 	 * imized tail call which saves us a stack frame.
11564 	 */
11565 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
11566 }
11567 
11568 
11569 /*
11570  *    Function: sd_xbuf_strategy
11571  *
11572  * Description: Function for initiating IO operations via the
11573  *		ddi_xbuf_qstrategy() mechanism.
11574  *
11575  *     Context: Kernel thread context.
11576  */
11577 
11578 static void
11579 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11580 {
11581 	struct sd_lun *un = arg;
11582 
11583 	ASSERT(bp != NULL);
11584 	ASSERT(xp != NULL);
11585 	ASSERT(un != NULL);
11586 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11587 
11588 	/*
11589 	 * Initialize the fields in the xbuf and save a pointer to the
11590 	 * xbuf in bp->b_private.
11591 	 */
11592 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11593 
11594 	/* Send the buf down the iostart chain */
11595 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11596 }
11597 
11598 
11599 /*
11600  *    Function: sd_xbuf_init
11601  *
11602  * Description: Prepare the given sd_xbuf struct for use.
11603  *
11604  *   Arguments: un - ptr to softstate
11605  *		bp - ptr to associated buf(9S)
11606  *		xp - ptr to associated sd_xbuf
11607  *		chain_type - IO chain type to use:
11608  *			SD_CHAIN_NULL
11609  *			SD_CHAIN_BUFIO
11610  *			SD_CHAIN_USCSI
11611  *			SD_CHAIN_DIRECT
11612  *			SD_CHAIN_DIRECT_PRIORITY
11613  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11614  *			initialization; may be NULL if none.
11615  *
11616  *     Context: Kernel thread context
11617  */
11618 
11619 static void
11620 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11621     uchar_t chain_type, void *pktinfop)
11622 {
11623 	int index;
11624 
11625 	ASSERT(un != NULL);
11626 	ASSERT(bp != NULL);
11627 	ASSERT(xp != NULL);
11628 
11629 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11630 	    bp, chain_type);
11631 
11632 	xp->xb_un	= un;
11633 	xp->xb_pktp	= NULL;
11634 	xp->xb_pktinfo	= pktinfop;
11635 	xp->xb_private	= bp->b_private;
11636 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11637 
11638 	/*
11639 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11640 	 * upon the specified chain type to use.
11641 	 */
11642 	switch (chain_type) {
11643 	case SD_CHAIN_NULL:
11644 		/*
11645 		 * Fall thru to just use the values for the buf type, even
11646 		 * tho for the NULL chain these values will never be used.
11647 		 */
11648 		/* FALLTHRU */
11649 	case SD_CHAIN_BUFIO:
11650 		index = un->un_buf_chain_type;
11651 		if ((!un->un_f_has_removable_media) &&
11652 		    (un->un_tgt_blocksize != 0) &&
11653 		    (un->un_tgt_blocksize != DEV_BSIZE ||
11654 		    un->un_f_enable_rmw)) {
11655 			int secmask = 0, blknomask = 0;
11656 			if (un->un_f_enable_rmw) {
11657 				blknomask =
11658 				    (un->un_phy_blocksize / DEV_BSIZE) - 1;
11659 				secmask = un->un_phy_blocksize - 1;
11660 			} else {
11661 				blknomask =
11662 				    (un->un_tgt_blocksize / DEV_BSIZE) - 1;
11663 				secmask = un->un_tgt_blocksize - 1;
11664 			}
11665 
11666 			if ((bp->b_lblkno & (blknomask)) ||
11667 			    (bp->b_bcount & (secmask))) {
11668 				if ((un->un_f_rmw_type !=
11669 				    SD_RMW_TYPE_RETURN_ERROR) ||
11670 				    un->un_f_enable_rmw) {
11671 					if (un->un_f_pm_is_enabled == FALSE)
11672 						index =
11673 						    SD_CHAIN_INFO_MSS_DSK_NO_PM;
11674 					else
11675 						index =
11676 						    SD_CHAIN_INFO_MSS_DISK;
11677 				}
11678 			}
11679 		}
11680 		break;
11681 	case SD_CHAIN_USCSI:
11682 		index = un->un_uscsi_chain_type;
11683 		break;
11684 	case SD_CHAIN_DIRECT:
11685 		index = un->un_direct_chain_type;
11686 		break;
11687 	case SD_CHAIN_DIRECT_PRIORITY:
11688 		index = un->un_priority_chain_type;
11689 		break;
11690 	default:
11691 		/* We're really broken if we ever get here... */
11692 		panic("sd_xbuf_init: illegal chain type!");
11693 		/*NOTREACHED*/
11694 	}
11695 
11696 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11697 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11698 
11699 	/*
11700 	 * It might be a bit easier to simply bzero the entire xbuf above,
11701 	 * but it turns out that since we init a fair number of members anyway,
11702 	 * we save a fair number cycles by doing explicit assignment of zero.
11703 	 */
11704 	xp->xb_pkt_flags	= 0;
11705 	xp->xb_dma_resid	= 0;
11706 	xp->xb_retry_count	= 0;
11707 	xp->xb_victim_retry_count = 0;
11708 	xp->xb_ua_retry_count	= 0;
11709 	xp->xb_nr_retry_count	= 0;
11710 	xp->xb_sense_bp		= NULL;
11711 	xp->xb_sense_status	= 0;
11712 	xp->xb_sense_state	= 0;
11713 	xp->xb_sense_resid	= 0;
11714 	xp->xb_ena		= 0;
11715 
11716 	bp->b_private	= xp;
11717 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11718 	bp->b_resid	= 0;
11719 	bp->av_forw	= NULL;
11720 	bp->av_back	= NULL;
11721 	bioerror(bp, 0);
11722 
11723 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11724 }
11725 
11726 
11727 /*
11728  *    Function: sd_uscsi_strategy
11729  *
11730  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11731  *
11732  *   Arguments: bp - buf struct ptr
11733  *
11734  * Return Code: Always returns 0
11735  *
11736  *     Context: Kernel thread context
11737  */
11738 
11739 static int
11740 sd_uscsi_strategy(struct buf *bp)
11741 {
11742 	struct sd_lun		*un;
11743 	struct sd_uscsi_info	*uip;
11744 	struct sd_xbuf		*xp;
11745 	uchar_t			chain_type;
11746 	uchar_t			cmd;
11747 
11748 	ASSERT(bp != NULL);
11749 
11750 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11751 	if (un == NULL) {
11752 		bioerror(bp, EIO);
11753 		bp->b_resid = bp->b_bcount;
11754 		biodone(bp);
11755 		return (0);
11756 	}
11757 
11758 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11759 
11760 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11761 
11762 	/*
11763 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11764 	 */
11765 	ASSERT(bp->b_private != NULL);
11766 	uip = (struct sd_uscsi_info *)bp->b_private;
11767 	cmd = ((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_cdb[0];
11768 
11769 	mutex_enter(SD_MUTEX(un));
11770 	/*
11771 	 * atapi: Since we are running the CD for now in PIO mode we need to
11772 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11773 	 * the HBA's init_pkt routine.
11774 	 */
11775 	if (un->un_f_cfg_is_atapi == TRUE) {
11776 		mutex_exit(SD_MUTEX(un));
11777 		bp_mapin(bp);
11778 		mutex_enter(SD_MUTEX(un));
11779 	}
11780 	un->un_ncmds_in_driver++;
11781 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11782 	    un->un_ncmds_in_driver);
11783 
11784 	if ((bp->b_flags & B_WRITE) && (bp->b_bcount != 0) &&
11785 	    (cmd != SCMD_MODE_SELECT) && (cmd != SCMD_MODE_SELECT_G1))
11786 		un->un_f_sync_cache_required = TRUE;
11787 
11788 	mutex_exit(SD_MUTEX(un));
11789 
11790 	switch (uip->ui_flags) {
11791 	case SD_PATH_DIRECT:
11792 		chain_type = SD_CHAIN_DIRECT;
11793 		break;
11794 	case SD_PATH_DIRECT_PRIORITY:
11795 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11796 		break;
11797 	default:
11798 		chain_type = SD_CHAIN_USCSI;
11799 		break;
11800 	}
11801 
11802 	/*
11803 	 * We may allocate extra buf for external USCSI commands. If the
11804 	 * application asks for bigger than 20-byte sense data via USCSI,
11805 	 * SCSA layer will allocate 252 bytes sense buf for that command.
11806 	 */
11807 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
11808 	    SENSE_LENGTH) {
11809 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
11810 		    MAX_SENSE_LENGTH, KM_SLEEP);
11811 	} else {
11812 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
11813 	}
11814 
11815 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11816 
11817 	/* Use the index obtained within xbuf_init */
11818 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11819 
11820 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11821 
11822 	return (0);
11823 }
11824 
11825 /*
11826  *    Function: sd_send_scsi_cmd
11827  *
11828  * Description: Runs a USCSI command for user (when called thru sdioctl),
11829  *		or for the driver
11830  *
11831  *   Arguments: dev - the dev_t for the device
11832  *		incmd - ptr to a valid uscsi_cmd struct
11833  *		flag - bit flag, indicating open settings, 32/64 bit type
11834  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11835  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11836  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11837  *			to use the USCSI "direct" chain and bypass the normal
11838  *			command waitq.
11839  *
11840  * Return Code: 0 -  successful completion of the given command
11841  *		EIO - scsi_uscsi_handle_command() failed
11842  *		ENXIO  - soft state not found for specified dev
11843  *		EINVAL
11844  *		EFAULT - copyin/copyout error
11845  *		return code of scsi_uscsi_handle_command():
11846  *			EIO
11847  *			ENXIO
11848  *			EACCES
11849  *
11850  *     Context: Waits for command to complete. Can sleep.
11851  */
11852 
11853 static int
11854 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
11855     enum uio_seg dataspace, int path_flag)
11856 {
11857 	struct sd_lun	*un;
11858 	sd_ssc_t	*ssc;
11859 	int		rval;
11860 
11861 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11862 	if (un == NULL) {
11863 		return (ENXIO);
11864 	}
11865 
11866 	/*
11867 	 * Using sd_ssc_send to handle uscsi cmd
11868 	 */
11869 	ssc = sd_ssc_init(un);
11870 	rval = sd_ssc_send(ssc, incmd, flag, dataspace, path_flag);
11871 	sd_ssc_fini(ssc);
11872 
11873 	return (rval);
11874 }
11875 
11876 /*
11877  *    Function: sd_ssc_init
11878  *
11879  * Description: Uscsi end-user call this function to initialize necessary
11880  *              fields, such as uscsi_cmd and sd_uscsi_info struct.
11881  *
11882  *              The return value of sd_send_scsi_cmd will be treated as a
11883  *              fault in various conditions. Even it is not Zero, some
11884  *              callers may ignore the return value. That is to say, we can
11885  *              not make an accurate assessment in sdintr, since if a
11886  *              command is failed in sdintr it does not mean the caller of
11887  *              sd_send_scsi_cmd will treat it as a real failure.
11888  *
11889  *              To avoid printing too many error logs for a failed uscsi
11890  *              packet that the caller may not treat it as a failure, the
11891  *              sd will keep silent for handling all uscsi commands.
11892  *
11893  *              During detach->attach and attach-open, for some types of
11894  *              problems, the driver should be providing information about
11895  *              the problem encountered. Device use USCSI_SILENT, which
11896  *              suppresses all driver information. The result is that no
11897  *              information about the problem is available. Being
11898  *              completely silent during this time is inappropriate. The
11899  *              driver needs a more selective filter than USCSI_SILENT, so
11900  *              that information related to faults is provided.
11901  *
11902  *              To make the accurate accessment, the caller  of
11903  *              sd_send_scsi_USCSI_CMD should take the ownership and
11904  *              get necessary information to print error messages.
11905  *
11906  *              If we want to print necessary info of uscsi command, we need to
11907  *              keep the uscsi_cmd and sd_uscsi_info till we can make the
11908  *              assessment. We use sd_ssc_init to alloc necessary
11909  *              structs for sending an uscsi command and we are also
11910  *              responsible for free the memory by calling
11911  *              sd_ssc_fini.
11912  *
11913  *              The calling secquences will look like:
11914  *              sd_ssc_init->
11915  *
11916  *                  ...
11917  *
11918  *                  sd_send_scsi_USCSI_CMD->
11919  *                      sd_ssc_send-> - - - sdintr
11920  *                  ...
11921  *
11922  *                  if we think the return value should be treated as a
11923  *                  failure, we make the accessment here and print out
11924  *                  necessary by retrieving uscsi_cmd and sd_uscsi_info'
11925  *
11926  *                  ...
11927  *
11928  *              sd_ssc_fini
11929  *
11930  *
11931  *   Arguments: un - pointer to driver soft state (unit) structure for this
11932  *                   target.
11933  *
11934  * Return code: sd_ssc_t - pointer to allocated sd_ssc_t struct, it contains
11935  *                         uscsi_cmd and sd_uscsi_info.
11936  *                  NULL - if can not alloc memory for sd_ssc_t struct
11937  *
11938  *     Context: Kernel Thread.
11939  */
11940 static sd_ssc_t *
11941 sd_ssc_init(struct sd_lun *un)
11942 {
11943 	sd_ssc_t		*ssc;
11944 	struct uscsi_cmd	*ucmdp;
11945 	struct sd_uscsi_info	*uip;
11946 
11947 	ASSERT(un != NULL);
11948 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11949 
11950 	/*
11951 	 * Allocate sd_ssc_t structure
11952 	 */
11953 	ssc = kmem_zalloc(sizeof (sd_ssc_t), KM_SLEEP);
11954 
11955 	/*
11956 	 * Allocate uscsi_cmd by calling scsi_uscsi_alloc common routine
11957 	 */
11958 	ucmdp = scsi_uscsi_alloc();
11959 
11960 	/*
11961 	 * Allocate sd_uscsi_info structure
11962 	 */
11963 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11964 
11965 	ssc->ssc_uscsi_cmd = ucmdp;
11966 	ssc->ssc_uscsi_info = uip;
11967 	ssc->ssc_un = un;
11968 
11969 	return (ssc);
11970 }
11971 
11972 /*
11973  * Function: sd_ssc_fini
11974  *
11975  * Description: To free sd_ssc_t and it's hanging off
11976  *
11977  * Arguments: ssc - struct pointer of sd_ssc_t.
11978  */
11979 static void
11980 sd_ssc_fini(sd_ssc_t *ssc)
11981 {
11982 	scsi_uscsi_free(ssc->ssc_uscsi_cmd);
11983 
11984 	if (ssc->ssc_uscsi_info != NULL) {
11985 		kmem_free(ssc->ssc_uscsi_info, sizeof (struct sd_uscsi_info));
11986 		ssc->ssc_uscsi_info = NULL;
11987 	}
11988 
11989 	kmem_free(ssc, sizeof (sd_ssc_t));
11990 	ssc = NULL;
11991 }
11992 
11993 /*
11994  * Function: sd_ssc_send
11995  *
11996  * Description: Runs a USCSI command for user when called through sdioctl,
11997  *              or for the driver.
11998  *
11999  *   Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12000  *                    sd_uscsi_info in.
12001  *		incmd - ptr to a valid uscsi_cmd struct
12002  *		flag - bit flag, indicating open settings, 32/64 bit type
12003  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
12004  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
12005  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
12006  *			to use the USCSI "direct" chain and bypass the normal
12007  *			command waitq.
12008  *
12009  * Return Code: 0 -  successful completion of the given command
12010  *		EIO - scsi_uscsi_handle_command() failed
12011  *		ENXIO  - soft state not found for specified dev
12012  *		ECANCELED - command cancelled due to low power
12013  *		EINVAL
12014  *		EFAULT - copyin/copyout error
12015  *		return code of scsi_uscsi_handle_command():
12016  *			EIO
12017  *			ENXIO
12018  *			EACCES
12019  *
12020  *     Context: Kernel Thread;
12021  *              Waits for command to complete. Can sleep.
12022  */
12023 static int
12024 sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd, int flag,
12025     enum uio_seg dataspace, int path_flag)
12026 {
12027 	struct sd_uscsi_info	*uip;
12028 	struct uscsi_cmd	*uscmd;
12029 	struct sd_lun		*un;
12030 	dev_t			dev;
12031 
12032 	int	format = 0;
12033 	int	rval;
12034 
12035 	ASSERT(ssc != NULL);
12036 	un = ssc->ssc_un;
12037 	ASSERT(un != NULL);
12038 	uscmd = ssc->ssc_uscsi_cmd;
12039 	ASSERT(uscmd != NULL);
12040 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12041 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
12042 		/*
12043 		 * If enter here, it indicates that the previous uscsi
12044 		 * command has not been processed by sd_ssc_assessment.
12045 		 * This is violating our rules of FMA telemetry processing.
12046 		 * We should print out this message and the last undisposed
12047 		 * uscsi command.
12048 		 */
12049 		if (uscmd->uscsi_cdb != NULL) {
12050 			SD_INFO(SD_LOG_SDTEST, un,
12051 			    "sd_ssc_send is missing the alternative "
12052 			    "sd_ssc_assessment when running command 0x%x.\n",
12053 			    uscmd->uscsi_cdb[0]);
12054 		}
12055 		/*
12056 		 * Set the ssc_flags to SSC_FLAGS_UNKNOWN, which should be
12057 		 * the initial status.
12058 		 */
12059 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12060 	}
12061 
12062 	/*
12063 	 * We need to make sure sd_ssc_send will have sd_ssc_assessment
12064 	 * followed to avoid missing FMA telemetries.
12065 	 */
12066 	ssc->ssc_flags |= SSC_FLAGS_NEED_ASSESSMENT;
12067 
12068 	/*
12069 	 * if USCSI_PMFAILFAST is set and un is in low power, fail the
12070 	 * command immediately.
12071 	 */
12072 	mutex_enter(SD_MUTEX(un));
12073 	mutex_enter(&un->un_pm_mutex);
12074 	if ((uscmd->uscsi_flags & USCSI_PMFAILFAST) &&
12075 	    SD_DEVICE_IS_IN_LOW_POWER(un)) {
12076 		SD_TRACE(SD_LOG_IO, un, "sd_ssc_send:"
12077 		    "un:0x%p is in low power\n", un);
12078 		mutex_exit(&un->un_pm_mutex);
12079 		mutex_exit(SD_MUTEX(un));
12080 		return (ECANCELED);
12081 	}
12082 	mutex_exit(&un->un_pm_mutex);
12083 	mutex_exit(SD_MUTEX(un));
12084 
12085 #ifdef SDDEBUG
12086 	switch (dataspace) {
12087 	case UIO_USERSPACE:
12088 		SD_TRACE(SD_LOG_IO, un,
12089 		    "sd_ssc_send: entry: un:0x%p UIO_USERSPACE\n", un);
12090 		break;
12091 	case UIO_SYSSPACE:
12092 		SD_TRACE(SD_LOG_IO, un,
12093 		    "sd_ssc_send: entry: un:0x%p UIO_SYSSPACE\n", un);
12094 		break;
12095 	default:
12096 		SD_TRACE(SD_LOG_IO, un,
12097 		    "sd_ssc_send: entry: un:0x%p UNEXPECTED SPACE\n", un);
12098 		break;
12099 	}
12100 #endif
12101 
12102 	rval = scsi_uscsi_copyin((intptr_t)incmd, flag,
12103 	    SD_ADDRESS(un), &uscmd);
12104 	if (rval != 0) {
12105 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
12106 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
12107 		return (rval);
12108 	}
12109 
12110 	if ((uscmd->uscsi_cdb != NULL) &&
12111 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
12112 		mutex_enter(SD_MUTEX(un));
12113 		un->un_f_format_in_progress = TRUE;
12114 		mutex_exit(SD_MUTEX(un));
12115 		format = 1;
12116 	}
12117 
12118 	/*
12119 	 * Allocate an sd_uscsi_info struct and fill it with the info
12120 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
12121 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
12122 	 * since we allocate the buf here in this function, we do not
12123 	 * need to preserve the prior contents of b_private.
12124 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
12125 	 */
12126 	uip = ssc->ssc_uscsi_info;
12127 	uip->ui_flags = path_flag;
12128 	uip->ui_cmdp = uscmd;
12129 
12130 	/*
12131 	 * Commands sent with priority are intended for error recovery
12132 	 * situations, and do not have retries performed.
12133 	 */
12134 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
12135 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
12136 	}
12137 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
12138 
12139 	dev = SD_GET_DEV(un);
12140 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
12141 	    sd_uscsi_strategy, NULL, uip);
12142 
12143 	/*
12144 	 * mark ssc_flags right after handle_cmd to make sure
12145 	 * the uscsi has been sent
12146 	 */
12147 	ssc->ssc_flags |= SSC_FLAGS_CMD_ISSUED;
12148 
12149 #ifdef SDDEBUG
12150 	SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
12151 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
12152 	    uscmd->uscsi_status, uscmd->uscsi_resid);
12153 	if (uscmd->uscsi_bufaddr != NULL) {
12154 		SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
12155 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
12156 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
12157 		if (dataspace == UIO_SYSSPACE) {
12158 			SD_DUMP_MEMORY(un, SD_LOG_IO,
12159 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
12160 			    uscmd->uscsi_buflen, SD_LOG_HEX);
12161 		}
12162 	}
12163 #endif
12164 
12165 	if (format == 1) {
12166 		mutex_enter(SD_MUTEX(un));
12167 		un->un_f_format_in_progress = FALSE;
12168 		mutex_exit(SD_MUTEX(un));
12169 	}
12170 
12171 	(void) scsi_uscsi_copyout((intptr_t)incmd, uscmd);
12172 
12173 	return (rval);
12174 }
12175 
12176 /*
12177  *     Function: sd_ssc_print
12178  *
12179  * Description: Print information available to the console.
12180  *
12181  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12182  *                    sd_uscsi_info in.
12183  *            sd_severity - log level.
12184  *     Context: Kernel thread or interrupt context.
12185  */
12186 static void
12187 sd_ssc_print(sd_ssc_t *ssc, int sd_severity)
12188 {
12189 	struct uscsi_cmd	*ucmdp;
12190 	struct scsi_device	*devp;
12191 	dev_info_t		*devinfo;
12192 	uchar_t			*sensep;
12193 	int			senlen;
12194 	union scsi_cdb		*cdbp;
12195 	uchar_t			com;
12196 	extern struct scsi_key_strings scsi_cmds[];
12197 
12198 	ASSERT(ssc != NULL);
12199 	ASSERT(ssc->ssc_un != NULL);
12200 
12201 	if (SD_FM_LOG(ssc->ssc_un) != SD_FM_LOG_EREPORT)
12202 		return;
12203 	ucmdp = ssc->ssc_uscsi_cmd;
12204 	devp = SD_SCSI_DEVP(ssc->ssc_un);
12205 	devinfo = SD_DEVINFO(ssc->ssc_un);
12206 	ASSERT(ucmdp != NULL);
12207 	ASSERT(devp != NULL);
12208 	ASSERT(devinfo != NULL);
12209 	sensep = (uint8_t *)ucmdp->uscsi_rqbuf;
12210 	senlen = ucmdp->uscsi_rqlen - ucmdp->uscsi_rqresid;
12211 	cdbp = (union scsi_cdb *)ucmdp->uscsi_cdb;
12212 
12213 	/* In certain case (like DOORLOCK), the cdb could be NULL. */
12214 	if (cdbp == NULL)
12215 		return;
12216 	/* We don't print log if no sense data available. */
12217 	if (senlen == 0)
12218 		sensep = NULL;
12219 	com = cdbp->scc_cmd;
12220 	scsi_generic_errmsg(devp, sd_label, sd_severity, 0, 0, com,
12221 	    scsi_cmds, sensep, ssc->ssc_un->un_additional_codes, NULL);
12222 }
12223 
12224 /*
12225  *     Function: sd_ssc_assessment
12226  *
12227  * Description: We use this function to make an assessment at the point
12228  *              where SD driver may encounter a potential error.
12229  *
12230  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12231  *                  sd_uscsi_info in.
12232  *            tp_assess - a hint of strategy for ereport posting.
12233  *            Possible values of tp_assess include:
12234  *                SD_FMT_IGNORE - we don't post any ereport because we're
12235  *                sure that it is ok to ignore the underlying problems.
12236  *                SD_FMT_IGNORE_COMPROMISE - we don't post any ereport for now
12237  *                but it might be not correct to ignore the underlying hardware
12238  *                error.
12239  *                SD_FMT_STATUS_CHECK - we will post an ereport with the
12240  *                payload driver-assessment of value "fail" or
12241  *                "fatal"(depending on what information we have here). This
12242  *                assessment value is usually set when SD driver think there
12243  *                is a potential error occurred(Typically, when return value
12244  *                of the SCSI command is EIO).
12245  *                SD_FMT_STANDARD - we will post an ereport with the payload
12246  *                driver-assessment of value "info". This assessment value is
12247  *                set when the SCSI command returned successfully and with
12248  *                sense data sent back.
12249  *
12250  *     Context: Kernel thread.
12251  */
12252 static void
12253 sd_ssc_assessment(sd_ssc_t *ssc, enum sd_type_assessment tp_assess)
12254 {
12255 	int senlen = 0;
12256 	struct uscsi_cmd *ucmdp = NULL;
12257 	struct sd_lun *un;
12258 
12259 	ASSERT(ssc != NULL);
12260 	un = ssc->ssc_un;
12261 	ASSERT(un != NULL);
12262 	ucmdp = ssc->ssc_uscsi_cmd;
12263 	ASSERT(ucmdp != NULL);
12264 
12265 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
12266 		ssc->ssc_flags &= ~SSC_FLAGS_NEED_ASSESSMENT;
12267 	} else {
12268 		/*
12269 		 * If enter here, it indicates that we have a wrong
12270 		 * calling sequence of sd_ssc_send and sd_ssc_assessment,
12271 		 * both of which should be called in a pair in case of
12272 		 * loss of FMA telemetries.
12273 		 */
12274 		if (ucmdp->uscsi_cdb != NULL) {
12275 			SD_INFO(SD_LOG_SDTEST, un,
12276 			    "sd_ssc_assessment is missing the "
12277 			    "alternative sd_ssc_send when running 0x%x, "
12278 			    "or there are superfluous sd_ssc_assessment for "
12279 			    "the same sd_ssc_send.\n",
12280 			    ucmdp->uscsi_cdb[0]);
12281 		}
12282 		/*
12283 		 * Set the ssc_flags to the initial value to avoid passing
12284 		 * down dirty flags to the following sd_ssc_send function.
12285 		 */
12286 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12287 		return;
12288 	}
12289 
12290 	/*
12291 	 * Only handle an issued command which is waiting for assessment.
12292 	 * A command which is not issued will not have
12293 	 * SSC_FLAGS_INVALID_DATA set, so it'ok we just return here.
12294 	 */
12295 	if (!(ssc->ssc_flags & SSC_FLAGS_CMD_ISSUED)) {
12296 		sd_ssc_print(ssc, SCSI_ERR_INFO);
12297 		return;
12298 	} else {
12299 		/*
12300 		 * For an issued command, we should clear this flag in
12301 		 * order to make the sd_ssc_t structure be used off
12302 		 * multiple uscsi commands.
12303 		 */
12304 		ssc->ssc_flags &= ~SSC_FLAGS_CMD_ISSUED;
12305 	}
12306 
12307 	/*
12308 	 * We will not deal with non-retryable(flag USCSI_DIAGNOSE set)
12309 	 * commands here. And we should clear the ssc_flags before return.
12310 	 */
12311 	if (ucmdp->uscsi_flags & USCSI_DIAGNOSE) {
12312 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12313 		return;
12314 	}
12315 
12316 	switch (tp_assess) {
12317 	case SD_FMT_IGNORE:
12318 	case SD_FMT_IGNORE_COMPROMISE:
12319 		break;
12320 	case SD_FMT_STATUS_CHECK:
12321 		/*
12322 		 * For a failed command(including the succeeded command
12323 		 * with invalid data sent back).
12324 		 */
12325 		sd_ssc_post(ssc, SD_FM_DRV_FATAL);
12326 		break;
12327 	case SD_FMT_STANDARD:
12328 		/*
12329 		 * Always for the succeeded commands probably with sense
12330 		 * data sent back.
12331 		 * Limitation:
12332 		 *	We can only handle a succeeded command with sense
12333 		 *	data sent back when auto-request-sense is enabled.
12334 		 */
12335 		senlen = ssc->ssc_uscsi_cmd->uscsi_rqlen -
12336 		    ssc->ssc_uscsi_cmd->uscsi_rqresid;
12337 		if ((ssc->ssc_uscsi_info->ui_pkt_state & STATE_ARQ_DONE) &&
12338 		    (un->un_f_arq_enabled == TRUE) &&
12339 		    senlen > 0 &&
12340 		    ssc->ssc_uscsi_cmd->uscsi_rqbuf != NULL) {
12341 			sd_ssc_post(ssc, SD_FM_DRV_NOTICE);
12342 		}
12343 		break;
12344 	default:
12345 		/*
12346 		 * Should not have other type of assessment.
12347 		 */
12348 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
12349 		    "sd_ssc_assessment got wrong "
12350 		    "sd_type_assessment %d.\n", tp_assess);
12351 		break;
12352 	}
12353 	/*
12354 	 * Clear up the ssc_flags before return.
12355 	 */
12356 	ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12357 }
12358 
12359 /*
12360  *    Function: sd_ssc_post
12361  *
12362  * Description: 1. read the driver property to get fm-scsi-log flag.
12363  *              2. print log if fm_log_capable is non-zero.
12364  *              3. call sd_ssc_ereport_post to post ereport if possible.
12365  *
12366  *    Context: May be called from kernel thread or interrupt context.
12367  */
12368 static void
12369 sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess)
12370 {
12371 	struct sd_lun	*un;
12372 	int		sd_severity;
12373 
12374 	ASSERT(ssc != NULL);
12375 	un = ssc->ssc_un;
12376 	ASSERT(un != NULL);
12377 
12378 	/*
12379 	 * We may enter here from sd_ssc_assessment(for USCSI command) or
12380 	 * by directly called from sdintr context.
12381 	 * We don't handle a non-disk drive(CD-ROM, removable media).
12382 	 * Clear the ssc_flags before return in case we've set
12383 	 * SSC_FLAGS_INVALID_XXX which should be skipped for a non-disk
12384 	 * driver.
12385 	 */
12386 	if (ISCD(un) || un->un_f_has_removable_media) {
12387 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12388 		return;
12389 	}
12390 
12391 	switch (sd_assess) {
12392 		case SD_FM_DRV_FATAL:
12393 			sd_severity = SCSI_ERR_FATAL;
12394 			break;
12395 		case SD_FM_DRV_RECOVERY:
12396 			sd_severity = SCSI_ERR_RECOVERED;
12397 			break;
12398 		case SD_FM_DRV_RETRY:
12399 			sd_severity = SCSI_ERR_RETRYABLE;
12400 			break;
12401 		case SD_FM_DRV_NOTICE:
12402 			sd_severity = SCSI_ERR_INFO;
12403 			break;
12404 		default:
12405 			sd_severity = SCSI_ERR_UNKNOWN;
12406 	}
12407 	/* print log */
12408 	sd_ssc_print(ssc, sd_severity);
12409 
12410 	/* always post ereport */
12411 	sd_ssc_ereport_post(ssc, sd_assess);
12412 }
12413 
12414 /*
12415  *    Function: sd_ssc_set_info
12416  *
12417  * Description: Mark ssc_flags and set ssc_info which would be the
12418  *              payload of uderr ereport. This function will cause
12419  *              sd_ssc_ereport_post to post uderr ereport only.
12420  *              Besides, when ssc_flags == SSC_FLAGS_INVALID_DATA(USCSI),
12421  *              the function will also call SD_ERROR or scsi_log for a
12422  *              CDROM/removable-media/DDI_FM_NOT_CAPABLE device.
12423  *
12424  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12425  *                  sd_uscsi_info in.
12426  *            ssc_flags - indicate the sub-category of a uderr.
12427  *            comp - this argument is meaningful only when
12428  *                   ssc_flags == SSC_FLAGS_INVALID_DATA, and its possible
12429  *                   values include:
12430  *                   > 0, SD_ERROR is used with comp as the driver logging
12431  *                   component;
12432  *                   = 0, scsi-log is used to log error telemetries;
12433  *                   < 0, no log available for this telemetry.
12434  *
12435  *    Context: Kernel thread or interrupt context
12436  */
12437 static void
12438 sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp, const char *fmt, ...)
12439 {
12440 	va_list	ap;
12441 
12442 	ASSERT(ssc != NULL);
12443 	ASSERT(ssc->ssc_un != NULL);
12444 
12445 	ssc->ssc_flags |= ssc_flags;
12446 	va_start(ap, fmt);
12447 	(void) vsnprintf(ssc->ssc_info, sizeof (ssc->ssc_info), fmt, ap);
12448 	va_end(ap);
12449 
12450 	/*
12451 	 * If SSC_FLAGS_INVALID_DATA is set, it should be a uscsi command
12452 	 * with invalid data sent back. For non-uscsi command, the
12453 	 * following code will be bypassed.
12454 	 */
12455 	if (ssc_flags & SSC_FLAGS_INVALID_DATA) {
12456 		if (SD_FM_LOG(ssc->ssc_un) == SD_FM_LOG_NSUP) {
12457 			/*
12458 			 * If the error belong to certain component and we
12459 			 * do not want it to show up on the console, we
12460 			 * will use SD_ERROR, otherwise scsi_log is
12461 			 * preferred.
12462 			 */
12463 			if (comp > 0) {
12464 				SD_ERROR(comp, ssc->ssc_un, ssc->ssc_info);
12465 			} else if (comp == 0) {
12466 				scsi_log(SD_DEVINFO(ssc->ssc_un), sd_label,
12467 				    CE_WARN, ssc->ssc_info);
12468 			}
12469 		}
12470 	}
12471 }
12472 
12473 /*
12474  *    Function: sd_buf_iodone
12475  *
12476  * Description: Frees the sd_xbuf & returns the buf to its originator.
12477  *
12478  *     Context: May be called from interrupt context.
12479  */
12480 /* ARGSUSED */
12481 static void
12482 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
12483 {
12484 	struct sd_xbuf *xp;
12485 
12486 	ASSERT(un != NULL);
12487 	ASSERT(bp != NULL);
12488 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12489 
12490 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
12491 
12492 	xp = SD_GET_XBUF(bp);
12493 	ASSERT(xp != NULL);
12494 
12495 	/* xbuf is gone after this */
12496 	if (ddi_xbuf_done(bp, un->un_xbuf_attr)) {
12497 		mutex_enter(SD_MUTEX(un));
12498 
12499 		/*
12500 		 * Grab time when the cmd completed.
12501 		 * This is used for determining if the system has been
12502 		 * idle long enough to make it idle to the PM framework.
12503 		 * This is for lowering the overhead, and therefore improving
12504 		 * performance per I/O operation.
12505 		 */
12506 		un->un_pm_idle_time = gethrtime();
12507 
12508 		un->un_ncmds_in_driver--;
12509 		ASSERT(un->un_ncmds_in_driver >= 0);
12510 		SD_INFO(SD_LOG_IO, un,
12511 		    "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
12512 		    un->un_ncmds_in_driver);
12513 
12514 		mutex_exit(SD_MUTEX(un));
12515 	}
12516 
12517 	biodone(bp);				/* bp is gone after this */
12518 
12519 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
12520 }
12521 
12522 
12523 /*
12524  *    Function: sd_uscsi_iodone
12525  *
12526  * Description: Frees the sd_xbuf & returns the buf to its originator.
12527  *
12528  *     Context: May be called from interrupt context.
12529  */
12530 /* ARGSUSED */
12531 static void
12532 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12533 {
12534 	struct sd_xbuf *xp;
12535 
12536 	ASSERT(un != NULL);
12537 	ASSERT(bp != NULL);
12538 
12539 	xp = SD_GET_XBUF(bp);
12540 	ASSERT(xp != NULL);
12541 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12542 
12543 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
12544 
12545 	bp->b_private = xp->xb_private;
12546 
12547 	mutex_enter(SD_MUTEX(un));
12548 
12549 	/*
12550 	 * Grab time when the cmd completed.
12551 	 * This is used for determining if the system has been
12552 	 * idle long enough to make it idle to the PM framework.
12553 	 * This is for lowering the overhead, and therefore improving
12554 	 * performance per I/O operation.
12555 	 */
12556 	un->un_pm_idle_time = gethrtime();
12557 
12558 	un->un_ncmds_in_driver--;
12559 	ASSERT(un->un_ncmds_in_driver >= 0);
12560 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
12561 	    un->un_ncmds_in_driver);
12562 
12563 	mutex_exit(SD_MUTEX(un));
12564 
12565 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
12566 	    SENSE_LENGTH) {
12567 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
12568 		    MAX_SENSE_LENGTH);
12569 	} else {
12570 		kmem_free(xp, sizeof (struct sd_xbuf));
12571 	}
12572 
12573 	biodone(bp);
12574 
12575 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
12576 }
12577 
12578 
12579 /*
12580  *    Function: sd_mapblockaddr_iostart
12581  *
12582  * Description: Verify request lies within the partition limits for
12583  *		the indicated minor device.  Issue "overrun" buf if
12584  *		request would exceed partition range.  Converts
12585  *		partition-relative block address to absolute.
12586  *
12587  *              Upon exit of this function:
12588  *              1.I/O is aligned
12589  *                 xp->xb_blkno represents the absolute sector address
12590  *              2.I/O is misaligned
12591  *                 xp->xb_blkno represents the absolute logical block address
12592  *                 based on DEV_BSIZE. The logical block address will be
12593  *                 converted to physical sector address in sd_mapblocksize_\
12594  *                 iostart.
12595  *              3.I/O is misaligned but is aligned in "overrun" buf
12596  *                 xp->xb_blkno represents the absolute logical block address
12597  *                 based on DEV_BSIZE. The logical block address will be
12598  *                 converted to physical sector address in sd_mapblocksize_\
12599  *                 iostart. But no RMW will be issued in this case.
12600  *
12601  *     Context: Can sleep
12602  *
12603  *      Issues: This follows what the old code did, in terms of accessing
12604  *		some of the partition info in the unit struct without holding
12605  *		the mutext.  This is a general issue, if the partition info
12606  *		can be altered while IO is in progress... as soon as we send
12607  *		a buf, its partitioning can be invalid before it gets to the
12608  *		device.  Probably the right fix is to move partitioning out
12609  *		of the driver entirely.
12610  */
12611 
12612 static void
12613 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
12614 {
12615 	diskaddr_t	nblocks;	/* #blocks in the given partition */
12616 	daddr_t	blocknum;	/* Block number specified by the buf */
12617 	size_t	requested_nblocks;
12618 	size_t	available_nblocks;
12619 	int	partition;
12620 	diskaddr_t	partition_offset;
12621 	struct sd_xbuf *xp;
12622 	int secmask = 0, blknomask = 0;
12623 	ushort_t is_aligned = TRUE;
12624 
12625 	ASSERT(un != NULL);
12626 	ASSERT(bp != NULL);
12627 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12628 
12629 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12630 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
12631 
12632 	xp = SD_GET_XBUF(bp);
12633 	ASSERT(xp != NULL);
12634 
12635 	/*
12636 	 * If the geometry is not indicated as valid, attempt to access
12637 	 * the unit & verify the geometry/label. This can be the case for
12638 	 * removable-media devices, of if the device was opened in
12639 	 * NDELAY/NONBLOCK mode.
12640 	 */
12641 	partition = SDPART(bp->b_edev);
12642 
12643 	if (!SD_IS_VALID_LABEL(un)) {
12644 		sd_ssc_t *ssc;
12645 		/*
12646 		 * Initialize sd_ssc_t for internal uscsi commands
12647 		 * In case of potential porformance issue, we need
12648 		 * to alloc memory only if there is invalid label
12649 		 */
12650 		ssc = sd_ssc_init(un);
12651 
12652 		if (sd_ready_and_valid(ssc, partition) != SD_READY_VALID) {
12653 			/*
12654 			 * For removable devices it is possible to start an
12655 			 * I/O without a media by opening the device in nodelay
12656 			 * mode. Also for writable CDs there can be many
12657 			 * scenarios where there is no geometry yet but volume
12658 			 * manager is trying to issue a read() just because
12659 			 * it can see TOC on the CD. So do not print a message
12660 			 * for removables.
12661 			 */
12662 			if (!un->un_f_has_removable_media) {
12663 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12664 				    "i/o to invalid geometry\n");
12665 			}
12666 			bioerror(bp, EIO);
12667 			bp->b_resid = bp->b_bcount;
12668 			SD_BEGIN_IODONE(index, un, bp);
12669 
12670 			sd_ssc_fini(ssc);
12671 			return;
12672 		}
12673 		sd_ssc_fini(ssc);
12674 	}
12675 
12676 	nblocks = 0;
12677 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
12678 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
12679 
12680 	if (un->un_f_enable_rmw) {
12681 		blknomask = (un->un_phy_blocksize / DEV_BSIZE) - 1;
12682 		secmask = un->un_phy_blocksize - 1;
12683 	} else {
12684 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
12685 		secmask = un->un_tgt_blocksize - 1;
12686 	}
12687 
12688 	if ((bp->b_lblkno & (blknomask)) || (bp->b_bcount & (secmask))) {
12689 		is_aligned = FALSE;
12690 	}
12691 
12692 	if (!(NOT_DEVBSIZE(un)) || un->un_f_enable_rmw) {
12693 		/*
12694 		 * If I/O is aligned, no need to involve RMW(Read Modify Write)
12695 		 * Convert the logical block number to target's physical sector
12696 		 * number.
12697 		 */
12698 		if (is_aligned) {
12699 			xp->xb_blkno = SD_SYS2TGTBLOCK(un, xp->xb_blkno);
12700 		} else {
12701 			/*
12702 			 * There is no RMW if we're just reading, so don't
12703 			 * warn or error out because of it.
12704 			 */
12705 			if (bp->b_flags & B_READ) {
12706 				/*EMPTY*/
12707 			} else if (!un->un_f_enable_rmw &&
12708 			    un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR) {
12709 				bp->b_flags |= B_ERROR;
12710 				goto error_exit;
12711 			} else if (un->un_f_rmw_type == SD_RMW_TYPE_DEFAULT) {
12712 				mutex_enter(SD_MUTEX(un));
12713 				if (!un->un_f_enable_rmw &&
12714 				    un->un_rmw_msg_timeid == NULL) {
12715 					scsi_log(SD_DEVINFO(un), sd_label,
12716 					    CE_WARN, "I/O request is not "
12717 					    "aligned with %d disk sector size. "
12718 					    "It is handled through Read Modify "
12719 					    "Write but the performance is "
12720 					    "very low.\n",
12721 					    un->un_tgt_blocksize);
12722 					un->un_rmw_msg_timeid =
12723 					    timeout(sd_rmw_msg_print_handler,
12724 					    un, SD_RMW_MSG_PRINT_TIMEOUT);
12725 				} else {
12726 					un->un_rmw_incre_count ++;
12727 				}
12728 				mutex_exit(SD_MUTEX(un));
12729 			}
12730 
12731 			nblocks = SD_TGT2SYSBLOCK(un, nblocks);
12732 			partition_offset = SD_TGT2SYSBLOCK(un,
12733 			    partition_offset);
12734 		}
12735 	}
12736 
12737 	/*
12738 	 * blocknum is the starting block number of the request. At this
12739 	 * point it is still relative to the start of the minor device.
12740 	 */
12741 	blocknum = xp->xb_blkno;
12742 
12743 	/*
12744 	 * Legacy: If the starting block number is one past the last block
12745 	 * in the partition, do not set B_ERROR in the buf.
12746 	 */
12747 	if (blocknum == nblocks)  {
12748 		goto error_exit;
12749 	}
12750 
12751 	/*
12752 	 * Confirm that the first block of the request lies within the
12753 	 * partition limits. Also the requested number of bytes must be
12754 	 * a multiple of the system block size.
12755 	 */
12756 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12757 	    ((bp->b_bcount & (DEV_BSIZE - 1)) != 0)) {
12758 		bp->b_flags |= B_ERROR;
12759 		goto error_exit;
12760 	}
12761 
12762 	/*
12763 	 * If the requsted # blocks exceeds the available # blocks, that
12764 	 * is an overrun of the partition.
12765 	 */
12766 	if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12767 		requested_nblocks = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
12768 	} else {
12769 		requested_nblocks = SD_BYTES2SYSBLOCKS(bp->b_bcount);
12770 	}
12771 
12772 	available_nblocks = (size_t)(nblocks - blocknum);
12773 	ASSERT(nblocks >= blocknum);
12774 
12775 	if (requested_nblocks > available_nblocks) {
12776 		size_t resid;
12777 
12778 		/*
12779 		 * Allocate an "overrun" buf to allow the request to proceed
12780 		 * for the amount of space available in the partition. The
12781 		 * amount not transferred will be added into the b_resid
12782 		 * when the operation is complete. The overrun buf
12783 		 * replaces the original buf here, and the original buf
12784 		 * is saved inside the overrun buf, for later use.
12785 		 */
12786 		if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12787 			resid = SD_TGTBLOCKS2BYTES(un,
12788 			    (offset_t)(requested_nblocks - available_nblocks));
12789 		} else {
12790 			resid = SD_SYSBLOCKS2BYTES(
12791 			    (offset_t)(requested_nblocks - available_nblocks));
12792 		}
12793 
12794 		size_t count = bp->b_bcount - resid;
12795 		/*
12796 		 * Note: count is an unsigned entity thus it'll NEVER
12797 		 * be less than 0 so ASSERT the original values are
12798 		 * correct.
12799 		 */
12800 		ASSERT(bp->b_bcount >= resid);
12801 
12802 		bp = sd_bioclone_alloc(bp, count, blocknum,
12803 		    (int (*)(struct buf *))(uintptr_t)sd_mapblockaddr_iodone);
12804 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12805 		ASSERT(xp != NULL);
12806 	}
12807 
12808 	/* At this point there should be no residual for this buf. */
12809 	ASSERT(bp->b_resid == 0);
12810 
12811 	/* Convert the block number to an absolute address. */
12812 	xp->xb_blkno += partition_offset;
12813 
12814 	SD_NEXT_IOSTART(index, un, bp);
12815 
12816 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12817 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12818 
12819 	return;
12820 
12821 error_exit:
12822 	bp->b_resid = bp->b_bcount;
12823 	SD_BEGIN_IODONE(index, un, bp);
12824 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12825 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12826 }
12827 
12828 
12829 /*
12830  *    Function: sd_mapblockaddr_iodone
12831  *
12832  * Description: Completion-side processing for partition management.
12833  *
12834  *     Context: May be called under interrupt context
12835  */
12836 
12837 static void
12838 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12839 {
12840 	/* int	partition; */	/* Not used, see below. */
12841 	ASSERT(un != NULL);
12842 	ASSERT(bp != NULL);
12843 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12844 
12845 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12846 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12847 
12848 	if ((uintptr_t)bp->b_iodone == (uintptr_t)sd_mapblockaddr_iodone) {
12849 		/*
12850 		 * We have an "overrun" buf to deal with...
12851 		 */
12852 		struct sd_xbuf	*xp;
12853 		struct buf	*obp;	/* ptr to the original buf */
12854 
12855 		xp = SD_GET_XBUF(bp);
12856 		ASSERT(xp != NULL);
12857 
12858 		/* Retrieve the pointer to the original buf */
12859 		obp = (struct buf *)xp->xb_private;
12860 		ASSERT(obp != NULL);
12861 
12862 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12863 		bioerror(obp, bp->b_error);
12864 
12865 		sd_bioclone_free(bp);
12866 
12867 		/*
12868 		 * Get back the original buf.
12869 		 * Note that since the restoration of xb_blkno below
12870 		 * was removed, the sd_xbuf is not needed.
12871 		 */
12872 		bp = obp;
12873 		/*
12874 		 * xp = SD_GET_XBUF(bp);
12875 		 * ASSERT(xp != NULL);
12876 		 */
12877 	}
12878 
12879 	/*
12880 	 * Convert sd->xb_blkno back to a minor-device relative value.
12881 	 * Note: this has been commented out, as it is not needed in the
12882 	 * current implementation of the driver (ie, since this function
12883 	 * is at the top of the layering chains, so the info will be
12884 	 * discarded) and it is in the "hot" IO path.
12885 	 *
12886 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12887 	 * xp->xb_blkno -= un->un_offset[partition];
12888 	 */
12889 
12890 	SD_NEXT_IODONE(index, un, bp);
12891 
12892 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12893 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12894 }
12895 
12896 
12897 /*
12898  *    Function: sd_mapblocksize_iostart
12899  *
12900  * Description: Convert between system block size (un->un_sys_blocksize)
12901  *		and target block size (un->un_tgt_blocksize).
12902  *
12903  *     Context: Can sleep to allocate resources.
12904  *
12905  * Assumptions: A higher layer has already performed any partition validation,
12906  *		and converted the xp->xb_blkno to an absolute value relative
12907  *		to the start of the device.
12908  *
12909  *		It is also assumed that the higher layer has implemented
12910  *		an "overrun" mechanism for the case where the request would
12911  *		read/write beyond the end of a partition.  In this case we
12912  *		assume (and ASSERT) that bp->b_resid == 0.
12913  *
12914  *		Note: The implementation for this routine assumes the target
12915  *		block size remains constant between allocation and transport.
12916  */
12917 
12918 static void
12919 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12920 {
12921 	struct sd_mapblocksize_info	*bsp;
12922 	struct sd_xbuf			*xp;
12923 	offset_t first_byte;
12924 	daddr_t	start_block, end_block;
12925 	daddr_t	request_bytes;
12926 	ushort_t is_aligned = FALSE;
12927 
12928 	ASSERT(un != NULL);
12929 	ASSERT(bp != NULL);
12930 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12931 	ASSERT(bp->b_resid == 0);
12932 
12933 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12934 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12935 
12936 	/*
12937 	 * For a non-writable CD, a write request is an error
12938 	 */
12939 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12940 	    (un->un_f_mmc_writable_media == FALSE)) {
12941 		bioerror(bp, EIO);
12942 		bp->b_resid = bp->b_bcount;
12943 		SD_BEGIN_IODONE(index, un, bp);
12944 		return;
12945 	}
12946 
12947 	/*
12948 	 * We do not need a shadow buf if the device is using
12949 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12950 	 * In this case there is no layer-private data block allocated.
12951 	 */
12952 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
12953 	    (bp->b_bcount == 0)) {
12954 		goto done;
12955 	}
12956 
12957 #if defined(__x86)
12958 	/* We do not support non-block-aligned transfers for ROD devices */
12959 	ASSERT(!ISROD(un));
12960 #endif
12961 
12962 	xp = SD_GET_XBUF(bp);
12963 	ASSERT(xp != NULL);
12964 
12965 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12966 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12967 	    un->un_tgt_blocksize, DEV_BSIZE);
12968 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12969 	    "request start block:0x%x\n", xp->xb_blkno);
12970 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12971 	    "request len:0x%x\n", bp->b_bcount);
12972 
12973 	/*
12974 	 * Allocate the layer-private data area for the mapblocksize layer.
12975 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12976 	 * struct to store the pointer to their layer-private data block, but
12977 	 * each layer also has the responsibility of restoring the prior
12978 	 * contents of xb_private before returning the buf/xbuf to the
12979 	 * higher layer that sent it.
12980 	 *
12981 	 * Here we save the prior contents of xp->xb_private into the
12982 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12983 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12984 	 * the layer-private area and returning the buf/xbuf to the layer
12985 	 * that sent it.
12986 	 *
12987 	 * Note that here we use kmem_zalloc for the allocation as there are
12988 	 * parts of the mapblocksize code that expect certain fields to be
12989 	 * zero unless explicitly set to a required value.
12990 	 */
12991 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12992 	bsp->mbs_oprivate = xp->xb_private;
12993 	xp->xb_private = bsp;
12994 
12995 	/*
12996 	 * This treats the data on the disk (target) as an array of bytes.
12997 	 * first_byte is the byte offset, from the beginning of the device,
12998 	 * to the location of the request. This is converted from a
12999 	 * un->un_sys_blocksize block address to a byte offset, and then back
13000 	 * to a block address based upon a un->un_tgt_blocksize block size.
13001 	 *
13002 	 * xp->xb_blkno should be absolute upon entry into this function,
13003 	 * but, but it is based upon partitions that use the "system"
13004 	 * block size. It must be adjusted to reflect the block size of
13005 	 * the target.
13006 	 *
13007 	 * Note that end_block is actually the block that follows the last
13008 	 * block of the request, but that's what is needed for the computation.
13009 	 */
13010 	first_byte  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
13011 	if (un->un_f_enable_rmw) {
13012 		start_block = xp->xb_blkno =
13013 		    (first_byte / un->un_phy_blocksize) *
13014 		    (un->un_phy_blocksize / DEV_BSIZE);
13015 		end_block   = ((first_byte + bp->b_bcount +
13016 		    un->un_phy_blocksize - 1) / un->un_phy_blocksize) *
13017 		    (un->un_phy_blocksize / DEV_BSIZE);
13018 	} else {
13019 		start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
13020 		end_block   = (first_byte + bp->b_bcount +
13021 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
13022 	}
13023 
13024 	/* request_bytes is rounded up to a multiple of the target block size */
13025 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
13026 
13027 	/*
13028 	 * See if the starting address of the request and the request
13029 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
13030 	 * then we do not need to allocate a shadow buf to handle the request.
13031 	 */
13032 	if (un->un_f_enable_rmw) {
13033 		if (((first_byte % un->un_phy_blocksize) == 0) &&
13034 		    ((bp->b_bcount % un->un_phy_blocksize) == 0)) {
13035 			is_aligned = TRUE;
13036 		}
13037 	} else {
13038 		if (((first_byte % un->un_tgt_blocksize) == 0) &&
13039 		    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
13040 			is_aligned = TRUE;
13041 		}
13042 	}
13043 
13044 	if ((bp->b_flags & B_READ) == 0) {
13045 		/*
13046 		 * Lock the range for a write operation. An aligned request is
13047 		 * considered a simple write; otherwise the request must be a
13048 		 * read-modify-write.
13049 		 */
13050 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
13051 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
13052 	}
13053 
13054 	/*
13055 	 * Alloc a shadow buf if the request is not aligned. Also, this is
13056 	 * where the READ command is generated for a read-modify-write. (The
13057 	 * write phase is deferred until after the read completes.)
13058 	 */
13059 	if (is_aligned == FALSE) {
13060 
13061 		struct sd_mapblocksize_info	*shadow_bsp;
13062 		struct sd_xbuf	*shadow_xp;
13063 		struct buf	*shadow_bp;
13064 
13065 		/*
13066 		 * Allocate the shadow buf and it associated xbuf. Note that
13067 		 * after this call the xb_blkno value in both the original
13068 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
13069 		 * same: absolute relative to the start of the device, and
13070 		 * adjusted for the target block size. The b_blkno in the
13071 		 * shadow buf will also be set to this value. We should never
13072 		 * change b_blkno in the original bp however.
13073 		 *
13074 		 * Note also that the shadow buf will always need to be a
13075 		 * READ command, regardless of whether the incoming command
13076 		 * is a READ or a WRITE.
13077 		 */
13078 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
13079 		    xp->xb_blkno,
13080 		    (int (*)(struct buf *))(uintptr_t)sd_mapblocksize_iodone);
13081 
13082 		shadow_xp = SD_GET_XBUF(shadow_bp);
13083 
13084 		/*
13085 		 * Allocate the layer-private data for the shadow buf.
13086 		 * (No need to preserve xb_private in the shadow xbuf.)
13087 		 */
13088 		shadow_xp->xb_private = shadow_bsp =
13089 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
13090 
13091 		/*
13092 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
13093 		 * to figure out where the start of the user data is (based upon
13094 		 * the system block size) in the data returned by the READ
13095 		 * command (which will be based upon the target blocksize). Note
13096 		 * that this is only really used if the request is unaligned.
13097 		 */
13098 		if (un->un_f_enable_rmw) {
13099 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
13100 			    ((offset_t)xp->xb_blkno * un->un_sys_blocksize));
13101 			ASSERT((bsp->mbs_copy_offset >= 0) &&
13102 			    (bsp->mbs_copy_offset < un->un_phy_blocksize));
13103 		} else {
13104 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
13105 			    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
13106 			ASSERT((bsp->mbs_copy_offset >= 0) &&
13107 			    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
13108 		}
13109 
13110 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
13111 
13112 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
13113 
13114 		/* Transfer the wmap (if any) to the shadow buf */
13115 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
13116 		bsp->mbs_wmp = NULL;
13117 
13118 		/*
13119 		 * The shadow buf goes on from here in place of the
13120 		 * original buf.
13121 		 */
13122 		shadow_bsp->mbs_orig_bp = bp;
13123 		bp = shadow_bp;
13124 	}
13125 
13126 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
13127 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
13128 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
13129 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
13130 	    request_bytes);
13131 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
13132 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
13133 
13134 done:
13135 	SD_NEXT_IOSTART(index, un, bp);
13136 
13137 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
13138 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
13139 }
13140 
13141 
13142 /*
13143  *    Function: sd_mapblocksize_iodone
13144  *
13145  * Description: Completion side processing for block-size mapping.
13146  *
13147  *     Context: May be called under interrupt context
13148  */
13149 
13150 static void
13151 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
13152 {
13153 	struct sd_mapblocksize_info	*bsp;
13154 	struct sd_xbuf	*xp;
13155 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
13156 	struct buf	*orig_bp;	/* ptr to the original buf */
13157 	offset_t	shadow_end;
13158 	offset_t	request_end;
13159 	offset_t	shadow_start;
13160 	ssize_t		copy_offset;
13161 	size_t		copy_length;
13162 	size_t		shortfall;
13163 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
13164 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
13165 
13166 	ASSERT(un != NULL);
13167 	ASSERT(bp != NULL);
13168 
13169 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
13170 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
13171 
13172 	/*
13173 	 * There is no shadow buf or layer-private data if the target is
13174 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
13175 	 */
13176 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
13177 	    (bp->b_bcount == 0)) {
13178 		goto exit;
13179 	}
13180 
13181 	xp = SD_GET_XBUF(bp);
13182 	ASSERT(xp != NULL);
13183 
13184 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
13185 	bsp = xp->xb_private;
13186 
13187 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
13188 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
13189 
13190 	if (is_write) {
13191 		/*
13192 		 * For a WRITE request we must free up the block range that
13193 		 * we have locked up.  This holds regardless of whether this is
13194 		 * an aligned write request or a read-modify-write request.
13195 		 */
13196 		sd_range_unlock(un, bsp->mbs_wmp);
13197 		bsp->mbs_wmp = NULL;
13198 	}
13199 
13200 	if ((uintptr_t)bp->b_iodone != (uintptr_t)sd_mapblocksize_iodone) {
13201 		/*
13202 		 * An aligned read or write command will have no shadow buf;
13203 		 * there is not much else to do with it.
13204 		 */
13205 		goto done;
13206 	}
13207 
13208 	orig_bp = bsp->mbs_orig_bp;
13209 	ASSERT(orig_bp != NULL);
13210 	orig_xp = SD_GET_XBUF(orig_bp);
13211 	ASSERT(orig_xp != NULL);
13212 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13213 
13214 	if (!is_write && has_wmap) {
13215 		/*
13216 		 * A READ with a wmap means this is the READ phase of a
13217 		 * read-modify-write. If an error occurred on the READ then
13218 		 * we do not proceed with the WRITE phase or copy any data.
13219 		 * Just release the write maps and return with an error.
13220 		 */
13221 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
13222 			orig_bp->b_resid = orig_bp->b_bcount;
13223 			bioerror(orig_bp, bp->b_error);
13224 			sd_range_unlock(un, bsp->mbs_wmp);
13225 			goto freebuf_done;
13226 		}
13227 	}
13228 
13229 	/*
13230 	 * Here is where we set up to copy the data from the shadow buf
13231 	 * into the space associated with the original buf.
13232 	 *
13233 	 * To deal with the conversion between block sizes, these
13234 	 * computations treat the data as an array of bytes, with the
13235 	 * first byte (byte 0) corresponding to the first byte in the
13236 	 * first block on the disk.
13237 	 */
13238 
13239 	/*
13240 	 * shadow_start and shadow_len indicate the location and size of
13241 	 * the data returned with the shadow IO request.
13242 	 */
13243 	if (un->un_f_enable_rmw) {
13244 		shadow_start  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
13245 	} else {
13246 		shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
13247 	}
13248 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
13249 
13250 	/*
13251 	 * copy_offset gives the offset (in bytes) from the start of the first
13252 	 * block of the READ request to the beginning of the data.  We retrieve
13253 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
13254 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
13255 	 * data to be copied (in bytes).
13256 	 */
13257 	copy_offset  = bsp->mbs_copy_offset;
13258 	if (un->un_f_enable_rmw) {
13259 		ASSERT((copy_offset >= 0) &&
13260 		    (copy_offset < un->un_phy_blocksize));
13261 	} else {
13262 		ASSERT((copy_offset >= 0) &&
13263 		    (copy_offset < un->un_tgt_blocksize));
13264 	}
13265 
13266 	copy_length  = orig_bp->b_bcount;
13267 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
13268 
13269 	/*
13270 	 * Set up the resid and error fields of orig_bp as appropriate.
13271 	 */
13272 	if (shadow_end >= request_end) {
13273 		/* We got all the requested data; set resid to zero */
13274 		orig_bp->b_resid = 0;
13275 	} else {
13276 		/*
13277 		 * We failed to get enough data to fully satisfy the original
13278 		 * request. Just copy back whatever data we got and set
13279 		 * up the residual and error code as required.
13280 		 *
13281 		 * 'shortfall' is the amount by which the data received with the
13282 		 * shadow buf has "fallen short" of the requested amount.
13283 		 */
13284 		shortfall = (size_t)(request_end - shadow_end);
13285 
13286 		if (shortfall > orig_bp->b_bcount) {
13287 			/*
13288 			 * We did not get enough data to even partially
13289 			 * fulfill the original request.  The residual is
13290 			 * equal to the amount requested.
13291 			 */
13292 			orig_bp->b_resid = orig_bp->b_bcount;
13293 		} else {
13294 			/*
13295 			 * We did not get all the data that we requested
13296 			 * from the device, but we will try to return what
13297 			 * portion we did get.
13298 			 */
13299 			orig_bp->b_resid = shortfall;
13300 		}
13301 		ASSERT(copy_length >= orig_bp->b_resid);
13302 		copy_length  -= orig_bp->b_resid;
13303 	}
13304 
13305 	/* Propagate the error code from the shadow buf to the original buf */
13306 	bioerror(orig_bp, bp->b_error);
13307 
13308 	if (is_write) {
13309 		goto freebuf_done;	/* No data copying for a WRITE */
13310 	}
13311 
13312 	if (has_wmap) {
13313 		/*
13314 		 * This is a READ command from the READ phase of a
13315 		 * read-modify-write request. We have to copy the data given
13316 		 * by the user OVER the data returned by the READ command,
13317 		 * then convert the command from a READ to a WRITE and send
13318 		 * it back to the target.
13319 		 */
13320 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
13321 		    copy_length);
13322 
13323 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
13324 
13325 		/*
13326 		 * Dispatch the WRITE command to the taskq thread, which
13327 		 * will in turn send the command to the target. When the
13328 		 * WRITE command completes, we (sd_mapblocksize_iodone())
13329 		 * will get called again as part of the iodone chain
13330 		 * processing for it. Note that we will still be dealing
13331 		 * with the shadow buf at that point.
13332 		 */
13333 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
13334 		    KM_NOSLEEP) != TASKQID_INVALID) {
13335 			/*
13336 			 * Dispatch was successful so we are done. Return
13337 			 * without going any higher up the iodone chain. Do
13338 			 * not free up any layer-private data until after the
13339 			 * WRITE completes.
13340 			 */
13341 			return;
13342 		}
13343 
13344 		/*
13345 		 * Dispatch of the WRITE command failed; set up the error
13346 		 * condition and send this IO back up the iodone chain.
13347 		 */
13348 		bioerror(orig_bp, EIO);
13349 		orig_bp->b_resid = orig_bp->b_bcount;
13350 
13351 	} else {
13352 		/*
13353 		 * This is a regular READ request (ie, not a RMW). Copy the
13354 		 * data from the shadow buf into the original buf. The
13355 		 * copy_offset compensates for any "misalignment" between the
13356 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
13357 		 * original buf (with its un->un_sys_blocksize blocks).
13358 		 */
13359 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
13360 		    copy_length);
13361 	}
13362 
13363 freebuf_done:
13364 
13365 	/*
13366 	 * At this point we still have both the shadow buf AND the original
13367 	 * buf to deal with, as well as the layer-private data area in each.
13368 	 * Local variables are as follows:
13369 	 *
13370 	 * bp -- points to shadow buf
13371 	 * xp -- points to xbuf of shadow buf
13372 	 * bsp -- points to layer-private data area of shadow buf
13373 	 * orig_bp -- points to original buf
13374 	 *
13375 	 * First free the shadow buf and its associated xbuf, then free the
13376 	 * layer-private data area from the shadow buf. There is no need to
13377 	 * restore xb_private in the shadow xbuf.
13378 	 */
13379 	sd_shadow_buf_free(bp);
13380 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13381 
13382 	/*
13383 	 * Now update the local variables to point to the original buf, xbuf,
13384 	 * and layer-private area.
13385 	 */
13386 	bp = orig_bp;
13387 	xp = SD_GET_XBUF(bp);
13388 	ASSERT(xp != NULL);
13389 	ASSERT(xp == orig_xp);
13390 	bsp = xp->xb_private;
13391 	ASSERT(bsp != NULL);
13392 
13393 done:
13394 	/*
13395 	 * Restore xb_private to whatever it was set to by the next higher
13396 	 * layer in the chain, then free the layer-private data area.
13397 	 */
13398 	xp->xb_private = bsp->mbs_oprivate;
13399 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13400 
13401 exit:
13402 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
13403 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
13404 
13405 	SD_NEXT_IODONE(index, un, bp);
13406 }
13407 
13408 
13409 /*
13410  *    Function: sd_checksum_iostart
13411  *
13412  * Description: A stub function for a layer that's currently not used.
13413  *		For now just a placeholder.
13414  *
13415  *     Context: Kernel thread context
13416  */
13417 
13418 static void
13419 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
13420 {
13421 	ASSERT(un != NULL);
13422 	ASSERT(bp != NULL);
13423 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13424 	SD_NEXT_IOSTART(index, un, bp);
13425 }
13426 
13427 
13428 /*
13429  *    Function: sd_checksum_iodone
13430  *
13431  * Description: A stub function for a layer that's currently not used.
13432  *		For now just a placeholder.
13433  *
13434  *     Context: May be called under interrupt context
13435  */
13436 
13437 static void
13438 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
13439 {
13440 	ASSERT(un != NULL);
13441 	ASSERT(bp != NULL);
13442 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13443 	SD_NEXT_IODONE(index, un, bp);
13444 }
13445 
13446 
13447 /*
13448  *    Function: sd_checksum_uscsi_iostart
13449  *
13450  * Description: A stub function for a layer that's currently not used.
13451  *		For now just a placeholder.
13452  *
13453  *     Context: Kernel thread context
13454  */
13455 
13456 static void
13457 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
13458 {
13459 	ASSERT(un != NULL);
13460 	ASSERT(bp != NULL);
13461 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13462 	SD_NEXT_IOSTART(index, un, bp);
13463 }
13464 
13465 
13466 /*
13467  *    Function: sd_checksum_uscsi_iodone
13468  *
13469  * Description: A stub function for a layer that's currently not used.
13470  *		For now just a placeholder.
13471  *
13472  *     Context: May be called under interrupt context
13473  */
13474 
13475 static void
13476 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
13477 {
13478 	ASSERT(un != NULL);
13479 	ASSERT(bp != NULL);
13480 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13481 	SD_NEXT_IODONE(index, un, bp);
13482 }
13483 
13484 
13485 /*
13486  *    Function: sd_pm_iostart
13487  *
13488  * Description: iostart-side routine for Power mangement.
13489  *
13490  *     Context: Kernel thread context
13491  */
13492 
13493 static void
13494 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
13495 {
13496 	ASSERT(un != NULL);
13497 	ASSERT(bp != NULL);
13498 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13499 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13500 
13501 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
13502 
13503 	if (sd_pm_entry(un) != DDI_SUCCESS) {
13504 		/*
13505 		 * Set up to return the failed buf back up the 'iodone'
13506 		 * side of the calling chain.
13507 		 */
13508 		bioerror(bp, EIO);
13509 		bp->b_resid = bp->b_bcount;
13510 
13511 		SD_BEGIN_IODONE(index, un, bp);
13512 
13513 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13514 		return;
13515 	}
13516 
13517 	SD_NEXT_IOSTART(index, un, bp);
13518 
13519 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13520 }
13521 
13522 
13523 /*
13524  *    Function: sd_pm_iodone
13525  *
13526  * Description: iodone-side routine for power mangement.
13527  *
13528  *     Context: may be called from interrupt context
13529  */
13530 
13531 static void
13532 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
13533 {
13534 	ASSERT(un != NULL);
13535 	ASSERT(bp != NULL);
13536 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13537 
13538 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
13539 
13540 	/*
13541 	 * After attach the following flag is only read, so don't
13542 	 * take the penalty of acquiring a mutex for it.
13543 	 */
13544 	if (un->un_f_pm_is_enabled == TRUE) {
13545 		sd_pm_exit(un);
13546 	}
13547 
13548 	SD_NEXT_IODONE(index, un, bp);
13549 
13550 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
13551 }
13552 
13553 
13554 /*
13555  *    Function: sd_core_iostart
13556  *
13557  * Description: Primary driver function for enqueuing buf(9S) structs from
13558  *		the system and initiating IO to the target device
13559  *
13560  *     Context: Kernel thread context. Can sleep.
13561  *
13562  * Assumptions:  - The given xp->xb_blkno is absolute
13563  *		   (ie, relative to the start of the device).
13564  *		 - The IO is to be done using the native blocksize of
13565  *		   the device, as specified in un->un_tgt_blocksize.
13566  */
13567 /* ARGSUSED */
13568 static void
13569 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
13570 {
13571 	struct sd_xbuf *xp;
13572 
13573 	ASSERT(un != NULL);
13574 	ASSERT(bp != NULL);
13575 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13576 	ASSERT(bp->b_resid == 0);
13577 
13578 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
13579 
13580 	xp = SD_GET_XBUF(bp);
13581 	ASSERT(xp != NULL);
13582 
13583 	mutex_enter(SD_MUTEX(un));
13584 
13585 	/*
13586 	 * If we are currently in the failfast state, fail any new IO
13587 	 * that has B_FAILFAST set, then return.
13588 	 */
13589 	if ((bp->b_flags & B_FAILFAST) &&
13590 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
13591 		mutex_exit(SD_MUTEX(un));
13592 		bioerror(bp, EIO);
13593 		bp->b_resid = bp->b_bcount;
13594 		SD_BEGIN_IODONE(index, un, bp);
13595 		return;
13596 	}
13597 
13598 	if (SD_IS_DIRECT_PRIORITY(xp)) {
13599 		/*
13600 		 * Priority command -- transport it immediately.
13601 		 *
13602 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
13603 		 * because all direct priority commands should be associated
13604 		 * with error recovery actions which we don't want to retry.
13605 		 */
13606 		sd_start_cmds(un, bp);
13607 	} else {
13608 		/*
13609 		 * Normal command -- add it to the wait queue, then start
13610 		 * transporting commands from the wait queue.
13611 		 */
13612 		sd_add_buf_to_waitq(un, bp);
13613 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13614 		sd_start_cmds(un, NULL);
13615 	}
13616 
13617 	mutex_exit(SD_MUTEX(un));
13618 
13619 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
13620 }
13621 
13622 
13623 /*
13624  *    Function: sd_init_cdb_limits
13625  *
13626  * Description: This is to handle scsi_pkt initialization differences
13627  *		between the driver platforms.
13628  *
13629  *		Legacy behaviors:
13630  *
13631  *		If the block number or the sector count exceeds the
13632  *		capabilities of a Group 0 command, shift over to a
13633  *		Group 1 command. We don't blindly use Group 1
13634  *		commands because a) some drives (CDC Wren IVs) get a
13635  *		bit confused, and b) there is probably a fair amount
13636  *		of speed difference for a target to receive and decode
13637  *		a 10 byte command instead of a 6 byte command.
13638  *
13639  *		The xfer time difference of 6 vs 10 byte CDBs is
13640  *		still significant so this code is still worthwhile.
13641  *		10 byte CDBs are very inefficient with the fas HBA driver
13642  *		and older disks. Each CDB byte took 1 usec with some
13643  *		popular disks.
13644  *
13645  *     Context: Must be called at attach time
13646  */
13647 
13648 static void
13649 sd_init_cdb_limits(struct sd_lun *un)
13650 {
13651 	int hba_cdb_limit;
13652 
13653 	/*
13654 	 * Use CDB_GROUP1 commands for most devices except for
13655 	 * parallel SCSI fixed drives in which case we get better
13656 	 * performance using CDB_GROUP0 commands (where applicable).
13657 	 */
13658 	un->un_mincdb = SD_CDB_GROUP1;
13659 #if !defined(__fibre)
13660 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
13661 	    !un->un_f_has_removable_media) {
13662 		un->un_mincdb = SD_CDB_GROUP0;
13663 	}
13664 #endif
13665 
13666 	/*
13667 	 * Try to read the max-cdb-length supported by HBA.
13668 	 */
13669 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
13670 	if (0 >= un->un_max_hba_cdb) {
13671 		un->un_max_hba_cdb = CDB_GROUP4;
13672 		hba_cdb_limit = SD_CDB_GROUP4;
13673 	} else if (0 < un->un_max_hba_cdb &&
13674 	    un->un_max_hba_cdb < CDB_GROUP1) {
13675 		hba_cdb_limit = SD_CDB_GROUP0;
13676 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
13677 	    un->un_max_hba_cdb < CDB_GROUP5) {
13678 		hba_cdb_limit = SD_CDB_GROUP1;
13679 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
13680 	    un->un_max_hba_cdb < CDB_GROUP4) {
13681 		hba_cdb_limit = SD_CDB_GROUP5;
13682 	} else {
13683 		hba_cdb_limit = SD_CDB_GROUP4;
13684 	}
13685 
13686 	/*
13687 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
13688 	 * commands for fixed disks unless we are building for a 32 bit
13689 	 * kernel.
13690 	 */
13691 #ifdef _LP64
13692 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13693 	    min(hba_cdb_limit, SD_CDB_GROUP4);
13694 #else
13695 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13696 	    min(hba_cdb_limit, SD_CDB_GROUP1);
13697 #endif
13698 
13699 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
13700 	    ? sizeof (struct scsi_arq_status) : 1);
13701 	if (!ISCD(un))
13702 		un->un_cmd_timeout = (ushort_t)sd_io_time;
13703 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
13704 }
13705 
13706 
13707 /*
13708  *    Function: sd_initpkt_for_buf
13709  *
13710  * Description: Allocate and initialize for transport a scsi_pkt struct,
13711  *		based upon the info specified in the given buf struct.
13712  *
13713  *		Assumes the xb_blkno in the request is absolute (ie,
13714  *		relative to the start of the device (NOT partition!).
13715  *		Also assumes that the request is using the native block
13716  *		size of the device (as returned by the READ CAPACITY
13717  *		command).
13718  *
13719  * Return Code: SD_PKT_ALLOC_SUCCESS
13720  *		SD_PKT_ALLOC_FAILURE
13721  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13722  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13723  *
13724  *     Context: Kernel thread and may be called from software interrupt context
13725  *		as part of a sdrunout callback. This function may not block or
13726  *		call routines that block
13727  */
13728 
13729 static int
13730 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
13731 {
13732 	struct sd_xbuf	*xp;
13733 	struct scsi_pkt *pktp = NULL;
13734 	struct sd_lun	*un;
13735 	size_t		blockcount;
13736 	daddr_t		startblock;
13737 	int		rval;
13738 	int		cmd_flags;
13739 
13740 	ASSERT(bp != NULL);
13741 	ASSERT(pktpp != NULL);
13742 	xp = SD_GET_XBUF(bp);
13743 	ASSERT(xp != NULL);
13744 	un = SD_GET_UN(bp);
13745 	ASSERT(un != NULL);
13746 	ASSERT(mutex_owned(SD_MUTEX(un)));
13747 	ASSERT(bp->b_resid == 0);
13748 
13749 	SD_TRACE(SD_LOG_IO_CORE, un,
13750 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13751 
13752 	mutex_exit(SD_MUTEX(un));
13753 
13754 #if defined(__x86)	/* DMAFREE for x86 only */
13755 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13756 		/*
13757 		 * Already have a scsi_pkt -- just need DMA resources.
13758 		 * We must recompute the CDB in case the mapping returns
13759 		 * a nonzero pkt_resid.
13760 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13761 		 * that is being retried, the unmap/remap of the DMA resouces
13762 		 * will result in the entire transfer starting over again
13763 		 * from the very first block.
13764 		 */
13765 		ASSERT(xp->xb_pktp != NULL);
13766 		pktp = xp->xb_pktp;
13767 	} else {
13768 		pktp = NULL;
13769 	}
13770 #endif /* __x86 */
13771 
13772 	startblock = xp->xb_blkno;	/* Absolute block num. */
13773 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13774 
13775 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13776 
13777 	/*
13778 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13779 	 * call scsi_init_pkt, and build the CDB.
13780 	 */
13781 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13782 	    cmd_flags, sdrunout, (caddr_t)un,
13783 	    startblock, blockcount);
13784 
13785 	if (rval == 0) {
13786 		/*
13787 		 * Success.
13788 		 *
13789 		 * If partial DMA is being used and required for this transfer.
13790 		 * set it up here.
13791 		 */
13792 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13793 		    (pktp->pkt_resid != 0)) {
13794 
13795 			/*
13796 			 * Save the CDB length and pkt_resid for the
13797 			 * next xfer
13798 			 */
13799 			xp->xb_dma_resid = pktp->pkt_resid;
13800 
13801 			/* rezero resid */
13802 			pktp->pkt_resid = 0;
13803 
13804 		} else {
13805 			xp->xb_dma_resid = 0;
13806 		}
13807 
13808 		pktp->pkt_flags = un->un_tagflags;
13809 		pktp->pkt_time  = un->un_cmd_timeout;
13810 		pktp->pkt_comp  = sdintr;
13811 
13812 		pktp->pkt_private = bp;
13813 		*pktpp = pktp;
13814 
13815 		SD_TRACE(SD_LOG_IO_CORE, un,
13816 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13817 
13818 #if defined(__x86)	/* DMAFREE for x86 only */
13819 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13820 #endif
13821 
13822 		mutex_enter(SD_MUTEX(un));
13823 		return (SD_PKT_ALLOC_SUCCESS);
13824 
13825 	}
13826 
13827 	/*
13828 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13829 	 * from sd_setup_rw_pkt.
13830 	 */
13831 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13832 
13833 	if (rval == SD_PKT_ALLOC_FAILURE) {
13834 		*pktpp = NULL;
13835 		/*
13836 		 * Set the driver state to RWAIT to indicate the driver
13837 		 * is waiting on resource allocations. The driver will not
13838 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13839 		 */
13840 		mutex_enter(SD_MUTEX(un));
13841 		New_state(un, SD_STATE_RWAIT);
13842 
13843 		SD_ERROR(SD_LOG_IO_CORE, un,
13844 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13845 
13846 		if ((bp->b_flags & B_ERROR) != 0) {
13847 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13848 		}
13849 		return (SD_PKT_ALLOC_FAILURE);
13850 	} else {
13851 		/*
13852 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13853 		 *
13854 		 * This should never happen.  Maybe someone messed with the
13855 		 * kernel's minphys?
13856 		 */
13857 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13858 		    "Request rejected: too large for CDB: "
13859 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13860 		SD_ERROR(SD_LOG_IO_CORE, un,
13861 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13862 		mutex_enter(SD_MUTEX(un));
13863 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13864 
13865 	}
13866 }
13867 
13868 
13869 /*
13870  *    Function: sd_destroypkt_for_buf
13871  *
13872  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13873  *
13874  *     Context: Kernel thread or interrupt context
13875  */
13876 
13877 static void
13878 sd_destroypkt_for_buf(struct buf *bp)
13879 {
13880 	ASSERT(bp != NULL);
13881 	ASSERT(SD_GET_UN(bp) != NULL);
13882 
13883 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13884 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13885 
13886 	ASSERT(SD_GET_PKTP(bp) != NULL);
13887 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13888 
13889 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13890 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13891 }
13892 
13893 /*
13894  *    Function: sd_setup_rw_pkt
13895  *
13896  * Description: Determines appropriate CDB group for the requested LBA
13897  *		and transfer length, calls scsi_init_pkt, and builds
13898  *		the CDB.  Do not use for partial DMA transfers except
13899  *		for the initial transfer since the CDB size must
13900  *		remain constant.
13901  *
13902  *     Context: Kernel thread and may be called from software interrupt
13903  *		context as part of a sdrunout callback. This function may not
13904  *		block or call routines that block
13905  */
13906 
13907 
13908 int
13909 sd_setup_rw_pkt(struct sd_lun *un,
13910     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13911     int (*callback)(caddr_t), caddr_t callback_arg,
13912     diskaddr_t lba, uint32_t blockcount)
13913 {
13914 	struct scsi_pkt *return_pktp;
13915 	union scsi_cdb *cdbp;
13916 	struct sd_cdbinfo *cp = NULL;
13917 	int i;
13918 
13919 	/*
13920 	 * See which size CDB to use, based upon the request.
13921 	 */
13922 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13923 
13924 		/*
13925 		 * Check lba and block count against sd_cdbtab limits.
13926 		 * In the partial DMA case, we have to use the same size
13927 		 * CDB for all the transfers.  Check lba + blockcount
13928 		 * against the max LBA so we know that segment of the
13929 		 * transfer can use the CDB we select.
13930 		 */
13931 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13932 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13933 
13934 			/*
13935 			 * The command will fit into the CDB type
13936 			 * specified by sd_cdbtab[i].
13937 			 */
13938 			cp = sd_cdbtab + i;
13939 
13940 			/*
13941 			 * Call scsi_init_pkt so we can fill in the
13942 			 * CDB.
13943 			 */
13944 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13945 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13946 			    flags, callback, callback_arg);
13947 
13948 			if (return_pktp != NULL) {
13949 
13950 				/*
13951 				 * Return new value of pkt
13952 				 */
13953 				*pktpp = return_pktp;
13954 
13955 				/*
13956 				 * To be safe, zero the CDB insuring there is
13957 				 * no leftover data from a previous command.
13958 				 */
13959 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13960 
13961 				/*
13962 				 * Handle partial DMA mapping
13963 				 */
13964 				if (return_pktp->pkt_resid != 0) {
13965 
13966 					/*
13967 					 * Not going to xfer as many blocks as
13968 					 * originally expected
13969 					 */
13970 					blockcount -=
13971 					    SD_BYTES2TGTBLOCKS(un,
13972 					    return_pktp->pkt_resid);
13973 				}
13974 
13975 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13976 
13977 				/*
13978 				 * Set command byte based on the CDB
13979 				 * type we matched.
13980 				 */
13981 				cdbp->scc_cmd = cp->sc_grpmask |
13982 				    ((bp->b_flags & B_READ) ?
13983 				    SCMD_READ : SCMD_WRITE);
13984 
13985 				SD_FILL_SCSI1_LUN(un, return_pktp);
13986 
13987 				/*
13988 				 * Fill in LBA and length
13989 				 */
13990 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13991 				    (cp->sc_grpcode == CDB_GROUP4) ||
13992 				    (cp->sc_grpcode == CDB_GROUP0) ||
13993 				    (cp->sc_grpcode == CDB_GROUP5));
13994 
13995 				if (cp->sc_grpcode == CDB_GROUP1) {
13996 					FORMG1ADDR(cdbp, lba);
13997 					FORMG1COUNT(cdbp, blockcount);
13998 					return (0);
13999 				} else if (cp->sc_grpcode == CDB_GROUP4) {
14000 					FORMG4LONGADDR(cdbp, lba);
14001 					FORMG4COUNT(cdbp, blockcount);
14002 					return (0);
14003 				} else if (cp->sc_grpcode == CDB_GROUP0) {
14004 					FORMG0ADDR(cdbp, lba);
14005 					FORMG0COUNT(cdbp, blockcount);
14006 					return (0);
14007 				} else if (cp->sc_grpcode == CDB_GROUP5) {
14008 					FORMG5ADDR(cdbp, lba);
14009 					FORMG5COUNT(cdbp, blockcount);
14010 					return (0);
14011 				}
14012 
14013 				/*
14014 				 * It should be impossible to not match one
14015 				 * of the CDB types above, so we should never
14016 				 * reach this point.  Set the CDB command byte
14017 				 * to test-unit-ready to avoid writing
14018 				 * to somewhere we don't intend.
14019 				 */
14020 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
14021 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
14022 			} else {
14023 				/*
14024 				 * Couldn't get scsi_pkt
14025 				 */
14026 				return (SD_PKT_ALLOC_FAILURE);
14027 			}
14028 		}
14029 	}
14030 
14031 	/*
14032 	 * None of the available CDB types were suitable.  This really
14033 	 * should never happen:  on a 64 bit system we support
14034 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
14035 	 * and on a 32 bit system we will refuse to bind to a device
14036 	 * larger than 2TB so addresses will never be larger than 32 bits.
14037 	 */
14038 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
14039 }
14040 
14041 /*
14042  *    Function: sd_setup_next_rw_pkt
14043  *
14044  * Description: Setup packet for partial DMA transfers, except for the
14045  *		initial transfer.  sd_setup_rw_pkt should be used for
14046  *		the initial transfer.
14047  *
14048  *     Context: Kernel thread and may be called from interrupt context.
14049  */
14050 
14051 int
14052 sd_setup_next_rw_pkt(struct sd_lun *un,
14053     struct scsi_pkt *pktp, struct buf *bp,
14054     diskaddr_t lba, uint32_t blockcount)
14055 {
14056 	uchar_t com;
14057 	union scsi_cdb *cdbp;
14058 	uchar_t cdb_group_id;
14059 
14060 	ASSERT(pktp != NULL);
14061 	ASSERT(pktp->pkt_cdbp != NULL);
14062 
14063 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
14064 	com = cdbp->scc_cmd;
14065 	cdb_group_id = CDB_GROUPID(com);
14066 
14067 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
14068 	    (cdb_group_id == CDB_GROUPID_1) ||
14069 	    (cdb_group_id == CDB_GROUPID_4) ||
14070 	    (cdb_group_id == CDB_GROUPID_5));
14071 
14072 	/*
14073 	 * Move pkt to the next portion of the xfer.
14074 	 * func is NULL_FUNC so we do not have to release
14075 	 * the disk mutex here.
14076 	 */
14077 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
14078 	    NULL_FUNC, NULL) == pktp) {
14079 		/* Success.  Handle partial DMA */
14080 		if (pktp->pkt_resid != 0) {
14081 			blockcount -=
14082 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
14083 		}
14084 
14085 		cdbp->scc_cmd = com;
14086 		SD_FILL_SCSI1_LUN(un, pktp);
14087 		if (cdb_group_id == CDB_GROUPID_1) {
14088 			FORMG1ADDR(cdbp, lba);
14089 			FORMG1COUNT(cdbp, blockcount);
14090 			return (0);
14091 		} else if (cdb_group_id == CDB_GROUPID_4) {
14092 			FORMG4LONGADDR(cdbp, lba);
14093 			FORMG4COUNT(cdbp, blockcount);
14094 			return (0);
14095 		} else if (cdb_group_id == CDB_GROUPID_0) {
14096 			FORMG0ADDR(cdbp, lba);
14097 			FORMG0COUNT(cdbp, blockcount);
14098 			return (0);
14099 		} else if (cdb_group_id == CDB_GROUPID_5) {
14100 			FORMG5ADDR(cdbp, lba);
14101 			FORMG5COUNT(cdbp, blockcount);
14102 			return (0);
14103 		}
14104 
14105 		/* Unreachable */
14106 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
14107 	}
14108 
14109 	/*
14110 	 * Error setting up next portion of cmd transfer.
14111 	 * Something is definitely very wrong and this
14112 	 * should not happen.
14113 	 */
14114 	return (SD_PKT_ALLOC_FAILURE);
14115 }
14116 
14117 /*
14118  *    Function: sd_initpkt_for_uscsi
14119  *
14120  * Description: Allocate and initialize for transport a scsi_pkt struct,
14121  *		based upon the info specified in the given uscsi_cmd struct.
14122  *
14123  * Return Code: SD_PKT_ALLOC_SUCCESS
14124  *		SD_PKT_ALLOC_FAILURE
14125  *		SD_PKT_ALLOC_FAILURE_NO_DMA
14126  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
14127  *
14128  *     Context: Kernel thread and may be called from software interrupt context
14129  *		as part of a sdrunout callback. This function may not block or
14130  *		call routines that block
14131  */
14132 
14133 static int
14134 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
14135 {
14136 	struct uscsi_cmd *uscmd;
14137 	struct sd_xbuf	*xp;
14138 	struct scsi_pkt	*pktp;
14139 	struct sd_lun	*un;
14140 	uint32_t	flags = 0;
14141 
14142 	ASSERT(bp != NULL);
14143 	ASSERT(pktpp != NULL);
14144 	xp = SD_GET_XBUF(bp);
14145 	ASSERT(xp != NULL);
14146 	un = SD_GET_UN(bp);
14147 	ASSERT(un != NULL);
14148 	ASSERT(mutex_owned(SD_MUTEX(un)));
14149 
14150 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14151 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14152 	ASSERT(uscmd != NULL);
14153 
14154 	SD_TRACE(SD_LOG_IO_CORE, un,
14155 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
14156 
14157 	/*
14158 	 * Allocate the scsi_pkt for the command.
14159 	 *
14160 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
14161 	 *	 during scsi_init_pkt time and will continue to use the
14162 	 *	 same path as long as the same scsi_pkt is used without
14163 	 *	 intervening scsi_dmafree(). Since uscsi command does
14164 	 *	 not call scsi_dmafree() before retry failed command, it
14165 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
14166 	 *	 set such that scsi_vhci can use other available path for
14167 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
14168 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
14169 	 *
14170 	 *	 More fundamentally, we can't support breaking up this DMA into
14171 	 *	 multiple windows on x86. There is, in general, no guarantee
14172 	 *	 that arbitrary SCSI commands are idempotent, which is required
14173 	 *	 if we want to use multiple windows for a given command.
14174 	 */
14175 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14176 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
14177 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
14178 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
14179 		    - sizeof (struct scsi_extended_sense)), 0,
14180 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
14181 		    sdrunout, (caddr_t)un);
14182 	} else {
14183 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
14184 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
14185 		    sizeof (struct scsi_arq_status), 0,
14186 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
14187 		    sdrunout, (caddr_t)un);
14188 	}
14189 
14190 	if (pktp == NULL) {
14191 		*pktpp = NULL;
14192 		/*
14193 		 * Set the driver state to RWAIT to indicate the driver
14194 		 * is waiting on resource allocations. The driver will not
14195 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
14196 		 */
14197 		New_state(un, SD_STATE_RWAIT);
14198 
14199 		SD_ERROR(SD_LOG_IO_CORE, un,
14200 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
14201 
14202 		if ((bp->b_flags & B_ERROR) != 0) {
14203 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
14204 		}
14205 		return (SD_PKT_ALLOC_FAILURE);
14206 	}
14207 
14208 	/*
14209 	 * We do not do DMA breakup for USCSI commands, so return failure
14210 	 * here if all the needed DMA resources were not allocated.
14211 	 */
14212 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
14213 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
14214 		scsi_destroy_pkt(pktp);
14215 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
14216 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
14217 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
14218 	}
14219 
14220 	/* Init the cdb from the given uscsi struct */
14221 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
14222 	    uscmd->uscsi_cdb[0], 0, 0, 0);
14223 
14224 	SD_FILL_SCSI1_LUN(un, pktp);
14225 
14226 	/*
14227 	 * Set up the optional USCSI flags. See the uscsi(4I) man page
14228 	 * for listing of the supported flags.
14229 	 */
14230 
14231 	if (uscmd->uscsi_flags & USCSI_SILENT) {
14232 		flags |= FLAG_SILENT;
14233 	}
14234 
14235 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
14236 		flags |= FLAG_DIAGNOSE;
14237 	}
14238 
14239 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
14240 		flags |= FLAG_ISOLATE;
14241 	}
14242 
14243 	if (un->un_f_is_fibre == FALSE) {
14244 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
14245 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
14246 		}
14247 	}
14248 
14249 	/*
14250 	 * Set the pkt flags here so we save time later.
14251 	 * Note: These flags are NOT in the uscsi man page!!!
14252 	 */
14253 	if (uscmd->uscsi_flags & USCSI_HEAD) {
14254 		flags |= FLAG_HEAD;
14255 	}
14256 
14257 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
14258 		flags |= FLAG_NOINTR;
14259 	}
14260 
14261 	/*
14262 	 * For tagged queueing, things get a bit complicated.
14263 	 * Check first for head of queue and last for ordered queue.
14264 	 * If neither head nor order, use the default driver tag flags.
14265 	 */
14266 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
14267 		if (uscmd->uscsi_flags & USCSI_HTAG) {
14268 			flags |= FLAG_HTAG;
14269 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
14270 			flags |= FLAG_OTAG;
14271 		} else {
14272 			flags |= un->un_tagflags & FLAG_TAGMASK;
14273 		}
14274 	}
14275 
14276 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
14277 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
14278 	}
14279 
14280 	pktp->pkt_flags = flags;
14281 
14282 	/* Transfer uscsi information to scsi_pkt */
14283 	(void) scsi_uscsi_pktinit(uscmd, pktp);
14284 
14285 	/* Copy the caller's CDB into the pkt... */
14286 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
14287 
14288 	if (uscmd->uscsi_timeout == 0) {
14289 		pktp->pkt_time = un->un_uscsi_timeout;
14290 	} else {
14291 		pktp->pkt_time = uscmd->uscsi_timeout;
14292 	}
14293 
14294 	/* need it later to identify USCSI request in sdintr */
14295 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
14296 
14297 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
14298 
14299 	pktp->pkt_private = bp;
14300 	pktp->pkt_comp = sdintr;
14301 	*pktpp = pktp;
14302 
14303 	SD_TRACE(SD_LOG_IO_CORE, un,
14304 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
14305 
14306 	return (SD_PKT_ALLOC_SUCCESS);
14307 }
14308 
14309 
14310 /*
14311  *    Function: sd_destroypkt_for_uscsi
14312  *
14313  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
14314  *		IOs.. Also saves relevant info into the associated uscsi_cmd
14315  *		struct.
14316  *
14317  *     Context: May be called under interrupt context
14318  */
14319 
14320 static void
14321 sd_destroypkt_for_uscsi(struct buf *bp)
14322 {
14323 	struct uscsi_cmd *uscmd;
14324 	struct sd_xbuf	*xp;
14325 	struct scsi_pkt	*pktp;
14326 	struct sd_lun	*un;
14327 	struct sd_uscsi_info *suip;
14328 
14329 	ASSERT(bp != NULL);
14330 	xp = SD_GET_XBUF(bp);
14331 	ASSERT(xp != NULL);
14332 	un = SD_GET_UN(bp);
14333 	ASSERT(un != NULL);
14334 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14335 	pktp = SD_GET_PKTP(bp);
14336 	ASSERT(pktp != NULL);
14337 
14338 	SD_TRACE(SD_LOG_IO_CORE, un,
14339 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
14340 
14341 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14342 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14343 	ASSERT(uscmd != NULL);
14344 
14345 	/* Save the status and the residual into the uscsi_cmd struct */
14346 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
14347 	uscmd->uscsi_resid  = bp->b_resid;
14348 
14349 	/* Transfer scsi_pkt information to uscsi */
14350 	(void) scsi_uscsi_pktfini(pktp, uscmd);
14351 
14352 	/*
14353 	 * If enabled, copy any saved sense data into the area specified
14354 	 * by the uscsi command.
14355 	 */
14356 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
14357 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
14358 		/*
14359 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
14360 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
14361 		 */
14362 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
14363 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
14364 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14365 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14366 			    MAX_SENSE_LENGTH);
14367 		} else {
14368 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14369 			    SENSE_LENGTH);
14370 		}
14371 	}
14372 	/*
14373 	 * The following assignments are for SCSI FMA.
14374 	 */
14375 	ASSERT(xp->xb_private != NULL);
14376 	suip = (struct sd_uscsi_info *)xp->xb_private;
14377 	suip->ui_pkt_reason = pktp->pkt_reason;
14378 	suip->ui_pkt_state = pktp->pkt_state;
14379 	suip->ui_pkt_statistics = pktp->pkt_statistics;
14380 	suip->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
14381 
14382 	/* We are done with the scsi_pkt; free it now */
14383 	ASSERT(SD_GET_PKTP(bp) != NULL);
14384 	scsi_destroy_pkt(SD_GET_PKTP(bp));
14385 
14386 	SD_TRACE(SD_LOG_IO_CORE, un,
14387 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
14388 }
14389 
14390 
14391 /*
14392  *    Function: sd_bioclone_alloc
14393  *
14394  * Description: Allocate a buf(9S) and init it as per the given buf
14395  *		and the various arguments.  The associated sd_xbuf
14396  *		struct is (nearly) duplicated.  The struct buf *bp
14397  *		argument is saved in new_xp->xb_private.
14398  *
14399  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14400  *		datalen - size of data area for the shadow bp
14401  *		blkno - starting LBA
14402  *		func - function pointer for b_iodone in the shadow buf. (May
14403  *			be NULL if none.)
14404  *
14405  * Return Code: Pointer to allocates buf(9S) struct
14406  *
14407  *     Context: Can sleep.
14408  */
14409 
14410 static struct buf *
14411 sd_bioclone_alloc(struct buf *bp, size_t datalen, daddr_t blkno,
14412     int (*func)(struct buf *))
14413 {
14414 	struct	sd_lun	*un;
14415 	struct	sd_xbuf	*xp;
14416 	struct	sd_xbuf	*new_xp;
14417 	struct	buf	*new_bp;
14418 
14419 	ASSERT(bp != NULL);
14420 	xp = SD_GET_XBUF(bp);
14421 	ASSERT(xp != NULL);
14422 	un = SD_GET_UN(bp);
14423 	ASSERT(un != NULL);
14424 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14425 
14426 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
14427 	    NULL, KM_SLEEP);
14428 
14429 	new_bp->b_lblkno	= blkno;
14430 
14431 	/*
14432 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14433 	 * original xbuf into it.
14434 	 */
14435 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14436 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14437 
14438 	/*
14439 	 * The given bp is automatically saved in the xb_private member
14440 	 * of the new xbuf.  Callers are allowed to depend on this.
14441 	 */
14442 	new_xp->xb_private = bp;
14443 
14444 	new_bp->b_private  = new_xp;
14445 
14446 	return (new_bp);
14447 }
14448 
14449 /*
14450  *    Function: sd_shadow_buf_alloc
14451  *
14452  * Description: Allocate a buf(9S) and init it as per the given buf
14453  *		and the various arguments.  The associated sd_xbuf
14454  *		struct is (nearly) duplicated.  The struct buf *bp
14455  *		argument is saved in new_xp->xb_private.
14456  *
14457  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14458  *		datalen - size of data area for the shadow bp
14459  *		bflags - B_READ or B_WRITE (pseudo flag)
14460  *		blkno - starting LBA
14461  *		func - function pointer for b_iodone in the shadow buf. (May
14462  *			be NULL if none.)
14463  *
14464  * Return Code: Pointer to allocates buf(9S) struct
14465  *
14466  *     Context: Can sleep.
14467  */
14468 
14469 static struct buf *
14470 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
14471     daddr_t blkno, int (*func)(struct buf *))
14472 {
14473 	struct	sd_lun	*un;
14474 	struct	sd_xbuf	*xp;
14475 	struct	sd_xbuf	*new_xp;
14476 	struct	buf	*new_bp;
14477 
14478 	ASSERT(bp != NULL);
14479 	xp = SD_GET_XBUF(bp);
14480 	ASSERT(xp != NULL);
14481 	un = SD_GET_UN(bp);
14482 	ASSERT(un != NULL);
14483 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14484 
14485 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
14486 		bp_mapin(bp);
14487 	}
14488 
14489 	bflags &= (B_READ | B_WRITE);
14490 #if defined(__x86)
14491 	new_bp = getrbuf(KM_SLEEP);
14492 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
14493 	new_bp->b_bcount = datalen;
14494 	new_bp->b_flags = bflags |
14495 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
14496 #else
14497 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
14498 	    datalen, bflags, SLEEP_FUNC, NULL);
14499 #endif
14500 	new_bp->av_forw	= NULL;
14501 	new_bp->av_back	= NULL;
14502 	new_bp->b_dev	= bp->b_dev;
14503 	new_bp->b_blkno	= blkno;
14504 	new_bp->b_iodone = func;
14505 	new_bp->b_edev	= bp->b_edev;
14506 	new_bp->b_resid	= 0;
14507 
14508 	/* We need to preserve the B_FAILFAST flag */
14509 	if (bp->b_flags & B_FAILFAST) {
14510 		new_bp->b_flags |= B_FAILFAST;
14511 	}
14512 
14513 	/*
14514 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14515 	 * original xbuf into it.
14516 	 */
14517 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14518 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14519 
14520 	/* Need later to copy data between the shadow buf & original buf! */
14521 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
14522 
14523 	/*
14524 	 * The given bp is automatically saved in the xb_private member
14525 	 * of the new xbuf.  Callers are allowed to depend on this.
14526 	 */
14527 	new_xp->xb_private = bp;
14528 
14529 	new_bp->b_private  = new_xp;
14530 
14531 	return (new_bp);
14532 }
14533 
14534 /*
14535  *    Function: sd_bioclone_free
14536  *
14537  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
14538  *		in the larger than partition operation.
14539  *
14540  *     Context: May be called under interrupt context
14541  */
14542 
14543 static void
14544 sd_bioclone_free(struct buf *bp)
14545 {
14546 	struct sd_xbuf	*xp;
14547 
14548 	ASSERT(bp != NULL);
14549 	xp = SD_GET_XBUF(bp);
14550 	ASSERT(xp != NULL);
14551 
14552 	/*
14553 	 * Call bp_mapout() before freeing the buf,  in case a lower
14554 	 * layer or HBA  had done a bp_mapin().  we must do this here
14555 	 * as we are the "originator" of the shadow buf.
14556 	 */
14557 	bp_mapout(bp);
14558 
14559 	/*
14560 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14561 	 * never gets confused by a stale value in this field. (Just a little
14562 	 * extra defensiveness here.)
14563 	 */
14564 	bp->b_iodone = NULL;
14565 
14566 	freerbuf(bp);
14567 
14568 	kmem_free(xp, sizeof (struct sd_xbuf));
14569 }
14570 
14571 /*
14572  *    Function: sd_shadow_buf_free
14573  *
14574  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
14575  *
14576  *     Context: May be called under interrupt context
14577  */
14578 
14579 static void
14580 sd_shadow_buf_free(struct buf *bp)
14581 {
14582 	struct sd_xbuf	*xp;
14583 
14584 	ASSERT(bp != NULL);
14585 	xp = SD_GET_XBUF(bp);
14586 	ASSERT(xp != NULL);
14587 
14588 #if defined(__sparc)
14589 	/*
14590 	 * Call bp_mapout() before freeing the buf,  in case a lower
14591 	 * layer or HBA  had done a bp_mapin().  we must do this here
14592 	 * as we are the "originator" of the shadow buf.
14593 	 */
14594 	bp_mapout(bp);
14595 #endif
14596 
14597 	/*
14598 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14599 	 * never gets confused by a stale value in this field. (Just a little
14600 	 * extra defensiveness here.)
14601 	 */
14602 	bp->b_iodone = NULL;
14603 
14604 #if defined(__x86)
14605 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
14606 	freerbuf(bp);
14607 #else
14608 	scsi_free_consistent_buf(bp);
14609 #endif
14610 
14611 	kmem_free(xp, sizeof (struct sd_xbuf));
14612 }
14613 
14614 
14615 /*
14616  *    Function: sd_print_transport_rejected_message
14617  *
14618  * Description: This implements the ludicrously complex rules for printing
14619  *		a "transport rejected" message.  This is to address the
14620  *		specific problem of having a flood of this error message
14621  *		produced when a failover occurs.
14622  *
14623  *     Context: Any.
14624  */
14625 
14626 static void
14627 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
14628     int code)
14629 {
14630 	ASSERT(un != NULL);
14631 	ASSERT(mutex_owned(SD_MUTEX(un)));
14632 	ASSERT(xp != NULL);
14633 
14634 	/*
14635 	 * Print the "transport rejected" message under the following
14636 	 * conditions:
14637 	 *
14638 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
14639 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
14640 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
14641 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
14642 	 *   scsi_transport(9F) (which indicates that the target might have
14643 	 *   gone off-line).  This uses the un->un_tran_fatal_count
14644 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
14645 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
14646 	 *   from scsi_transport().
14647 	 *
14648 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
14649 	 * the preceeding cases in order for the message to be printed.
14650 	 */
14651 	if (((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) &&
14652 	    (SD_FM_LOG(un) == SD_FM_LOG_NSUP)) {
14653 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
14654 		    (code != TRAN_FATAL_ERROR) ||
14655 		    (un->un_tran_fatal_count == 1)) {
14656 			switch (code) {
14657 			case TRAN_BADPKT:
14658 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14659 				    "transport rejected bad packet\n");
14660 				break;
14661 			case TRAN_FATAL_ERROR:
14662 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14663 				    "transport rejected fatal error\n");
14664 				break;
14665 			default:
14666 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14667 				    "transport rejected (%d)\n", code);
14668 				break;
14669 			}
14670 		}
14671 	}
14672 }
14673 
14674 
14675 /*
14676  *    Function: sd_add_buf_to_waitq
14677  *
14678  * Description: Add the given buf(9S) struct to the wait queue for the
14679  *		instance.  If sorting is enabled, then the buf is added
14680  *		to the queue via an elevator sort algorithm (a la
14681  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
14682  *		If sorting is not enabled, then the buf is just added
14683  *		to the end of the wait queue.
14684  *
14685  * Return Code: void
14686  *
14687  *     Context: Does not sleep/block, therefore technically can be called
14688  *		from any context.  However if sorting is enabled then the
14689  *		execution time is indeterminate, and may take long if
14690  *		the wait queue grows large.
14691  */
14692 
14693 static void
14694 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
14695 {
14696 	struct buf *ap;
14697 
14698 	ASSERT(bp != NULL);
14699 	ASSERT(un != NULL);
14700 	ASSERT(mutex_owned(SD_MUTEX(un)));
14701 
14702 	/* If the queue is empty, add the buf as the only entry & return. */
14703 	if (un->un_waitq_headp == NULL) {
14704 		ASSERT(un->un_waitq_tailp == NULL);
14705 		un->un_waitq_headp = un->un_waitq_tailp = bp;
14706 		bp->av_forw = NULL;
14707 		return;
14708 	}
14709 
14710 	ASSERT(un->un_waitq_tailp != NULL);
14711 
14712 	/*
14713 	 * If sorting is disabled, just add the buf to the tail end of
14714 	 * the wait queue and return.
14715 	 */
14716 	if (un->un_f_disksort_disabled || un->un_f_enable_rmw) {
14717 		un->un_waitq_tailp->av_forw = bp;
14718 		un->un_waitq_tailp = bp;
14719 		bp->av_forw = NULL;
14720 		return;
14721 	}
14722 
14723 	/*
14724 	 * Sort thru the list of requests currently on the wait queue
14725 	 * and add the new buf request at the appropriate position.
14726 	 *
14727 	 * The un->un_waitq_headp is an activity chain pointer on which
14728 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
14729 	 * first queue holds those requests which are positioned after
14730 	 * the current SD_GET_BLKNO() (in the first request); the second holds
14731 	 * requests which came in after their SD_GET_BLKNO() number was passed.
14732 	 * Thus we implement a one way scan, retracting after reaching
14733 	 * the end of the drive to the first request on the second
14734 	 * queue, at which time it becomes the first queue.
14735 	 * A one-way scan is natural because of the way UNIX read-ahead
14736 	 * blocks are allocated.
14737 	 *
14738 	 * If we lie after the first request, then we must locate the
14739 	 * second request list and add ourselves to it.
14740 	 */
14741 	ap = un->un_waitq_headp;
14742 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
14743 		while (ap->av_forw != NULL) {
14744 			/*
14745 			 * Look for an "inversion" in the (normally
14746 			 * ascending) block numbers. This indicates
14747 			 * the start of the second request list.
14748 			 */
14749 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14750 				/*
14751 				 * Search the second request list for the
14752 				 * first request at a larger block number.
14753 				 * We go before that; however if there is
14754 				 * no such request, we go at the end.
14755 				 */
14756 				do {
14757 					if (SD_GET_BLKNO(bp) <
14758 					    SD_GET_BLKNO(ap->av_forw)) {
14759 						goto insert;
14760 					}
14761 					ap = ap->av_forw;
14762 				} while (ap->av_forw != NULL);
14763 				goto insert;		/* after last */
14764 			}
14765 			ap = ap->av_forw;
14766 		}
14767 
14768 		/*
14769 		 * No inversions... we will go after the last, and
14770 		 * be the first request in the second request list.
14771 		 */
14772 		goto insert;
14773 	}
14774 
14775 	/*
14776 	 * Request is at/after the current request...
14777 	 * sort in the first request list.
14778 	 */
14779 	while (ap->av_forw != NULL) {
14780 		/*
14781 		 * We want to go after the current request (1) if
14782 		 * there is an inversion after it (i.e. it is the end
14783 		 * of the first request list), or (2) if the next
14784 		 * request is a larger block no. than our request.
14785 		 */
14786 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14787 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14788 			goto insert;
14789 		}
14790 		ap = ap->av_forw;
14791 	}
14792 
14793 	/*
14794 	 * Neither a second list nor a larger request, therefore
14795 	 * we go at the end of the first list (which is the same
14796 	 * as the end of the whole schebang).
14797 	 */
14798 insert:
14799 	bp->av_forw = ap->av_forw;
14800 	ap->av_forw = bp;
14801 
14802 	/*
14803 	 * If we inserted onto the tail end of the waitq, make sure the
14804 	 * tail pointer is updated.
14805 	 */
14806 	if (ap == un->un_waitq_tailp) {
14807 		un->un_waitq_tailp = bp;
14808 	}
14809 }
14810 
14811 
14812 /*
14813  *    Function: sd_start_cmds
14814  *
14815  * Description: Remove and transport cmds from the driver queues.
14816  *
14817  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14818  *
14819  *		immed_bp - ptr to a buf to be transported immediately. Only
14820  *		the immed_bp is transported; bufs on the waitq are not
14821  *		processed and the un_retry_bp is not checked.  If immed_bp is
14822  *		NULL, then normal queue processing is performed.
14823  *
14824  *     Context: May be called from kernel thread context, interrupt context,
14825  *		or runout callback context. This function may not block or
14826  *		call routines that block.
14827  */
14828 
14829 static void
14830 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14831 {
14832 	struct	sd_xbuf	*xp;
14833 	struct	buf	*bp;
14834 	void	(*statp)(kstat_io_t *);
14835 #if defined(__x86)	/* DMAFREE for x86 only */
14836 	void	(*saved_statp)(kstat_io_t *);
14837 #endif
14838 	int	rval;
14839 	struct sd_fm_internal *sfip = NULL;
14840 
14841 	ASSERT(un != NULL);
14842 	ASSERT(mutex_owned(SD_MUTEX(un)));
14843 	ASSERT(un->un_ncmds_in_transport >= 0);
14844 	ASSERT(un->un_throttle >= 0);
14845 
14846 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14847 
14848 	do {
14849 #if defined(__x86)	/* DMAFREE for x86 only */
14850 		saved_statp = NULL;
14851 #endif
14852 
14853 		/*
14854 		 * If we are syncing or dumping, fail the command to
14855 		 * avoid recursively calling back into scsi_transport().
14856 		 * The dump I/O itself uses a separate code path so this
14857 		 * only prevents non-dump I/O from being sent while dumping.
14858 		 * File system sync takes place before dumping begins.
14859 		 * During panic, filesystem I/O is allowed provided
14860 		 * un_in_callback is <= 1.  This is to prevent recursion
14861 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14862 		 * sd_start_cmds and so on.  See panic.c for more information
14863 		 * about the states the system can be in during panic.
14864 		 */
14865 		if ((un->un_state == SD_STATE_DUMPING) ||
14866 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14867 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14868 			    "sd_start_cmds: panicking\n");
14869 			goto exit;
14870 		}
14871 
14872 		if ((bp = immed_bp) != NULL) {
14873 			/*
14874 			 * We have a bp that must be transported immediately.
14875 			 * It's OK to transport the immed_bp here without doing
14876 			 * the throttle limit check because the immed_bp is
14877 			 * always used in a retry/recovery case. This means
14878 			 * that we know we are not at the throttle limit by
14879 			 * virtue of the fact that to get here we must have
14880 			 * already gotten a command back via sdintr(). This also
14881 			 * relies on (1) the command on un_retry_bp preventing
14882 			 * further commands from the waitq from being issued;
14883 			 * and (2) the code in sd_retry_command checking the
14884 			 * throttle limit before issuing a delayed or immediate
14885 			 * retry. This holds even if the throttle limit is
14886 			 * currently ratcheted down from its maximum value.
14887 			 */
14888 			statp = kstat_runq_enter;
14889 			if (bp == un->un_retry_bp) {
14890 				ASSERT((un->un_retry_statp == NULL) ||
14891 				    (un->un_retry_statp == kstat_waitq_enter) ||
14892 				    (un->un_retry_statp ==
14893 				    kstat_runq_back_to_waitq));
14894 				/*
14895 				 * If the waitq kstat was incremented when
14896 				 * sd_set_retry_bp() queued this bp for a retry,
14897 				 * then we must set up statp so that the waitq
14898 				 * count will get decremented correctly below.
14899 				 * Also we must clear un->un_retry_statp to
14900 				 * ensure that we do not act on a stale value
14901 				 * in this field.
14902 				 */
14903 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14904 				    (un->un_retry_statp ==
14905 				    kstat_runq_back_to_waitq)) {
14906 					statp = kstat_waitq_to_runq;
14907 				}
14908 #if defined(__x86)	/* DMAFREE for x86 only */
14909 				saved_statp = un->un_retry_statp;
14910 #endif
14911 				un->un_retry_statp = NULL;
14912 
14913 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14914 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14915 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14916 				    un, un->un_retry_bp, un->un_throttle,
14917 				    un->un_ncmds_in_transport);
14918 			} else {
14919 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14920 				    "processing priority bp:0x%p\n", bp);
14921 			}
14922 
14923 		} else if ((bp = un->un_waitq_headp) != NULL) {
14924 			/*
14925 			 * A command on the waitq is ready to go, but do not
14926 			 * send it if:
14927 			 *
14928 			 * (1) the throttle limit has been reached, or
14929 			 * (2) a retry is pending, or
14930 			 * (3) a START_STOP_UNIT callback pending, or
14931 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14932 			 *	command is pending.
14933 			 *
14934 			 * For all of these conditions, IO processing will
14935 			 * restart after the condition is cleared.
14936 			 */
14937 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14938 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14939 				    "sd_start_cmds: exiting, "
14940 				    "throttle limit reached!\n");
14941 				goto exit;
14942 			}
14943 			if (un->un_retry_bp != NULL) {
14944 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14945 				    "sd_start_cmds: exiting, retry pending!\n");
14946 				goto exit;
14947 			}
14948 			if (un->un_startstop_timeid != NULL) {
14949 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14950 				    "sd_start_cmds: exiting, "
14951 				    "START_STOP pending!\n");
14952 				goto exit;
14953 			}
14954 			if (un->un_direct_priority_timeid != NULL) {
14955 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14956 				    "sd_start_cmds: exiting, "
14957 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14958 				goto exit;
14959 			}
14960 
14961 			/* Dequeue the command */
14962 			un->un_waitq_headp = bp->av_forw;
14963 			if (un->un_waitq_headp == NULL) {
14964 				un->un_waitq_tailp = NULL;
14965 			}
14966 			bp->av_forw = NULL;
14967 			statp = kstat_waitq_to_runq;
14968 			SD_TRACE(SD_LOG_IO_CORE, un,
14969 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14970 
14971 		} else {
14972 			/* No work to do so bail out now */
14973 			SD_TRACE(SD_LOG_IO_CORE, un,
14974 			    "sd_start_cmds: no more work, exiting!\n");
14975 			goto exit;
14976 		}
14977 
14978 		/*
14979 		 * Reset the state to normal. This is the mechanism by which
14980 		 * the state transitions from either SD_STATE_RWAIT or
14981 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14982 		 * If state is SD_STATE_PM_CHANGING then this command is
14983 		 * part of the device power control and the state must
14984 		 * not be put back to normal. Doing so would would
14985 		 * allow new commands to proceed when they shouldn't,
14986 		 * the device may be going off.
14987 		 */
14988 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14989 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14990 			New_state(un, SD_STATE_NORMAL);
14991 		}
14992 
14993 		xp = SD_GET_XBUF(bp);
14994 		ASSERT(xp != NULL);
14995 
14996 #if defined(__x86)	/* DMAFREE for x86 only */
14997 		/*
14998 		 * Allocate the scsi_pkt if we need one, or attach DMA
14999 		 * resources if we have a scsi_pkt that needs them. The
15000 		 * latter should only occur for commands that are being
15001 		 * retried.
15002 		 */
15003 		if ((xp->xb_pktp == NULL) ||
15004 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
15005 #else
15006 		if (xp->xb_pktp == NULL) {
15007 #endif
15008 			/*
15009 			 * There is no scsi_pkt allocated for this buf. Call
15010 			 * the initpkt function to allocate & init one.
15011 			 *
15012 			 * The scsi_init_pkt runout callback functionality is
15013 			 * implemented as follows:
15014 			 *
15015 			 * 1) The initpkt function always calls
15016 			 *    scsi_init_pkt(9F) with sdrunout specified as the
15017 			 *    callback routine.
15018 			 * 2) A successful packet allocation is initialized and
15019 			 *    the I/O is transported.
15020 			 * 3) The I/O associated with an allocation resource
15021 			 *    failure is left on its queue to be retried via
15022 			 *    runout or the next I/O.
15023 			 * 4) The I/O associated with a DMA error is removed
15024 			 *    from the queue and failed with EIO. Processing of
15025 			 *    the transport queues is also halted to be
15026 			 *    restarted via runout or the next I/O.
15027 			 * 5) The I/O associated with a CDB size or packet
15028 			 *    size error is removed from the queue and failed
15029 			 *    with EIO. Processing of the transport queues is
15030 			 *    continued.
15031 			 *
15032 			 * Note: there is no interface for canceling a runout
15033 			 * callback. To prevent the driver from detaching or
15034 			 * suspending while a runout is pending the driver
15035 			 * state is set to SD_STATE_RWAIT
15036 			 *
15037 			 * Note: using the scsi_init_pkt callback facility can
15038 			 * result in an I/O request persisting at the head of
15039 			 * the list which cannot be satisfied even after
15040 			 * multiple retries. In the future the driver may
15041 			 * implement some kind of maximum runout count before
15042 			 * failing an I/O.
15043 			 *
15044 			 * Note: the use of funcp below may seem superfluous,
15045 			 * but it helps warlock figure out the correct
15046 			 * initpkt function calls (see [s]sd.wlcmd).
15047 			 */
15048 			struct scsi_pkt	*pktp;
15049 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
15050 
15051 			ASSERT(bp != un->un_rqs_bp);
15052 
15053 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
15054 			switch ((*funcp)(bp, &pktp)) {
15055 			case  SD_PKT_ALLOC_SUCCESS:
15056 				xp->xb_pktp = pktp;
15057 				SD_TRACE(SD_LOG_IO_CORE, un,
15058 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
15059 				    pktp);
15060 				goto got_pkt;
15061 
15062 			case SD_PKT_ALLOC_FAILURE:
15063 				/*
15064 				 * Temporary (hopefully) resource depletion.
15065 				 * Since retries and RQS commands always have a
15066 				 * scsi_pkt allocated, these cases should never
15067 				 * get here. So the only cases this needs to
15068 				 * handle is a bp from the waitq (which we put
15069 				 * back onto the waitq for sdrunout), or a bp
15070 				 * sent as an immed_bp (which we just fail).
15071 				 */
15072 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15073 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
15074 
15075 #if defined(__x86)	/* DMAFREE for x86 only */
15076 
15077 				if (bp == immed_bp) {
15078 					/*
15079 					 * If SD_XB_DMA_FREED is clear, then
15080 					 * this is a failure to allocate a
15081 					 * scsi_pkt, and we must fail the
15082 					 * command.
15083 					 */
15084 					if ((xp->xb_pkt_flags &
15085 					    SD_XB_DMA_FREED) == 0) {
15086 						break;
15087 					}
15088 
15089 					/*
15090 					 * If this immediate command is NOT our
15091 					 * un_retry_bp, then we must fail it.
15092 					 */
15093 					if (bp != un->un_retry_bp) {
15094 						break;
15095 					}
15096 
15097 					/*
15098 					 * We get here if this cmd is our
15099 					 * un_retry_bp that was DMAFREED, but
15100 					 * scsi_init_pkt() failed to reallocate
15101 					 * DMA resources when we attempted to
15102 					 * retry it. This can happen when an
15103 					 * mpxio failover is in progress, but
15104 					 * we don't want to just fail the
15105 					 * command in this case.
15106 					 *
15107 					 * Use timeout(9F) to restart it after
15108 					 * a 100ms delay.  We don't want to
15109 					 * let sdrunout() restart it, because
15110 					 * sdrunout() is just supposed to start
15111 					 * commands that are sitting on the
15112 					 * wait queue.  The un_retry_bp stays
15113 					 * set until the command completes, but
15114 					 * sdrunout can be called many times
15115 					 * before that happens.  Since sdrunout
15116 					 * cannot tell if the un_retry_bp is
15117 					 * already in the transport, it could
15118 					 * end up calling scsi_transport() for
15119 					 * the un_retry_bp multiple times.
15120 					 *
15121 					 * Also: don't schedule the callback
15122 					 * if some other callback is already
15123 					 * pending.
15124 					 */
15125 					if (un->un_retry_statp == NULL) {
15126 						/*
15127 						 * restore the kstat pointer to
15128 						 * keep kstat counts coherent
15129 						 * when we do retry the command.
15130 						 */
15131 						un->un_retry_statp =
15132 						    saved_statp;
15133 					}
15134 
15135 					if ((un->un_startstop_timeid == NULL) &&
15136 					    (un->un_retry_timeid == NULL) &&
15137 					    (un->un_direct_priority_timeid ==
15138 					    NULL)) {
15139 
15140 						un->un_retry_timeid =
15141 						    timeout(
15142 						    sd_start_retry_command,
15143 						    un, SD_RESTART_TIMEOUT);
15144 					}
15145 					goto exit;
15146 				}
15147 
15148 #else
15149 				if (bp == immed_bp) {
15150 					break;	/* Just fail the command */
15151 				}
15152 #endif
15153 
15154 				/* Add the buf back to the head of the waitq */
15155 				bp->av_forw = un->un_waitq_headp;
15156 				un->un_waitq_headp = bp;
15157 				if (un->un_waitq_tailp == NULL) {
15158 					un->un_waitq_tailp = bp;
15159 				}
15160 				goto exit;
15161 
15162 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
15163 				/*
15164 				 * HBA DMA resource failure. Fail the command
15165 				 * and continue processing of the queues.
15166 				 */
15167 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15168 				    "sd_start_cmds: "
15169 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
15170 				break;
15171 
15172 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
15173 				/*
15174 				 * Note:x86: Partial DMA mapping not supported
15175 				 * for USCSI commands, and all the needed DMA
15176 				 * resources were not allocated.
15177 				 */
15178 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15179 				    "sd_start_cmds: "
15180 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
15181 				break;
15182 
15183 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
15184 				/*
15185 				 * Note:x86: Request cannot fit into CDB based
15186 				 * on lba and len.
15187 				 */
15188 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15189 				    "sd_start_cmds: "
15190 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
15191 				break;
15192 
15193 			default:
15194 				/* Should NEVER get here! */
15195 				panic("scsi_initpkt error");
15196 				/*NOTREACHED*/
15197 			}
15198 
15199 			/*
15200 			 * Fatal error in allocating a scsi_pkt for this buf.
15201 			 * Update kstats & return the buf with an error code.
15202 			 * We must use sd_return_failed_command_no_restart() to
15203 			 * avoid a recursive call back into sd_start_cmds().
15204 			 * However this also means that we must keep processing
15205 			 * the waitq here in order to avoid stalling.
15206 			 */
15207 			if (statp == kstat_waitq_to_runq) {
15208 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
15209 			}
15210 			sd_return_failed_command_no_restart(un, bp, EIO);
15211 			if (bp == immed_bp) {
15212 				/* immed_bp is gone by now, so clear this */
15213 				immed_bp = NULL;
15214 			}
15215 			continue;
15216 		}
15217 got_pkt:
15218 		if (bp == immed_bp) {
15219 			/* goto the head of the class.... */
15220 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15221 		}
15222 
15223 		un->un_ncmds_in_transport++;
15224 		SD_UPDATE_KSTATS(un, statp, bp);
15225 
15226 		/*
15227 		 * Call scsi_transport() to send the command to the target.
15228 		 * According to SCSA architecture, we must drop the mutex here
15229 		 * before calling scsi_transport() in order to avoid deadlock.
15230 		 * Note that the scsi_pkt's completion routine can be executed
15231 		 * (from interrupt context) even before the call to
15232 		 * scsi_transport() returns.
15233 		 */
15234 		SD_TRACE(SD_LOG_IO_CORE, un,
15235 		    "sd_start_cmds: calling scsi_transport()\n");
15236 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
15237 
15238 		mutex_exit(SD_MUTEX(un));
15239 		rval = scsi_transport(xp->xb_pktp);
15240 		mutex_enter(SD_MUTEX(un));
15241 
15242 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15243 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
15244 
15245 		switch (rval) {
15246 		case TRAN_ACCEPT:
15247 			/* Clear this with every pkt accepted by the HBA */
15248 			un->un_tran_fatal_count = 0;
15249 			break;	/* Success; try the next cmd (if any) */
15250 
15251 		case TRAN_BUSY:
15252 			un->un_ncmds_in_transport--;
15253 			ASSERT(un->un_ncmds_in_transport >= 0);
15254 
15255 			/*
15256 			 * Don't retry request sense, the sense data
15257 			 * is lost when another request is sent.
15258 			 * Free up the rqs buf and retry
15259 			 * the original failed cmd.  Update kstat.
15260 			 */
15261 			if (bp == un->un_rqs_bp) {
15262 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15263 				bp = sd_mark_rqs_idle(un, xp);
15264 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15265 				    NULL, NULL, EIO, un->un_busy_timeout / 500,
15266 				    kstat_waitq_enter);
15267 				goto exit;
15268 			}
15269 
15270 #if defined(__x86)	/* DMAFREE for x86 only */
15271 			/*
15272 			 * Free the DMA resources for the  scsi_pkt. This will
15273 			 * allow mpxio to select another path the next time
15274 			 * we call scsi_transport() with this scsi_pkt.
15275 			 * See sdintr() for the rationalization behind this.
15276 			 */
15277 			if ((un->un_f_is_fibre == TRUE) &&
15278 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15279 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
15280 				scsi_dmafree(xp->xb_pktp);
15281 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15282 			}
15283 #endif
15284 
15285 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
15286 				/*
15287 				 * Commands that are SD_PATH_DIRECT_PRIORITY
15288 				 * are for error recovery situations. These do
15289 				 * not use the normal command waitq, so if they
15290 				 * get a TRAN_BUSY we cannot put them back onto
15291 				 * the waitq for later retry. One possible
15292 				 * problem is that there could already be some
15293 				 * other command on un_retry_bp that is waiting
15294 				 * for this one to complete, so we would be
15295 				 * deadlocked if we put this command back onto
15296 				 * the waitq for later retry (since un_retry_bp
15297 				 * must complete before the driver gets back to
15298 				 * commands on the waitq).
15299 				 *
15300 				 * To avoid deadlock we must schedule a callback
15301 				 * that will restart this command after a set
15302 				 * interval.  This should keep retrying for as
15303 				 * long as the underlying transport keeps
15304 				 * returning TRAN_BUSY (just like for other
15305 				 * commands).  Use the same timeout interval as
15306 				 * for the ordinary TRAN_BUSY retry.
15307 				 */
15308 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15309 				    "sd_start_cmds: scsi_transport() returned "
15310 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
15311 
15312 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15313 				un->un_direct_priority_timeid =
15314 				    timeout(sd_start_direct_priority_command,
15315 				    bp, un->un_busy_timeout / 500);
15316 
15317 				goto exit;
15318 			}
15319 
15320 			/*
15321 			 * For TRAN_BUSY, we want to reduce the throttle value,
15322 			 * unless we are retrying a command.
15323 			 */
15324 			if (bp != un->un_retry_bp) {
15325 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
15326 			}
15327 
15328 			/*
15329 			 * Set up the bp to be tried again 10 ms later.
15330 			 * Note:x86: Is there a timeout value in the sd_lun
15331 			 * for this condition?
15332 			 */
15333 			sd_set_retry_bp(un, bp, un->un_busy_timeout / 500,
15334 			    kstat_runq_back_to_waitq);
15335 			goto exit;
15336 
15337 		case TRAN_FATAL_ERROR:
15338 			un->un_tran_fatal_count++;
15339 			/* FALLTHRU */
15340 
15341 		case TRAN_BADPKT:
15342 		default:
15343 			un->un_ncmds_in_transport--;
15344 			ASSERT(un->un_ncmds_in_transport >= 0);
15345 
15346 			/*
15347 			 * If this is our REQUEST SENSE command with a
15348 			 * transport error, we must get back the pointers
15349 			 * to the original buf, and mark the REQUEST
15350 			 * SENSE command as "available".
15351 			 */
15352 			if (bp == un->un_rqs_bp) {
15353 				bp = sd_mark_rqs_idle(un, xp);
15354 				xp = SD_GET_XBUF(bp);
15355 			} else {
15356 				/*
15357 				 * Legacy behavior: do not update transport
15358 				 * error count for request sense commands.
15359 				 */
15360 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
15361 			}
15362 
15363 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15364 			sd_print_transport_rejected_message(un, xp, rval);
15365 
15366 			/*
15367 			 * This command will be terminated by SD driver due
15368 			 * to a fatal transport error. We should post
15369 			 * ereport.io.scsi.cmd.disk.tran with driver-assessment
15370 			 * of "fail" for any command to indicate this
15371 			 * situation.
15372 			 */
15373 			if (xp->xb_ena > 0) {
15374 				ASSERT(un->un_fm_private != NULL);
15375 				sfip = un->un_fm_private;
15376 				sfip->fm_ssc.ssc_flags |= SSC_FLAGS_TRAN_ABORT;
15377 				sd_ssc_extract_info(&sfip->fm_ssc, un,
15378 				    xp->xb_pktp, bp, xp);
15379 				sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15380 			}
15381 
15382 			/*
15383 			 * We must use sd_return_failed_command_no_restart() to
15384 			 * avoid a recursive call back into sd_start_cmds().
15385 			 * However this also means that we must keep processing
15386 			 * the waitq here in order to avoid stalling.
15387 			 */
15388 			sd_return_failed_command_no_restart(un, bp, EIO);
15389 
15390 			/*
15391 			 * Notify any threads waiting in sd_ddi_suspend() that
15392 			 * a command completion has occurred.
15393 			 */
15394 			if (un->un_state == SD_STATE_SUSPENDED) {
15395 				cv_broadcast(&un->un_disk_busy_cv);
15396 			}
15397 
15398 			if (bp == immed_bp) {
15399 				/* immed_bp is gone by now, so clear this */
15400 				immed_bp = NULL;
15401 			}
15402 			break;
15403 		}
15404 
15405 	} while (immed_bp == NULL);
15406 
15407 exit:
15408 	ASSERT(mutex_owned(SD_MUTEX(un)));
15409 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
15410 }
15411 
15412 
15413 /*
15414  *    Function: sd_return_command
15415  *
15416  * Description: Returns a command to its originator (with or without an
15417  *		error).  Also starts commands waiting to be transported
15418  *		to the target.
15419  *
15420  *     Context: May be called from interrupt, kernel, or timeout context
15421  */
15422 
15423 static void
15424 sd_return_command(struct sd_lun *un, struct buf *bp)
15425 {
15426 	struct sd_xbuf *xp;
15427 	struct scsi_pkt *pktp;
15428 	struct sd_fm_internal *sfip;
15429 
15430 	ASSERT(bp != NULL);
15431 	ASSERT(un != NULL);
15432 	ASSERT(mutex_owned(SD_MUTEX(un)));
15433 	ASSERT(bp != un->un_rqs_bp);
15434 	xp = SD_GET_XBUF(bp);
15435 	ASSERT(xp != NULL);
15436 
15437 	pktp = SD_GET_PKTP(bp);
15438 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15439 	ASSERT(sfip != NULL);
15440 
15441 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
15442 
15443 	/*
15444 	 * Note: check for the "sdrestart failed" case.
15445 	 */
15446 	if ((un->un_partial_dma_supported == 1) &&
15447 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
15448 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
15449 	    (xp->xb_pktp->pkt_resid == 0)) {
15450 
15451 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
15452 			/*
15453 			 * Successfully set up next portion of cmd
15454 			 * transfer, try sending it
15455 			 */
15456 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15457 			    NULL, NULL, 0, (clock_t)0, NULL);
15458 			sd_start_cmds(un, NULL);
15459 			return;	/* Note:x86: need a return here? */
15460 		}
15461 	}
15462 
15463 	/*
15464 	 * If this is the failfast bp, clear it from un_failfast_bp. This
15465 	 * can happen if upon being re-tried the failfast bp either
15466 	 * succeeded or encountered another error (possibly even a different
15467 	 * error than the one that precipitated the failfast state, but in
15468 	 * that case it would have had to exhaust retries as well). Regardless,
15469 	 * this should not occur whenever the instance is in the active
15470 	 * failfast state.
15471 	 */
15472 	if (bp == un->un_failfast_bp) {
15473 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15474 		un->un_failfast_bp = NULL;
15475 	}
15476 
15477 	/*
15478 	 * Clear the failfast state upon successful completion of ANY cmd.
15479 	 */
15480 	if (bp->b_error == 0) {
15481 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15482 		/*
15483 		 * If this is a successful command, but used to be retried,
15484 		 * we will take it as a recovered command and post an
15485 		 * ereport with driver-assessment of "recovered".
15486 		 */
15487 		if (xp->xb_ena > 0) {
15488 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15489 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RECOVERY);
15490 		}
15491 	} else {
15492 		/*
15493 		 * If this is a failed non-USCSI command we will post an
15494 		 * ereport with driver-assessment set accordingly("fail" or
15495 		 * "fatal").
15496 		 */
15497 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15498 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15499 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15500 		}
15501 	}
15502 
15503 	/*
15504 	 * This is used if the command was retried one or more times. Show that
15505 	 * we are done with it, and allow processing of the waitq to resume.
15506 	 */
15507 	if (bp == un->un_retry_bp) {
15508 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15509 		    "sd_return_command: un:0x%p: "
15510 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15511 		un->un_retry_bp = NULL;
15512 		un->un_retry_statp = NULL;
15513 	}
15514 
15515 	SD_UPDATE_RDWR_STATS(un, bp);
15516 	SD_UPDATE_PARTITION_STATS(un, bp);
15517 
15518 	switch (un->un_state) {
15519 	case SD_STATE_SUSPENDED:
15520 		/*
15521 		 * Notify any threads waiting in sd_ddi_suspend() that
15522 		 * a command completion has occurred.
15523 		 */
15524 		cv_broadcast(&un->un_disk_busy_cv);
15525 		break;
15526 	default:
15527 		sd_start_cmds(un, NULL);
15528 		break;
15529 	}
15530 
15531 	/* Return this command up the iodone chain to its originator. */
15532 	mutex_exit(SD_MUTEX(un));
15533 
15534 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15535 	xp->xb_pktp = NULL;
15536 
15537 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15538 
15539 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15540 	mutex_enter(SD_MUTEX(un));
15541 
15542 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
15543 }
15544 
15545 
15546 /*
15547  *    Function: sd_return_failed_command
15548  *
15549  * Description: Command completion when an error occurred.
15550  *
15551  *     Context: May be called from interrupt context
15552  */
15553 
15554 static void
15555 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
15556 {
15557 	ASSERT(bp != NULL);
15558 	ASSERT(un != NULL);
15559 	ASSERT(mutex_owned(SD_MUTEX(un)));
15560 
15561 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15562 	    "sd_return_failed_command: entry\n");
15563 
15564 	/*
15565 	 * b_resid could already be nonzero due to a partial data
15566 	 * transfer, so do not change it here.
15567 	 */
15568 	SD_BIOERROR(bp, errcode);
15569 
15570 	sd_return_command(un, bp);
15571 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15572 	    "sd_return_failed_command: exit\n");
15573 }
15574 
15575 
15576 /*
15577  *    Function: sd_return_failed_command_no_restart
15578  *
15579  * Description: Same as sd_return_failed_command, but ensures that no
15580  *		call back into sd_start_cmds will be issued.
15581  *
15582  *     Context: May be called from interrupt context
15583  */
15584 
15585 static void
15586 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
15587     int errcode)
15588 {
15589 	struct sd_xbuf *xp;
15590 
15591 	ASSERT(bp != NULL);
15592 	ASSERT(un != NULL);
15593 	ASSERT(mutex_owned(SD_MUTEX(un)));
15594 	xp = SD_GET_XBUF(bp);
15595 	ASSERT(xp != NULL);
15596 	ASSERT(errcode != 0);
15597 
15598 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15599 	    "sd_return_failed_command_no_restart: entry\n");
15600 
15601 	/*
15602 	 * b_resid could already be nonzero due to a partial data
15603 	 * transfer, so do not change it here.
15604 	 */
15605 	SD_BIOERROR(bp, errcode);
15606 
15607 	/*
15608 	 * If this is the failfast bp, clear it. This can happen if the
15609 	 * failfast bp encounterd a fatal error when we attempted to
15610 	 * re-try it (such as a scsi_transport(9F) failure).  However
15611 	 * we should NOT be in an active failfast state if the failfast
15612 	 * bp is not NULL.
15613 	 */
15614 	if (bp == un->un_failfast_bp) {
15615 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15616 		un->un_failfast_bp = NULL;
15617 	}
15618 
15619 	if (bp == un->un_retry_bp) {
15620 		/*
15621 		 * This command was retried one or more times. Show that we are
15622 		 * done with it, and allow processing of the waitq to resume.
15623 		 */
15624 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15625 		    "sd_return_failed_command_no_restart: "
15626 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15627 		un->un_retry_bp = NULL;
15628 		un->un_retry_statp = NULL;
15629 	}
15630 
15631 	SD_UPDATE_RDWR_STATS(un, bp);
15632 	SD_UPDATE_PARTITION_STATS(un, bp);
15633 
15634 	mutex_exit(SD_MUTEX(un));
15635 
15636 	if (xp->xb_pktp != NULL) {
15637 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15638 		xp->xb_pktp = NULL;
15639 	}
15640 
15641 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15642 
15643 	mutex_enter(SD_MUTEX(un));
15644 
15645 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15646 	    "sd_return_failed_command_no_restart: exit\n");
15647 }
15648 
15649 
15650 /*
15651  *    Function: sd_retry_command
15652  *
15653  * Description: queue up a command for retry, or (optionally) fail it
15654  *		if retry counts are exhausted.
15655  *
15656  *   Arguments: un - Pointer to the sd_lun struct for the target.
15657  *
15658  *		bp - Pointer to the buf for the command to be retried.
15659  *
15660  *		retry_check_flag - Flag to see which (if any) of the retry
15661  *		   counts should be decremented/checked. If the indicated
15662  *		   retry count is exhausted, then the command will not be
15663  *		   retried; it will be failed instead. This should use a
15664  *		   value equal to one of the following:
15665  *
15666  *			SD_RETRIES_NOCHECK
15667  *			SD_RESD_RETRIES_STANDARD
15668  *			SD_RETRIES_VICTIM
15669  *
15670  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
15671  *		   if the check should be made to see of FLAG_ISOLATE is set
15672  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
15673  *		   not retried, it is simply failed.
15674  *
15675  *		user_funcp - Ptr to function to call before dispatching the
15676  *		   command. May be NULL if no action needs to be performed.
15677  *		   (Primarily intended for printing messages.)
15678  *
15679  *		user_arg - Optional argument to be passed along to
15680  *		   the user_funcp call.
15681  *
15682  *		failure_code - errno return code to set in the bp if the
15683  *		   command is going to be failed.
15684  *
15685  *		retry_delay - Retry delay interval in (clock_t) units. May
15686  *		   be zero which indicates that the retry should be retried
15687  *		   immediately (ie, without an intervening delay).
15688  *
15689  *		statp - Ptr to kstat function to be updated if the command
15690  *		   is queued for a delayed retry. May be NULL if no kstat
15691  *		   update is desired.
15692  *
15693  *     Context: May be called from interrupt context.
15694  */
15695 
15696 static void
15697 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
15698     void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int code),
15699     void *user_arg, int failure_code, clock_t retry_delay,
15700     void (*statp)(kstat_io_t *))
15701 {
15702 	struct sd_xbuf	*xp;
15703 	struct scsi_pkt	*pktp;
15704 	struct sd_fm_internal *sfip;
15705 
15706 	ASSERT(un != NULL);
15707 	ASSERT(mutex_owned(SD_MUTEX(un)));
15708 	ASSERT(bp != NULL);
15709 	xp = SD_GET_XBUF(bp);
15710 	ASSERT(xp != NULL);
15711 	pktp = SD_GET_PKTP(bp);
15712 	ASSERT(pktp != NULL);
15713 
15714 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15715 	ASSERT(sfip != NULL);
15716 
15717 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15718 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
15719 
15720 	/*
15721 	 * If we are syncing or dumping, fail the command to avoid
15722 	 * recursively calling back into scsi_transport().
15723 	 */
15724 	if (ddi_in_panic()) {
15725 		goto fail_command_no_log;
15726 	}
15727 
15728 	/*
15729 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
15730 	 * log an error and fail the command.
15731 	 */
15732 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15733 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
15734 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
15735 		sd_dump_memory(un, SD_LOG_IO, "CDB",
15736 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15737 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15738 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15739 		goto fail_command;
15740 	}
15741 
15742 	/*
15743 	 * If we are suspended, then put the command onto head of the
15744 	 * wait queue since we don't want to start more commands, and
15745 	 * clear the un_retry_bp. Next time when we are resumed, will
15746 	 * handle the command in the wait queue.
15747 	 */
15748 	switch (un->un_state) {
15749 	case SD_STATE_SUSPENDED:
15750 	case SD_STATE_DUMPING:
15751 		bp->av_forw = un->un_waitq_headp;
15752 		un->un_waitq_headp = bp;
15753 		if (un->un_waitq_tailp == NULL) {
15754 			un->un_waitq_tailp = bp;
15755 		}
15756 		if (bp == un->un_retry_bp) {
15757 			un->un_retry_bp = NULL;
15758 			un->un_retry_statp = NULL;
15759 		}
15760 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15761 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15762 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15763 		return;
15764 	default:
15765 		break;
15766 	}
15767 
15768 	/*
15769 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15770 	 * is set; if it is then we do not want to retry the command.
15771 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15772 	 */
15773 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15774 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15775 			goto fail_command;
15776 		}
15777 	}
15778 
15779 
15780 	/*
15781 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15782 	 * command timeout or a selection timeout has occurred. This means
15783 	 * that we were unable to establish an kind of communication with
15784 	 * the target, and subsequent retries and/or commands are likely
15785 	 * to encounter similar results and take a long time to complete.
15786 	 *
15787 	 * If this is a failfast error condition, we need to update the
15788 	 * failfast state, even if this bp does not have B_FAILFAST set.
15789 	 */
15790 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15791 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15792 			ASSERT(un->un_failfast_bp == NULL);
15793 			/*
15794 			 * If we are already in the active failfast state, and
15795 			 * another failfast error condition has been detected,
15796 			 * then fail this command if it has B_FAILFAST set.
15797 			 * If B_FAILFAST is clear, then maintain the legacy
15798 			 * behavior of retrying heroically, even tho this will
15799 			 * take a lot more time to fail the command.
15800 			 */
15801 			if (bp->b_flags & B_FAILFAST) {
15802 				goto fail_command;
15803 			}
15804 		} else {
15805 			/*
15806 			 * We're not in the active failfast state, but we
15807 			 * have a failfast error condition, so we must begin
15808 			 * transition to the next state. We do this regardless
15809 			 * of whether or not this bp has B_FAILFAST set.
15810 			 */
15811 			if (un->un_failfast_bp == NULL) {
15812 				/*
15813 				 * This is the first bp to meet a failfast
15814 				 * condition so save it on un_failfast_bp &
15815 				 * do normal retry processing. Do not enter
15816 				 * active failfast state yet. This marks
15817 				 * entry into the "failfast pending" state.
15818 				 */
15819 				un->un_failfast_bp = bp;
15820 
15821 			} else if (un->un_failfast_bp == bp) {
15822 				/*
15823 				 * This is the second time *this* bp has
15824 				 * encountered a failfast error condition,
15825 				 * so enter active failfast state & flush
15826 				 * queues as appropriate.
15827 				 */
15828 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15829 				un->un_failfast_bp = NULL;
15830 				sd_failfast_flushq(un);
15831 
15832 				/*
15833 				 * Fail this bp now if B_FAILFAST set;
15834 				 * otherwise continue with retries. (It would
15835 				 * be pretty ironic if this bp succeeded on a
15836 				 * subsequent retry after we just flushed all
15837 				 * the queues).
15838 				 */
15839 				if (bp->b_flags & B_FAILFAST) {
15840 					goto fail_command;
15841 				}
15842 
15843 #if !defined(lint) && !defined(__lint)
15844 			} else {
15845 				/*
15846 				 * If neither of the preceeding conditionals
15847 				 * was true, it means that there is some
15848 				 * *other* bp that has met an inital failfast
15849 				 * condition and is currently either being
15850 				 * retried or is waiting to be retried. In
15851 				 * that case we should perform normal retry
15852 				 * processing on *this* bp, since there is a
15853 				 * chance that the current failfast condition
15854 				 * is transient and recoverable. If that does
15855 				 * not turn out to be the case, then retries
15856 				 * will be cleared when the wait queue is
15857 				 * flushed anyway.
15858 				 */
15859 #endif
15860 			}
15861 		}
15862 	} else {
15863 		/*
15864 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15865 		 * likely were able to at least establish some level of
15866 		 * communication with the target and subsequent commands
15867 		 * and/or retries are likely to get through to the target,
15868 		 * In this case we want to be aggressive about clearing
15869 		 * the failfast state. Note that this does not affect
15870 		 * the "failfast pending" condition.
15871 		 */
15872 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15873 	}
15874 
15875 
15876 	/*
15877 	 * Check the specified retry count to see if we can still do
15878 	 * any retries with this pkt before we should fail it.
15879 	 */
15880 	switch (retry_check_flag & SD_RETRIES_MASK) {
15881 	case SD_RETRIES_VICTIM:
15882 		/*
15883 		 * Check the victim retry count. If exhausted, then fall
15884 		 * thru & check against the standard retry count.
15885 		 */
15886 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15887 			/* Increment count & proceed with the retry */
15888 			xp->xb_victim_retry_count++;
15889 			break;
15890 		}
15891 		/* Victim retries exhausted, fall back to std. retries... */
15892 		/* FALLTHRU */
15893 
15894 	case SD_RETRIES_STANDARD:
15895 		if (xp->xb_retry_count >= un->un_retry_count) {
15896 			/* Retries exhausted, fail the command */
15897 			SD_TRACE(SD_LOG_IO_CORE, un,
15898 			    "sd_retry_command: retries exhausted!\n");
15899 			/*
15900 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15901 			 * commands with nonzero pkt_resid.
15902 			 */
15903 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15904 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15905 			    (pktp->pkt_resid != 0)) {
15906 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15907 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15908 					SD_UPDATE_B_RESID(bp, pktp);
15909 				}
15910 			}
15911 			goto fail_command;
15912 		}
15913 		xp->xb_retry_count++;
15914 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15915 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15916 		break;
15917 
15918 	case SD_RETRIES_UA:
15919 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15920 			/* Retries exhausted, fail the command */
15921 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15922 			    "Unit Attention retries exhausted. "
15923 			    "Check the target.\n");
15924 			goto fail_command;
15925 		}
15926 		xp->xb_ua_retry_count++;
15927 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15928 		    "sd_retry_command: retry count:%d\n",
15929 		    xp->xb_ua_retry_count);
15930 		break;
15931 
15932 	case SD_RETRIES_BUSY:
15933 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15934 			/* Retries exhausted, fail the command */
15935 			SD_TRACE(SD_LOG_IO_CORE, un,
15936 			    "sd_retry_command: retries exhausted!\n");
15937 			goto fail_command;
15938 		}
15939 		xp->xb_retry_count++;
15940 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15941 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15942 		break;
15943 
15944 	case SD_RETRIES_NOCHECK:
15945 	default:
15946 		/* No retry count to check. Just proceed with the retry */
15947 		break;
15948 	}
15949 
15950 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15951 
15952 	/*
15953 	 * If this is a non-USCSI command being retried
15954 	 * during execution last time, we should post an ereport with
15955 	 * driver-assessment of the value "retry".
15956 	 * For partial DMA, request sense and STATUS_QFULL, there are no
15957 	 * hardware errors, we bypass ereport posting.
15958 	 */
15959 	if (failure_code != 0) {
15960 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15961 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15962 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RETRY);
15963 		}
15964 	}
15965 
15966 	/*
15967 	 * If we were given a zero timeout, we must attempt to retry the
15968 	 * command immediately (ie, without a delay).
15969 	 */
15970 	if (retry_delay == 0) {
15971 		/*
15972 		 * Check some limiting conditions to see if we can actually
15973 		 * do the immediate retry.  If we cannot, then we must
15974 		 * fall back to queueing up a delayed retry.
15975 		 */
15976 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15977 			/*
15978 			 * We are at the throttle limit for the target,
15979 			 * fall back to delayed retry.
15980 			 */
15981 			retry_delay = un->un_busy_timeout;
15982 			statp = kstat_waitq_enter;
15983 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15984 			    "sd_retry_command: immed. retry hit "
15985 			    "throttle!\n");
15986 		} else {
15987 			/*
15988 			 * We're clear to proceed with the immediate retry.
15989 			 * First call the user-provided function (if any)
15990 			 */
15991 			if (user_funcp != NULL) {
15992 				(*user_funcp)(un, bp, user_arg,
15993 				    SD_IMMEDIATE_RETRY_ISSUED);
15994 #ifdef __lock_lint
15995 				sd_print_incomplete_msg(un, bp, user_arg,
15996 				    SD_IMMEDIATE_RETRY_ISSUED);
15997 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15998 				    SD_IMMEDIATE_RETRY_ISSUED);
15999 				sd_print_sense_failed_msg(un, bp, user_arg,
16000 				    SD_IMMEDIATE_RETRY_ISSUED);
16001 #endif
16002 			}
16003 
16004 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16005 			    "sd_retry_command: issuing immediate retry\n");
16006 
16007 			/*
16008 			 * Call sd_start_cmds() to transport the command to
16009 			 * the target.
16010 			 */
16011 			sd_start_cmds(un, bp);
16012 
16013 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16014 			    "sd_retry_command exit\n");
16015 			return;
16016 		}
16017 	}
16018 
16019 	/*
16020 	 * Set up to retry the command after a delay.
16021 	 * First call the user-provided function (if any)
16022 	 */
16023 	if (user_funcp != NULL) {
16024 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
16025 	}
16026 
16027 	sd_set_retry_bp(un, bp, retry_delay, statp);
16028 
16029 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
16030 	return;
16031 
16032 fail_command:
16033 
16034 	if (user_funcp != NULL) {
16035 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
16036 	}
16037 
16038 fail_command_no_log:
16039 
16040 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16041 	    "sd_retry_command: returning failed command\n");
16042 
16043 	sd_return_failed_command(un, bp, failure_code);
16044 
16045 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
16046 }
16047 
16048 
16049 /*
16050  *    Function: sd_set_retry_bp
16051  *
16052  * Description: Set up the given bp for retry.
16053  *
16054  *   Arguments: un - ptr to associated softstate
16055  *		bp - ptr to buf(9S) for the command
16056  *		retry_delay - time interval before issuing retry (may be 0)
16057  *		statp - optional pointer to kstat function
16058  *
16059  *     Context: May be called under interrupt context
16060  */
16061 
16062 static void
16063 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
16064     void (*statp)(kstat_io_t *))
16065 {
16066 	ASSERT(un != NULL);
16067 	ASSERT(mutex_owned(SD_MUTEX(un)));
16068 	ASSERT(bp != NULL);
16069 
16070 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16071 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
16072 
16073 	/*
16074 	 * Indicate that the command is being retried. This will not allow any
16075 	 * other commands on the wait queue to be transported to the target
16076 	 * until this command has been completed (success or failure). The
16077 	 * "retry command" is not transported to the target until the given
16078 	 * time delay expires, unless the user specified a 0 retry_delay.
16079 	 *
16080 	 * Note: the timeout(9F) callback routine is what actually calls
16081 	 * sd_start_cmds() to transport the command, with the exception of a
16082 	 * zero retry_delay. The only current implementor of a zero retry delay
16083 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
16084 	 */
16085 	if (un->un_retry_bp == NULL) {
16086 		ASSERT(un->un_retry_statp == NULL);
16087 		un->un_retry_bp = bp;
16088 
16089 		/*
16090 		 * If the user has not specified a delay the command should
16091 		 * be queued and no timeout should be scheduled.
16092 		 */
16093 		if (retry_delay == 0) {
16094 			/*
16095 			 * Save the kstat pointer that will be used in the
16096 			 * call to SD_UPDATE_KSTATS() below, so that
16097 			 * sd_start_cmds() can correctly decrement the waitq
16098 			 * count when it is time to transport this command.
16099 			 */
16100 			un->un_retry_statp = statp;
16101 			goto done;
16102 		}
16103 	}
16104 
16105 	if (un->un_retry_bp == bp) {
16106 		/*
16107 		 * Save the kstat pointer that will be used in the call to
16108 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
16109 		 * correctly decrement the waitq count when it is time to
16110 		 * transport this command.
16111 		 */
16112 		un->un_retry_statp = statp;
16113 
16114 		/*
16115 		 * Schedule a timeout if:
16116 		 *   1) The user has specified a delay.
16117 		 *   2) There is not a START_STOP_UNIT callback pending.
16118 		 *
16119 		 * If no delay has been specified, then it is up to the caller
16120 		 * to ensure that IO processing continues without stalling.
16121 		 * Effectively, this means that the caller will issue the
16122 		 * required call to sd_start_cmds(). The START_STOP_UNIT
16123 		 * callback does this after the START STOP UNIT command has
16124 		 * completed. In either of these cases we should not schedule
16125 		 * a timeout callback here.  Also don't schedule the timeout if
16126 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
16127 		 */
16128 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
16129 		    (un->un_direct_priority_timeid == NULL)) {
16130 			un->un_retry_timeid =
16131 			    timeout(sd_start_retry_command, un, retry_delay);
16132 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16133 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
16134 			    " bp:0x%p un_retry_timeid:0x%p\n",
16135 			    un, bp, un->un_retry_timeid);
16136 		}
16137 	} else {
16138 		/*
16139 		 * We only get in here if there is already another command
16140 		 * waiting to be retried.  In this case, we just put the
16141 		 * given command onto the wait queue, so it can be transported
16142 		 * after the current retry command has completed.
16143 		 *
16144 		 * Also we have to make sure that if the command at the head
16145 		 * of the wait queue is the un_failfast_bp, that we do not
16146 		 * put ahead of it any other commands that are to be retried.
16147 		 */
16148 		if ((un->un_failfast_bp != NULL) &&
16149 		    (un->un_failfast_bp == un->un_waitq_headp)) {
16150 			/*
16151 			 * Enqueue this command AFTER the first command on
16152 			 * the wait queue (which is also un_failfast_bp).
16153 			 */
16154 			bp->av_forw = un->un_waitq_headp->av_forw;
16155 			un->un_waitq_headp->av_forw = bp;
16156 			if (un->un_waitq_headp == un->un_waitq_tailp) {
16157 				un->un_waitq_tailp = bp;
16158 			}
16159 		} else {
16160 			/* Enqueue this command at the head of the waitq. */
16161 			bp->av_forw = un->un_waitq_headp;
16162 			un->un_waitq_headp = bp;
16163 			if (un->un_waitq_tailp == NULL) {
16164 				un->un_waitq_tailp = bp;
16165 			}
16166 		}
16167 
16168 		if (statp == NULL) {
16169 			statp = kstat_waitq_enter;
16170 		}
16171 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16172 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
16173 	}
16174 
16175 done:
16176 	if (statp != NULL) {
16177 		SD_UPDATE_KSTATS(un, statp, bp);
16178 	}
16179 
16180 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16181 	    "sd_set_retry_bp: exit un:0x%p\n", un);
16182 }
16183 
16184 
16185 /*
16186  *    Function: sd_start_retry_command
16187  *
16188  * Description: Start the command that has been waiting on the target's
16189  *		retry queue.  Called from timeout(9F) context after the
16190  *		retry delay interval has expired.
16191  *
16192  *   Arguments: arg - pointer to associated softstate for the device.
16193  *
16194  *     Context: timeout(9F) thread context.  May not sleep.
16195  */
16196 
16197 static void
16198 sd_start_retry_command(void *arg)
16199 {
16200 	struct sd_lun *un = arg;
16201 
16202 	ASSERT(un != NULL);
16203 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16204 
16205 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16206 	    "sd_start_retry_command: entry\n");
16207 
16208 	mutex_enter(SD_MUTEX(un));
16209 
16210 	un->un_retry_timeid = NULL;
16211 
16212 	if (un->un_retry_bp != NULL) {
16213 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16214 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
16215 		    un, un->un_retry_bp);
16216 		sd_start_cmds(un, un->un_retry_bp);
16217 	}
16218 
16219 	mutex_exit(SD_MUTEX(un));
16220 
16221 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16222 	    "sd_start_retry_command: exit\n");
16223 }
16224 
16225 /*
16226  *    Function: sd_rmw_msg_print_handler
16227  *
16228  * Description: If RMW mode is enabled and warning message is triggered
16229  *              print I/O count during a fixed interval.
16230  *
16231  *   Arguments: arg - pointer to associated softstate for the device.
16232  *
16233  *     Context: timeout(9F) thread context. May not sleep.
16234  */
16235 static void
16236 sd_rmw_msg_print_handler(void *arg)
16237 {
16238 	struct sd_lun *un = arg;
16239 
16240 	ASSERT(un != NULL);
16241 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16242 
16243 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16244 	    "sd_rmw_msg_print_handler: entry\n");
16245 
16246 	mutex_enter(SD_MUTEX(un));
16247 
16248 	if (un->un_rmw_incre_count > 0) {
16249 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16250 		    "%"PRIu64" I/O requests are not aligned with %d disk "
16251 		    "sector size in %ld seconds. They are handled through "
16252 		    "Read Modify Write but the performance is very low!\n",
16253 		    un->un_rmw_incre_count, un->un_tgt_blocksize,
16254 		    drv_hztousec(SD_RMW_MSG_PRINT_TIMEOUT) / 1000000);
16255 		un->un_rmw_incre_count = 0;
16256 		un->un_rmw_msg_timeid = timeout(sd_rmw_msg_print_handler,
16257 		    un, SD_RMW_MSG_PRINT_TIMEOUT);
16258 	} else {
16259 		un->un_rmw_msg_timeid = NULL;
16260 	}
16261 
16262 	mutex_exit(SD_MUTEX(un));
16263 
16264 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16265 	    "sd_rmw_msg_print_handler: exit\n");
16266 }
16267 
16268 /*
16269  *    Function: sd_start_direct_priority_command
16270  *
16271  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
16272  *		received TRAN_BUSY when we called scsi_transport() to send it
16273  *		to the underlying HBA. This function is called from timeout(9F)
16274  *		context after the delay interval has expired.
16275  *
16276  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
16277  *
16278  *     Context: timeout(9F) thread context.  May not sleep.
16279  */
16280 
16281 static void
16282 sd_start_direct_priority_command(void *arg)
16283 {
16284 	struct buf	*priority_bp = arg;
16285 	struct sd_lun	*un;
16286 
16287 	ASSERT(priority_bp != NULL);
16288 	un = SD_GET_UN(priority_bp);
16289 	ASSERT(un != NULL);
16290 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16291 
16292 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16293 	    "sd_start_direct_priority_command: entry\n");
16294 
16295 	mutex_enter(SD_MUTEX(un));
16296 	un->un_direct_priority_timeid = NULL;
16297 	sd_start_cmds(un, priority_bp);
16298 	mutex_exit(SD_MUTEX(un));
16299 
16300 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16301 	    "sd_start_direct_priority_command: exit\n");
16302 }
16303 
16304 
16305 /*
16306  *    Function: sd_send_request_sense_command
16307  *
16308  * Description: Sends a REQUEST SENSE command to the target
16309  *
16310  *     Context: May be called from interrupt context.
16311  */
16312 
16313 static void
16314 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
16315     struct scsi_pkt *pktp)
16316 {
16317 	ASSERT(bp != NULL);
16318 	ASSERT(un != NULL);
16319 	ASSERT(mutex_owned(SD_MUTEX(un)));
16320 
16321 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
16322 	    "entry: buf:0x%p\n", bp);
16323 
16324 	/*
16325 	 * If we are syncing or dumping, then fail the command to avoid a
16326 	 * recursive callback into scsi_transport(). Also fail the command
16327 	 * if we are suspended (legacy behavior).
16328 	 */
16329 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
16330 	    (un->un_state == SD_STATE_DUMPING)) {
16331 		sd_return_failed_command(un, bp, EIO);
16332 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16333 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
16334 		return;
16335 	}
16336 
16337 	/*
16338 	 * Retry the failed command and don't issue the request sense if:
16339 	 *    1) the sense buf is busy
16340 	 *    2) we have 1 or more outstanding commands on the target
16341 	 *    (the sense data will be cleared or invalidated any way)
16342 	 *
16343 	 * Note: There could be an issue with not checking a retry limit here,
16344 	 * the problem is determining which retry limit to check.
16345 	 */
16346 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
16347 		/* Don't retry if the command is flagged as non-retryable */
16348 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16349 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
16350 			    NULL, NULL, 0, un->un_busy_timeout,
16351 			    kstat_waitq_enter);
16352 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16353 			    "sd_send_request_sense_command: "
16354 			    "at full throttle, retrying exit\n");
16355 		} else {
16356 			sd_return_failed_command(un, bp, EIO);
16357 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16358 			    "sd_send_request_sense_command: "
16359 			    "at full throttle, non-retryable exit\n");
16360 		}
16361 		return;
16362 	}
16363 
16364 	sd_mark_rqs_busy(un, bp);
16365 	sd_start_cmds(un, un->un_rqs_bp);
16366 
16367 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16368 	    "sd_send_request_sense_command: exit\n");
16369 }
16370 
16371 
16372 /*
16373  *    Function: sd_mark_rqs_busy
16374  *
16375  * Description: Indicate that the request sense bp for this instance is
16376  *		in use.
16377  *
16378  *     Context: May be called under interrupt context
16379  */
16380 
16381 static void
16382 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
16383 {
16384 	struct sd_xbuf	*sense_xp;
16385 
16386 	ASSERT(un != NULL);
16387 	ASSERT(bp != NULL);
16388 	ASSERT(mutex_owned(SD_MUTEX(un)));
16389 	ASSERT(un->un_sense_isbusy == 0);
16390 
16391 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
16392 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
16393 
16394 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
16395 	ASSERT(sense_xp != NULL);
16396 
16397 	SD_INFO(SD_LOG_IO, un,
16398 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
16399 
16400 	ASSERT(sense_xp->xb_pktp != NULL);
16401 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
16402 	    == (FLAG_SENSING | FLAG_HEAD));
16403 
16404 	un->un_sense_isbusy = 1;
16405 	un->un_rqs_bp->b_resid = 0;
16406 	sense_xp->xb_pktp->pkt_resid  = 0;
16407 	sense_xp->xb_pktp->pkt_reason = 0;
16408 
16409 	/* So we can get back the bp at interrupt time! */
16410 	sense_xp->xb_sense_bp = bp;
16411 
16412 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
16413 
16414 	/*
16415 	 * Mark this buf as awaiting sense data. (This is already set in
16416 	 * the pkt_flags for the RQS packet.)
16417 	 */
16418 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
16419 
16420 	/* Request sense down same path */
16421 	if (scsi_pkt_allocated_correctly((SD_GET_XBUF(bp))->xb_pktp) &&
16422 	    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance)
16423 		sense_xp->xb_pktp->pkt_path_instance =
16424 		    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance;
16425 
16426 	sense_xp->xb_retry_count = 0;
16427 	sense_xp->xb_victim_retry_count = 0;
16428 	sense_xp->xb_ua_retry_count = 0;
16429 	sense_xp->xb_nr_retry_count = 0;
16430 	sense_xp->xb_dma_resid  = 0;
16431 
16432 	/* Clean up the fields for auto-request sense */
16433 	sense_xp->xb_sense_status = 0;
16434 	sense_xp->xb_sense_state = 0;
16435 	sense_xp->xb_sense_resid = 0;
16436 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
16437 
16438 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
16439 }
16440 
16441 
16442 /*
16443  *    Function: sd_mark_rqs_idle
16444  *
16445  * Description: SD_MUTEX must be held continuously through this routine
16446  *		to prevent reuse of the rqs struct before the caller can
16447  *		complete it's processing.
16448  *
16449  * Return Code: Pointer to the RQS buf
16450  *
16451  *     Context: May be called under interrupt context
16452  */
16453 
16454 static struct buf *
16455 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
16456 {
16457 	struct buf *bp;
16458 	ASSERT(un != NULL);
16459 	ASSERT(sense_xp != NULL);
16460 	ASSERT(mutex_owned(SD_MUTEX(un)));
16461 	ASSERT(un->un_sense_isbusy != 0);
16462 
16463 	un->un_sense_isbusy = 0;
16464 	bp = sense_xp->xb_sense_bp;
16465 	sense_xp->xb_sense_bp = NULL;
16466 
16467 	/* This pkt is no longer interested in getting sense data */
16468 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
16469 
16470 	return (bp);
16471 }
16472 
16473 
16474 
16475 /*
16476  *    Function: sd_alloc_rqs
16477  *
16478  * Description: Set up the unit to receive auto request sense data
16479  *
16480  * Return Code: DDI_SUCCESS or DDI_FAILURE
16481  *
16482  *     Context: Called under attach(9E) context
16483  */
16484 
16485 static int
16486 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
16487 {
16488 	struct sd_xbuf *xp;
16489 
16490 	ASSERT(un != NULL);
16491 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16492 	ASSERT(un->un_rqs_bp == NULL);
16493 	ASSERT(un->un_rqs_pktp == NULL);
16494 
16495 	/*
16496 	 * First allocate the required buf and scsi_pkt structs, then set up
16497 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
16498 	 */
16499 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
16500 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
16501 	if (un->un_rqs_bp == NULL) {
16502 		return (DDI_FAILURE);
16503 	}
16504 
16505 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
16506 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
16507 
16508 	if (un->un_rqs_pktp == NULL) {
16509 		sd_free_rqs(un);
16510 		return (DDI_FAILURE);
16511 	}
16512 
16513 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
16514 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
16515 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
16516 
16517 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
16518 
16519 	/* Set up the other needed members in the ARQ scsi_pkt. */
16520 	un->un_rqs_pktp->pkt_comp   = sdintr;
16521 	un->un_rqs_pktp->pkt_time   = sd_io_time;
16522 	un->un_rqs_pktp->pkt_flags |=
16523 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
16524 
16525 	/*
16526 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
16527 	 * provide any intpkt, destroypkt routines as we take care of
16528 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
16529 	 */
16530 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
16531 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
16532 	xp->xb_pktp = un->un_rqs_pktp;
16533 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
16534 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
16535 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
16536 
16537 	/*
16538 	 * Save the pointer to the request sense private bp so it can
16539 	 * be retrieved in sdintr.
16540 	 */
16541 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
16542 	ASSERT(un->un_rqs_bp->b_private == xp);
16543 
16544 	/*
16545 	 * See if the HBA supports auto-request sense for the specified
16546 	 * target/lun. If it does, then try to enable it (if not already
16547 	 * enabled).
16548 	 *
16549 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
16550 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
16551 	 * return success.  However, in both of these cases ARQ is always
16552 	 * enabled and scsi_ifgetcap will always return true. The best approach
16553 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
16554 	 *
16555 	 * The 3rd case is the HBA (adp) always return enabled on
16556 	 * scsi_ifgetgetcap even when it's not enable, the best approach
16557 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
16558 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
16559 	 */
16560 
16561 	if (un->un_f_is_fibre == TRUE) {
16562 		un->un_f_arq_enabled = TRUE;
16563 	} else {
16564 #if defined(__x86)
16565 		/*
16566 		 * Circumvent the Adaptec bug, remove this code when
16567 		 * the bug is fixed
16568 		 */
16569 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
16570 #endif
16571 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
16572 		case 0:
16573 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16574 			    "sd_alloc_rqs: HBA supports ARQ\n");
16575 			/*
16576 			 * ARQ is supported by this HBA but currently is not
16577 			 * enabled. Attempt to enable it and if successful then
16578 			 * mark this instance as ARQ enabled.
16579 			 */
16580 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
16581 			    == 1) {
16582 				/* Successfully enabled ARQ in the HBA */
16583 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16584 				    "sd_alloc_rqs: ARQ enabled\n");
16585 				un->un_f_arq_enabled = TRUE;
16586 			} else {
16587 				/* Could not enable ARQ in the HBA */
16588 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16589 				    "sd_alloc_rqs: failed ARQ enable\n");
16590 				un->un_f_arq_enabled = FALSE;
16591 			}
16592 			break;
16593 		case 1:
16594 			/*
16595 			 * ARQ is supported by this HBA and is already enabled.
16596 			 * Just mark ARQ as enabled for this instance.
16597 			 */
16598 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16599 			    "sd_alloc_rqs: ARQ already enabled\n");
16600 			un->un_f_arq_enabled = TRUE;
16601 			break;
16602 		default:
16603 			/*
16604 			 * ARQ is not supported by this HBA; disable it for this
16605 			 * instance.
16606 			 */
16607 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16608 			    "sd_alloc_rqs: HBA does not support ARQ\n");
16609 			un->un_f_arq_enabled = FALSE;
16610 			break;
16611 		}
16612 	}
16613 
16614 	return (DDI_SUCCESS);
16615 }
16616 
16617 
16618 /*
16619  *    Function: sd_free_rqs
16620  *
16621  * Description: Cleanup for the pre-instance RQS command.
16622  *
16623  *     Context: Kernel thread context
16624  */
16625 
16626 static void
16627 sd_free_rqs(struct sd_lun *un)
16628 {
16629 	ASSERT(un != NULL);
16630 
16631 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
16632 
16633 	/*
16634 	 * If consistent memory is bound to a scsi_pkt, the pkt
16635 	 * has to be destroyed *before* freeing the consistent memory.
16636 	 * Don't change the sequence of this operations.
16637 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
16638 	 * after it was freed in scsi_free_consistent_buf().
16639 	 */
16640 	if (un->un_rqs_pktp != NULL) {
16641 		scsi_destroy_pkt(un->un_rqs_pktp);
16642 		un->un_rqs_pktp = NULL;
16643 	}
16644 
16645 	if (un->un_rqs_bp != NULL) {
16646 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
16647 		if (xp != NULL) {
16648 			kmem_free(xp, sizeof (struct sd_xbuf));
16649 		}
16650 		scsi_free_consistent_buf(un->un_rqs_bp);
16651 		un->un_rqs_bp = NULL;
16652 	}
16653 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
16654 }
16655 
16656 
16657 
16658 /*
16659  *    Function: sd_reduce_throttle
16660  *
16661  * Description: Reduces the maximum # of outstanding commands on a
16662  *		target to the current number of outstanding commands.
16663  *		Queues a tiemout(9F) callback to restore the limit
16664  *		after a specified interval has elapsed.
16665  *		Typically used when we get a TRAN_BUSY return code
16666  *		back from scsi_transport().
16667  *
16668  *   Arguments: un - ptr to the sd_lun softstate struct
16669  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
16670  *
16671  *     Context: May be called from interrupt context
16672  */
16673 
16674 static void
16675 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
16676 {
16677 	ASSERT(un != NULL);
16678 	ASSERT(mutex_owned(SD_MUTEX(un)));
16679 	ASSERT(un->un_ncmds_in_transport >= 0);
16680 
16681 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16682 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
16683 	    un, un->un_throttle, un->un_ncmds_in_transport);
16684 
16685 	if (un->un_throttle > 1) {
16686 		if (un->un_f_use_adaptive_throttle == TRUE) {
16687 			switch (throttle_type) {
16688 			case SD_THROTTLE_TRAN_BUSY:
16689 				if (un->un_busy_throttle == 0) {
16690 					un->un_busy_throttle = un->un_throttle;
16691 				}
16692 				break;
16693 			case SD_THROTTLE_QFULL:
16694 				un->un_busy_throttle = 0;
16695 				break;
16696 			default:
16697 				ASSERT(FALSE);
16698 			}
16699 
16700 			if (un->un_ncmds_in_transport > 0) {
16701 				un->un_throttle = un->un_ncmds_in_transport;
16702 			}
16703 
16704 		} else {
16705 			if (un->un_ncmds_in_transport == 0) {
16706 				un->un_throttle = 1;
16707 			} else {
16708 				un->un_throttle = un->un_ncmds_in_transport;
16709 			}
16710 		}
16711 	}
16712 
16713 	/* Reschedule the timeout if none is currently active */
16714 	if (un->un_reset_throttle_timeid == NULL) {
16715 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
16716 		    un, SD_THROTTLE_RESET_INTERVAL);
16717 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16718 		    "sd_reduce_throttle: timeout scheduled!\n");
16719 	}
16720 
16721 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16722 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16723 }
16724 
16725 
16726 
16727 /*
16728  *    Function: sd_restore_throttle
16729  *
16730  * Description: Callback function for timeout(9F).  Resets the current
16731  *		value of un->un_throttle to its default.
16732  *
16733  *   Arguments: arg - pointer to associated softstate for the device.
16734  *
16735  *     Context: May be called from interrupt context
16736  */
16737 
16738 static void
16739 sd_restore_throttle(void *arg)
16740 {
16741 	struct sd_lun	*un = arg;
16742 
16743 	ASSERT(un != NULL);
16744 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16745 
16746 	mutex_enter(SD_MUTEX(un));
16747 
16748 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16749 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16750 
16751 	un->un_reset_throttle_timeid = NULL;
16752 
16753 	if (un->un_f_use_adaptive_throttle == TRUE) {
16754 		/*
16755 		 * If un_busy_throttle is nonzero, then it contains the
16756 		 * value that un_throttle was when we got a TRAN_BUSY back
16757 		 * from scsi_transport(). We want to revert back to this
16758 		 * value.
16759 		 *
16760 		 * In the QFULL case, the throttle limit will incrementally
16761 		 * increase until it reaches max throttle.
16762 		 */
16763 		if (un->un_busy_throttle > 0) {
16764 			un->un_throttle = un->un_busy_throttle;
16765 			un->un_busy_throttle = 0;
16766 		} else {
16767 			/*
16768 			 * increase throttle by 10% open gate slowly, schedule
16769 			 * another restore if saved throttle has not been
16770 			 * reached
16771 			 */
16772 			short throttle;
16773 			if (sd_qfull_throttle_enable) {
16774 				throttle = un->un_throttle +
16775 				    max((un->un_throttle / 10), 1);
16776 				un->un_throttle =
16777 				    (throttle < un->un_saved_throttle) ?
16778 				    throttle : un->un_saved_throttle;
16779 				if (un->un_throttle < un->un_saved_throttle) {
16780 					un->un_reset_throttle_timeid =
16781 					    timeout(sd_restore_throttle,
16782 					    un,
16783 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
16784 				}
16785 			}
16786 		}
16787 
16788 		/*
16789 		 * If un_throttle has fallen below the low-water mark, we
16790 		 * restore the maximum value here (and allow it to ratchet
16791 		 * down again if necessary).
16792 		 */
16793 		if (un->un_throttle < un->un_min_throttle) {
16794 			un->un_throttle = un->un_saved_throttle;
16795 		}
16796 	} else {
16797 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16798 		    "restoring limit from 0x%x to 0x%x\n",
16799 		    un->un_throttle, un->un_saved_throttle);
16800 		un->un_throttle = un->un_saved_throttle;
16801 	}
16802 
16803 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16804 	    "sd_restore_throttle: calling sd_start_cmds!\n");
16805 
16806 	sd_start_cmds(un, NULL);
16807 
16808 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16809 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
16810 	    un, un->un_throttle);
16811 
16812 	mutex_exit(SD_MUTEX(un));
16813 
16814 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16815 }
16816 
16817 /*
16818  *    Function: sdrunout
16819  *
16820  * Description: Callback routine for scsi_init_pkt when a resource allocation
16821  *		fails.
16822  *
16823  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16824  *		soft state instance.
16825  *
16826  * Return Code: The scsi_init_pkt routine allows for the callback function to
16827  *		return a 0 indicating the callback should be rescheduled or a 1
16828  *		indicating not to reschedule. This routine always returns 1
16829  *		because the driver always provides a callback function to
16830  *		scsi_init_pkt. This results in a callback always being scheduled
16831  *		(via the scsi_init_pkt callback implementation) if a resource
16832  *		failure occurs.
16833  *
16834  *     Context: This callback function may not block or call routines that block
16835  *
16836  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16837  *		request persisting at the head of the list which cannot be
16838  *		satisfied even after multiple retries. In the future the driver
16839  *		may implement some time of maximum runout count before failing
16840  *		an I/O.
16841  */
16842 
16843 static int
16844 sdrunout(caddr_t arg)
16845 {
16846 	struct sd_lun	*un = (struct sd_lun *)arg;
16847 
16848 	ASSERT(un != NULL);
16849 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16850 
16851 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16852 
16853 	mutex_enter(SD_MUTEX(un));
16854 	sd_start_cmds(un, NULL);
16855 	mutex_exit(SD_MUTEX(un));
16856 	/*
16857 	 * This callback routine always returns 1 (i.e. do not reschedule)
16858 	 * because we always specify sdrunout as the callback handler for
16859 	 * scsi_init_pkt inside the call to sd_start_cmds.
16860 	 */
16861 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16862 	return (1);
16863 }
16864 
16865 
16866 /*
16867  *    Function: sdintr
16868  *
16869  * Description: Completion callback routine for scsi_pkt(9S) structs
16870  *		sent to the HBA driver via scsi_transport(9F).
16871  *
16872  *     Context: Interrupt context
16873  */
16874 
16875 static void
16876 sdintr(struct scsi_pkt *pktp)
16877 {
16878 	struct buf	*bp;
16879 	struct sd_xbuf	*xp;
16880 	struct sd_lun	*un;
16881 	size_t		actual_len;
16882 	sd_ssc_t	*sscp;
16883 
16884 	ASSERT(pktp != NULL);
16885 	bp = (struct buf *)pktp->pkt_private;
16886 	ASSERT(bp != NULL);
16887 	xp = SD_GET_XBUF(bp);
16888 	ASSERT(xp != NULL);
16889 	ASSERT(xp->xb_pktp != NULL);
16890 	un = SD_GET_UN(bp);
16891 	ASSERT(un != NULL);
16892 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16893 
16894 #ifdef SD_FAULT_INJECTION
16895 
16896 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16897 	/* SD FaultInjection */
16898 	sd_faultinjection(pktp);
16899 
16900 #endif /* SD_FAULT_INJECTION */
16901 
16902 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16903 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16904 
16905 	mutex_enter(SD_MUTEX(un));
16906 
16907 	ASSERT(un->un_fm_private != NULL);
16908 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16909 	ASSERT(sscp != NULL);
16910 
16911 	/* Reduce the count of the #commands currently in transport */
16912 	un->un_ncmds_in_transport--;
16913 	ASSERT(un->un_ncmds_in_transport >= 0);
16914 
16915 	/* Increment counter to indicate that the callback routine is active */
16916 	un->un_in_callback++;
16917 
16918 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16919 
16920 #ifdef	SDDEBUG
16921 	if (bp == un->un_retry_bp) {
16922 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16923 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16924 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16925 	}
16926 #endif
16927 
16928 	/*
16929 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
16930 	 * state if needed.
16931 	 */
16932 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16933 		/* Prevent multiple console messages for the same failure. */
16934 		if (un->un_last_pkt_reason != CMD_DEV_GONE) {
16935 			un->un_last_pkt_reason = CMD_DEV_GONE;
16936 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16937 			    "Command failed to complete...Device is gone\n");
16938 		}
16939 		if (un->un_mediastate != DKIO_DEV_GONE) {
16940 			un->un_mediastate = DKIO_DEV_GONE;
16941 			cv_broadcast(&un->un_state_cv);
16942 		}
16943 		/*
16944 		 * If the command happens to be the REQUEST SENSE command,
16945 		 * free up the rqs buf and fail the original command.
16946 		 */
16947 		if (bp == un->un_rqs_bp) {
16948 			bp = sd_mark_rqs_idle(un, xp);
16949 		}
16950 		sd_return_failed_command(un, bp, EIO);
16951 		goto exit;
16952 	}
16953 
16954 	if (pktp->pkt_state & STATE_XARQ_DONE) {
16955 		SD_TRACE(SD_LOG_COMMON, un,
16956 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
16957 	}
16958 
16959 	/*
16960 	 * First see if the pkt has auto-request sense data with it....
16961 	 * Look at the packet state first so we don't take a performance
16962 	 * hit looking at the arq enabled flag unless absolutely necessary.
16963 	 */
16964 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16965 	    (un->un_f_arq_enabled == TRUE)) {
16966 		/*
16967 		 * The HBA did an auto request sense for this command so check
16968 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16969 		 * driver command that should not be retried.
16970 		 */
16971 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16972 			/*
16973 			 * Save the relevant sense info into the xp for the
16974 			 * original cmd.
16975 			 */
16976 			struct scsi_arq_status *asp;
16977 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16978 			xp->xb_sense_status =
16979 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16980 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16981 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16982 			if (pktp->pkt_state & STATE_XARQ_DONE) {
16983 				actual_len = MAX_SENSE_LENGTH -
16984 				    xp->xb_sense_resid;
16985 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16986 				    MAX_SENSE_LENGTH);
16987 			} else {
16988 				if (xp->xb_sense_resid > SENSE_LENGTH) {
16989 					actual_len = MAX_SENSE_LENGTH -
16990 					    xp->xb_sense_resid;
16991 				} else {
16992 					actual_len = SENSE_LENGTH -
16993 					    xp->xb_sense_resid;
16994 				}
16995 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16996 					if ((((struct uscsi_cmd *)
16997 					    (xp->xb_pktinfo))->uscsi_rqlen) >
16998 					    actual_len) {
16999 						xp->xb_sense_resid =
17000 						    (((struct uscsi_cmd *)
17001 						    (xp->xb_pktinfo))->
17002 						    uscsi_rqlen) - actual_len;
17003 					} else {
17004 						xp->xb_sense_resid = 0;
17005 					}
17006 				}
17007 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
17008 				    SENSE_LENGTH);
17009 			}
17010 
17011 			/* fail the command */
17012 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17013 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
17014 			sd_return_failed_command(un, bp, EIO);
17015 			goto exit;
17016 		}
17017 
17018 #if (defined(__x86))	/* DMAFREE for x86 only */
17019 		/*
17020 		 * We want to either retry or fail this command, so free
17021 		 * the DMA resources here.  If we retry the command then
17022 		 * the DMA resources will be reallocated in sd_start_cmds().
17023 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
17024 		 * causes the *entire* transfer to start over again from the
17025 		 * beginning of the request, even for PARTIAL chunks that
17026 		 * have already transferred successfully.
17027 		 */
17028 		if ((un->un_f_is_fibre == TRUE) &&
17029 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
17030 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
17031 			scsi_dmafree(pktp);
17032 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
17033 		}
17034 #endif
17035 
17036 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17037 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
17038 
17039 		sd_handle_auto_request_sense(un, bp, xp, pktp);
17040 		goto exit;
17041 	}
17042 
17043 	/* Next see if this is the REQUEST SENSE pkt for the instance */
17044 	if (pktp->pkt_flags & FLAG_SENSING)  {
17045 		/* This pktp is from the unit's REQUEST_SENSE command */
17046 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17047 		    "sdintr: sd_handle_request_sense\n");
17048 		sd_handle_request_sense(un, bp, xp, pktp);
17049 		goto exit;
17050 	}
17051 
17052 	/*
17053 	 * Check to see if the command successfully completed as requested;
17054 	 * this is the most common case (and also the hot performance path).
17055 	 *
17056 	 * Requirements for successful completion are:
17057 	 * pkt_reason is CMD_CMPLT and packet status is status good.
17058 	 * In addition:
17059 	 * - A residual of zero indicates successful completion no matter what
17060 	 *   the command is.
17061 	 * - If the residual is not zero and the command is not a read or
17062 	 *   write, then it's still defined as successful completion. In other
17063 	 *   words, if the command is a read or write the residual must be
17064 	 *   zero for successful completion.
17065 	 * - If the residual is not zero and the command is a read or
17066 	 *   write, and it's a USCSICMD, then it's still defined as
17067 	 *   successful completion.
17068 	 */
17069 	if ((pktp->pkt_reason == CMD_CMPLT) &&
17070 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
17071 
17072 		/*
17073 		 * Since this command is returned with a good status, we
17074 		 * can reset the count for Sonoma failover.
17075 		 */
17076 		un->un_sonoma_failure_count = 0;
17077 
17078 		/*
17079 		 * Return all USCSI commands on good status
17080 		 */
17081 		if (pktp->pkt_resid == 0) {
17082 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17083 			    "sdintr: returning command for resid == 0\n");
17084 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
17085 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
17086 			SD_UPDATE_B_RESID(bp, pktp);
17087 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17088 			    "sdintr: returning command for resid != 0\n");
17089 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17090 			SD_UPDATE_B_RESID(bp, pktp);
17091 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17092 			    "sdintr: returning uscsi command\n");
17093 		} else {
17094 			goto not_successful;
17095 		}
17096 		sd_return_command(un, bp);
17097 
17098 		/*
17099 		 * Decrement counter to indicate that the callback routine
17100 		 * is done.
17101 		 */
17102 		un->un_in_callback--;
17103 		ASSERT(un->un_in_callback >= 0);
17104 		mutex_exit(SD_MUTEX(un));
17105 
17106 		return;
17107 	}
17108 
17109 not_successful:
17110 
17111 #if (defined(__x86))	/* DMAFREE for x86 only */
17112 	/*
17113 	 * The following is based upon knowledge of the underlying transport
17114 	 * and its use of DMA resources.  This code should be removed when
17115 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
17116 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
17117 	 * and sd_start_cmds().
17118 	 *
17119 	 * Free any DMA resources associated with this command if there
17120 	 * is a chance it could be retried or enqueued for later retry.
17121 	 * If we keep the DMA binding then mpxio cannot reissue the
17122 	 * command on another path whenever a path failure occurs.
17123 	 *
17124 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
17125 	 * causes the *entire* transfer to start over again from the
17126 	 * beginning of the request, even for PARTIAL chunks that
17127 	 * have already transferred successfully.
17128 	 *
17129 	 * This is only done for non-uscsi commands (and also skipped for the
17130 	 * driver's internal RQS command). Also just do this for Fibre Channel
17131 	 * devices as these are the only ones that support mpxio.
17132 	 */
17133 	if ((un->un_f_is_fibre == TRUE) &&
17134 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
17135 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
17136 		scsi_dmafree(pktp);
17137 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
17138 	}
17139 #endif
17140 
17141 	/*
17142 	 * The command did not successfully complete as requested so check
17143 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
17144 	 * driver command that should not be retried so just return. If
17145 	 * FLAG_DIAGNOSE is not set the error will be processed below.
17146 	 */
17147 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
17148 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17149 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
17150 		/*
17151 		 * Issue a request sense if a check condition caused the error
17152 		 * (we handle the auto request sense case above), otherwise
17153 		 * just fail the command.
17154 		 */
17155 		if ((pktp->pkt_reason == CMD_CMPLT) &&
17156 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
17157 			sd_send_request_sense_command(un, bp, pktp);
17158 		} else {
17159 			sd_return_failed_command(un, bp, EIO);
17160 		}
17161 		goto exit;
17162 	}
17163 
17164 	/*
17165 	 * The command did not successfully complete as requested so process
17166 	 * the error, retry, and/or attempt recovery.
17167 	 */
17168 	switch (pktp->pkt_reason) {
17169 	case CMD_CMPLT:
17170 		switch (SD_GET_PKT_STATUS(pktp)) {
17171 		case STATUS_GOOD:
17172 			/*
17173 			 * The command completed successfully with a non-zero
17174 			 * residual
17175 			 */
17176 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17177 			    "sdintr: STATUS_GOOD \n");
17178 			sd_pkt_status_good(un, bp, xp, pktp);
17179 			break;
17180 
17181 		case STATUS_CHECK:
17182 		case STATUS_TERMINATED:
17183 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17184 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
17185 			sd_pkt_status_check_condition(un, bp, xp, pktp);
17186 			break;
17187 
17188 		case STATUS_BUSY:
17189 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17190 			    "sdintr: STATUS_BUSY\n");
17191 			sd_pkt_status_busy(un, bp, xp, pktp);
17192 			break;
17193 
17194 		case STATUS_RESERVATION_CONFLICT:
17195 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17196 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
17197 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17198 			break;
17199 
17200 		case STATUS_QFULL:
17201 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17202 			    "sdintr: STATUS_QFULL\n");
17203 			sd_pkt_status_qfull(un, bp, xp, pktp);
17204 			break;
17205 
17206 		case STATUS_MET:
17207 		case STATUS_INTERMEDIATE:
17208 		case STATUS_SCSI2:
17209 		case STATUS_INTERMEDIATE_MET:
17210 		case STATUS_ACA_ACTIVE:
17211 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17212 			    "Unexpected SCSI status received: 0x%x\n",
17213 			    SD_GET_PKT_STATUS(pktp));
17214 			/*
17215 			 * Mark the ssc_flags when detected invalid status
17216 			 * code for non-USCSI command.
17217 			 */
17218 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17219 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17220 				    0, "stat-code");
17221 			}
17222 			sd_return_failed_command(un, bp, EIO);
17223 			break;
17224 
17225 		default:
17226 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17227 			    "Invalid SCSI status received: 0x%x\n",
17228 			    SD_GET_PKT_STATUS(pktp));
17229 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17230 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17231 				    0, "stat-code");
17232 			}
17233 			sd_return_failed_command(un, bp, EIO);
17234 			break;
17235 
17236 		}
17237 		break;
17238 
17239 	case CMD_INCOMPLETE:
17240 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17241 		    "sdintr:  CMD_INCOMPLETE\n");
17242 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
17243 		break;
17244 	case CMD_TRAN_ERR:
17245 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17246 		    "sdintr: CMD_TRAN_ERR\n");
17247 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
17248 		break;
17249 	case CMD_RESET:
17250 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17251 		    "sdintr: CMD_RESET \n");
17252 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
17253 		break;
17254 	case CMD_ABORTED:
17255 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17256 		    "sdintr: CMD_ABORTED \n");
17257 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
17258 		break;
17259 	case CMD_TIMEOUT:
17260 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17261 		    "sdintr: CMD_TIMEOUT\n");
17262 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
17263 		break;
17264 	case CMD_UNX_BUS_FREE:
17265 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17266 		    "sdintr: CMD_UNX_BUS_FREE \n");
17267 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
17268 		break;
17269 	case CMD_TAG_REJECT:
17270 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17271 		    "sdintr: CMD_TAG_REJECT\n");
17272 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
17273 		break;
17274 	default:
17275 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17276 		    "sdintr: default\n");
17277 		/*
17278 		 * Mark the ssc_flags for detecting invliad pkt_reason.
17279 		 */
17280 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17281 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_PKT_REASON,
17282 			    0, "pkt-reason");
17283 		}
17284 		sd_pkt_reason_default(un, bp, xp, pktp);
17285 		break;
17286 	}
17287 
17288 exit:
17289 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
17290 
17291 	/* Decrement counter to indicate that the callback routine is done. */
17292 	un->un_in_callback--;
17293 	ASSERT(un->un_in_callback >= 0);
17294 
17295 	/*
17296 	 * At this point, the pkt has been dispatched, ie, it is either
17297 	 * being re-tried or has been returned to its caller and should
17298 	 * not be referenced.
17299 	 */
17300 
17301 	mutex_exit(SD_MUTEX(un));
17302 }
17303 
17304 
17305 /*
17306  *    Function: sd_print_incomplete_msg
17307  *
17308  * Description: Prints the error message for a CMD_INCOMPLETE error.
17309  *
17310  *   Arguments: un - ptr to associated softstate for the device.
17311  *		bp - ptr to the buf(9S) for the command.
17312  *		arg - message string ptr
17313  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
17314  *			or SD_NO_RETRY_ISSUED.
17315  *
17316  *     Context: May be called under interrupt context
17317  */
17318 
17319 static void
17320 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17321 {
17322 	struct scsi_pkt	*pktp;
17323 	char	*msgp;
17324 	char	*cmdp = arg;
17325 
17326 	ASSERT(un != NULL);
17327 	ASSERT(mutex_owned(SD_MUTEX(un)));
17328 	ASSERT(bp != NULL);
17329 	ASSERT(arg != NULL);
17330 	pktp = SD_GET_PKTP(bp);
17331 	ASSERT(pktp != NULL);
17332 
17333 	switch (code) {
17334 	case SD_DELAYED_RETRY_ISSUED:
17335 	case SD_IMMEDIATE_RETRY_ISSUED:
17336 		msgp = "retrying";
17337 		break;
17338 	case SD_NO_RETRY_ISSUED:
17339 	default:
17340 		msgp = "giving up";
17341 		break;
17342 	}
17343 
17344 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17345 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17346 		    "incomplete %s- %s\n", cmdp, msgp);
17347 	}
17348 }
17349 
17350 
17351 
17352 /*
17353  *    Function: sd_pkt_status_good
17354  *
17355  * Description: Processing for a STATUS_GOOD code in pkt_status.
17356  *
17357  *     Context: May be called under interrupt context
17358  */
17359 
17360 static void
17361 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
17362     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17363 {
17364 	char	*cmdp;
17365 
17366 	ASSERT(un != NULL);
17367 	ASSERT(mutex_owned(SD_MUTEX(un)));
17368 	ASSERT(bp != NULL);
17369 	ASSERT(xp != NULL);
17370 	ASSERT(pktp != NULL);
17371 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
17372 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
17373 	ASSERT(pktp->pkt_resid != 0);
17374 
17375 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
17376 
17377 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17378 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
17379 	case SCMD_READ:
17380 		cmdp = "read";
17381 		break;
17382 	case SCMD_WRITE:
17383 		cmdp = "write";
17384 		break;
17385 	default:
17386 		SD_UPDATE_B_RESID(bp, pktp);
17387 		sd_return_command(un, bp);
17388 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17389 		return;
17390 	}
17391 
17392 	/*
17393 	 * See if we can retry the read/write, preferrably immediately.
17394 	 * If retries are exhaused, then sd_retry_command() will update
17395 	 * the b_resid count.
17396 	 */
17397 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
17398 	    cmdp, EIO, (clock_t)0, NULL);
17399 
17400 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17401 }
17402 
17403 
17404 
17405 
17406 
17407 /*
17408  *    Function: sd_handle_request_sense
17409  *
17410  * Description: Processing for non-auto Request Sense command.
17411  *
17412  *   Arguments: un - ptr to associated softstate
17413  *		sense_bp - ptr to buf(9S) for the RQS command
17414  *		sense_xp - ptr to the sd_xbuf for the RQS command
17415  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
17416  *
17417  *     Context: May be called under interrupt context
17418  */
17419 
17420 static void
17421 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
17422     struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
17423 {
17424 	struct buf	*cmd_bp;	/* buf for the original command */
17425 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
17426 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
17427 	size_t		actual_len;	/* actual sense data length */
17428 
17429 	ASSERT(un != NULL);
17430 	ASSERT(mutex_owned(SD_MUTEX(un)));
17431 	ASSERT(sense_bp != NULL);
17432 	ASSERT(sense_xp != NULL);
17433 	ASSERT(sense_pktp != NULL);
17434 
17435 	/*
17436 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
17437 	 * RQS command and not the original command.
17438 	 */
17439 	ASSERT(sense_pktp == un->un_rqs_pktp);
17440 	ASSERT(sense_bp   == un->un_rqs_bp);
17441 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
17442 	    (FLAG_SENSING | FLAG_HEAD));
17443 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
17444 	    FLAG_SENSING) == FLAG_SENSING);
17445 
17446 	/* These are the bp, xp, and pktp for the original command */
17447 	cmd_bp = sense_xp->xb_sense_bp;
17448 	cmd_xp = SD_GET_XBUF(cmd_bp);
17449 	cmd_pktp = SD_GET_PKTP(cmd_bp);
17450 
17451 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
17452 		/*
17453 		 * The REQUEST SENSE command failed.  Release the REQUEST
17454 		 * SENSE command for re-use, get back the bp for the original
17455 		 * command, and attempt to re-try the original command if
17456 		 * FLAG_DIAGNOSE is not set in the original packet.
17457 		 */
17458 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17459 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17460 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
17461 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
17462 			    NULL, NULL, EIO, (clock_t)0, NULL);
17463 			return;
17464 		}
17465 	}
17466 
17467 	/*
17468 	 * Save the relevant sense info into the xp for the original cmd.
17469 	 *
17470 	 * Note: if the request sense failed the state info will be zero
17471 	 * as set in sd_mark_rqs_busy()
17472 	 */
17473 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
17474 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
17475 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
17476 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
17477 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
17478 	    SENSE_LENGTH)) {
17479 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17480 		    MAX_SENSE_LENGTH);
17481 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
17482 	} else {
17483 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17484 		    SENSE_LENGTH);
17485 		if (actual_len < SENSE_LENGTH) {
17486 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
17487 		} else {
17488 			cmd_xp->xb_sense_resid = 0;
17489 		}
17490 	}
17491 
17492 	/*
17493 	 *  Free up the RQS command....
17494 	 *  NOTE:
17495 	 *	Must do this BEFORE calling sd_validate_sense_data!
17496 	 *	sd_validate_sense_data may return the original command in
17497 	 *	which case the pkt will be freed and the flags can no
17498 	 *	longer be touched.
17499 	 *	SD_MUTEX is held through this process until the command
17500 	 *	is dispatched based upon the sense data, so there are
17501 	 *	no race conditions.
17502 	 */
17503 	(void) sd_mark_rqs_idle(un, sense_xp);
17504 
17505 	/*
17506 	 * For a retryable command see if we have valid sense data, if so then
17507 	 * turn it over to sd_decode_sense() to figure out the right course of
17508 	 * action. Just fail a non-retryable command.
17509 	 */
17510 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17511 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
17512 		    SD_SENSE_DATA_IS_VALID) {
17513 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
17514 		}
17515 	} else {
17516 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
17517 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17518 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
17519 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
17520 		sd_return_failed_command(un, cmd_bp, EIO);
17521 	}
17522 }
17523 
17524 
17525 
17526 
17527 /*
17528  *    Function: sd_handle_auto_request_sense
17529  *
17530  * Description: Processing for auto-request sense information.
17531  *
17532  *   Arguments: un - ptr to associated softstate
17533  *		bp - ptr to buf(9S) for the command
17534  *		xp - ptr to the sd_xbuf for the command
17535  *		pktp - ptr to the scsi_pkt(9S) for the command
17536  *
17537  *     Context: May be called under interrupt context
17538  */
17539 
17540 static void
17541 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
17542     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17543 {
17544 	struct scsi_arq_status *asp;
17545 	size_t actual_len;
17546 
17547 	ASSERT(un != NULL);
17548 	ASSERT(mutex_owned(SD_MUTEX(un)));
17549 	ASSERT(bp != NULL);
17550 	ASSERT(xp != NULL);
17551 	ASSERT(pktp != NULL);
17552 	ASSERT(pktp != un->un_rqs_pktp);
17553 	ASSERT(bp   != un->un_rqs_bp);
17554 
17555 	/*
17556 	 * For auto-request sense, we get a scsi_arq_status back from
17557 	 * the HBA, with the sense data in the sts_sensedata member.
17558 	 * The pkt_scbp of the packet points to this scsi_arq_status.
17559 	 */
17560 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
17561 
17562 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
17563 		/*
17564 		 * The auto REQUEST SENSE failed; see if we can re-try
17565 		 * the original command.
17566 		 */
17567 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17568 		    "auto request sense failed (reason=%s)\n",
17569 		    scsi_rname(asp->sts_rqpkt_reason));
17570 
17571 		sd_reset_target(un, pktp);
17572 
17573 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17574 		    NULL, NULL, EIO, (clock_t)0, NULL);
17575 		return;
17576 	}
17577 
17578 	/* Save the relevant sense info into the xp for the original cmd. */
17579 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
17580 	xp->xb_sense_state  = asp->sts_rqpkt_state;
17581 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
17582 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
17583 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17584 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
17585 		    MAX_SENSE_LENGTH);
17586 	} else {
17587 		if (xp->xb_sense_resid > SENSE_LENGTH) {
17588 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17589 		} else {
17590 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
17591 		}
17592 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17593 			if ((((struct uscsi_cmd *)
17594 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
17595 				xp->xb_sense_resid = (((struct uscsi_cmd *)
17596 				    (xp->xb_pktinfo))->uscsi_rqlen) -
17597 				    actual_len;
17598 			} else {
17599 				xp->xb_sense_resid = 0;
17600 			}
17601 		}
17602 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
17603 	}
17604 
17605 	/*
17606 	 * See if we have valid sense data, if so then turn it over to
17607 	 * sd_decode_sense() to figure out the right course of action.
17608 	 */
17609 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
17610 	    SD_SENSE_DATA_IS_VALID) {
17611 		sd_decode_sense(un, bp, xp, pktp);
17612 	}
17613 }
17614 
17615 
17616 /*
17617  *    Function: sd_print_sense_failed_msg
17618  *
17619  * Description: Print log message when RQS has failed.
17620  *
17621  *   Arguments: un - ptr to associated softstate
17622  *		bp - ptr to buf(9S) for the command
17623  *		arg - generic message string ptr
17624  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17625  *			or SD_NO_RETRY_ISSUED
17626  *
17627  *     Context: May be called from interrupt context
17628  */
17629 
17630 static void
17631 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
17632     int code)
17633 {
17634 	char	*msgp = arg;
17635 
17636 	ASSERT(un != NULL);
17637 	ASSERT(mutex_owned(SD_MUTEX(un)));
17638 	ASSERT(bp != NULL);
17639 
17640 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
17641 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
17642 	}
17643 }
17644 
17645 
17646 /*
17647  *    Function: sd_validate_sense_data
17648  *
17649  * Description: Check the given sense data for validity.
17650  *		If the sense data is not valid, the command will
17651  *		be either failed or retried!
17652  *
17653  * Return Code: SD_SENSE_DATA_IS_INVALID
17654  *		SD_SENSE_DATA_IS_VALID
17655  *
17656  *     Context: May be called from interrupt context
17657  */
17658 
17659 static int
17660 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17661     size_t actual_len)
17662 {
17663 	struct scsi_extended_sense *esp;
17664 	struct	scsi_pkt *pktp;
17665 	char	*msgp = NULL;
17666 	sd_ssc_t *sscp;
17667 
17668 	ASSERT(un != NULL);
17669 	ASSERT(mutex_owned(SD_MUTEX(un)));
17670 	ASSERT(bp != NULL);
17671 	ASSERT(bp != un->un_rqs_bp);
17672 	ASSERT(xp != NULL);
17673 	ASSERT(un->un_fm_private != NULL);
17674 
17675 	pktp = SD_GET_PKTP(bp);
17676 	ASSERT(pktp != NULL);
17677 
17678 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
17679 	ASSERT(sscp != NULL);
17680 
17681 	/*
17682 	 * Check the status of the RQS command (auto or manual).
17683 	 */
17684 	switch (xp->xb_sense_status & STATUS_MASK) {
17685 	case STATUS_GOOD:
17686 		break;
17687 
17688 	case STATUS_RESERVATION_CONFLICT:
17689 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17690 		return (SD_SENSE_DATA_IS_INVALID);
17691 
17692 	case STATUS_BUSY:
17693 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17694 		    "Busy Status on REQUEST SENSE\n");
17695 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
17696 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17697 		return (SD_SENSE_DATA_IS_INVALID);
17698 
17699 	case STATUS_QFULL:
17700 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17701 		    "QFULL Status on REQUEST SENSE\n");
17702 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
17703 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17704 		return (SD_SENSE_DATA_IS_INVALID);
17705 
17706 	case STATUS_CHECK:
17707 	case STATUS_TERMINATED:
17708 		msgp = "Check Condition on REQUEST SENSE\n";
17709 		goto sense_failed;
17710 
17711 	default:
17712 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
17713 		goto sense_failed;
17714 	}
17715 
17716 	/*
17717 	 * See if we got the minimum required amount of sense data.
17718 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
17719 	 * or less.
17720 	 */
17721 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
17722 	    (actual_len == 0)) {
17723 		msgp = "Request Sense couldn't get sense data\n";
17724 		goto sense_failed;
17725 	}
17726 
17727 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
17728 		msgp = "Not enough sense information\n";
17729 		/* Mark the ssc_flags for detecting invalid sense data */
17730 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17731 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17732 			    "sense-data");
17733 		}
17734 		goto sense_failed;
17735 	}
17736 
17737 	/*
17738 	 * We require the extended sense data
17739 	 */
17740 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
17741 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
17742 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17743 			static char tmp[8];
17744 			static char buf[148];
17745 			char *p = (char *)(xp->xb_sense_data);
17746 			int i;
17747 
17748 			mutex_enter(&sd_sense_mutex);
17749 			(void) strcpy(buf, "undecodable sense information:");
17750 			for (i = 0; i < actual_len; i++) {
17751 				(void) sprintf(tmp, " 0x%x", *(p++) & 0xff);
17752 				(void) strcpy(&buf[strlen(buf)], tmp);
17753 			}
17754 			i = strlen(buf);
17755 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
17756 
17757 			if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
17758 				scsi_log(SD_DEVINFO(un), sd_label,
17759 				    CE_WARN, buf);
17760 			}
17761 			mutex_exit(&sd_sense_mutex);
17762 		}
17763 
17764 		/* Mark the ssc_flags for detecting invalid sense data */
17765 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17766 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17767 			    "sense-data");
17768 		}
17769 
17770 		/* Note: Legacy behavior, fail the command with no retry */
17771 		sd_return_failed_command(un, bp, EIO);
17772 		return (SD_SENSE_DATA_IS_INVALID);
17773 	}
17774 
17775 	/*
17776 	 * Check that es_code is valid (es_class concatenated with es_code
17777 	 * make up the "response code" field.  es_class will always be 7, so
17778 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
17779 	 * format.
17780 	 */
17781 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
17782 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
17783 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
17784 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
17785 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
17786 		/* Mark the ssc_flags for detecting invalid sense data */
17787 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17788 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17789 			    "sense-data");
17790 		}
17791 		goto sense_failed;
17792 	}
17793 
17794 	return (SD_SENSE_DATA_IS_VALID);
17795 
17796 sense_failed:
17797 	/*
17798 	 * If the request sense failed (for whatever reason), attempt
17799 	 * to retry the original command.
17800 	 */
17801 #if defined(__x86)
17802 	/*
17803 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
17804 	 * sddef.h for Sparc platform, and x86 uses 1 binary
17805 	 * for both SCSI/FC.
17806 	 * The SD_RETRY_DELAY value need to be adjusted here
17807 	 * when SD_RETRY_DELAY change in sddef.h
17808 	 */
17809 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17810 	    sd_print_sense_failed_msg, msgp, EIO,
17811 	    un->un_f_is_fibre ? drv_usectohz(100000) : (clock_t)0, NULL);
17812 #else
17813 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17814 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
17815 #endif
17816 
17817 	return (SD_SENSE_DATA_IS_INVALID);
17818 }
17819 
17820 /*
17821  *    Function: sd_decode_sense
17822  *
17823  * Description: Take recovery action(s) when SCSI Sense Data is received.
17824  *
17825  *     Context: Interrupt context.
17826  */
17827 
17828 static void
17829 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17830     struct scsi_pkt *pktp)
17831 {
17832 	uint8_t sense_key;
17833 
17834 	ASSERT(un != NULL);
17835 	ASSERT(mutex_owned(SD_MUTEX(un)));
17836 	ASSERT(bp != NULL);
17837 	ASSERT(bp != un->un_rqs_bp);
17838 	ASSERT(xp != NULL);
17839 	ASSERT(pktp != NULL);
17840 
17841 	sense_key = scsi_sense_key(xp->xb_sense_data);
17842 
17843 	switch (sense_key) {
17844 	case KEY_NO_SENSE:
17845 		sd_sense_key_no_sense(un, bp, xp, pktp);
17846 		break;
17847 	case KEY_RECOVERABLE_ERROR:
17848 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
17849 		    bp, xp, pktp);
17850 		break;
17851 	case KEY_NOT_READY:
17852 		sd_sense_key_not_ready(un, xp->xb_sense_data,
17853 		    bp, xp, pktp);
17854 		break;
17855 	case KEY_MEDIUM_ERROR:
17856 	case KEY_HARDWARE_ERROR:
17857 		sd_sense_key_medium_or_hardware_error(un,
17858 		    xp->xb_sense_data, bp, xp, pktp);
17859 		break;
17860 	case KEY_ILLEGAL_REQUEST:
17861 		sd_sense_key_illegal_request(un, bp, xp, pktp);
17862 		break;
17863 	case KEY_UNIT_ATTENTION:
17864 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
17865 		    bp, xp, pktp);
17866 		break;
17867 	case KEY_WRITE_PROTECT:
17868 	case KEY_VOLUME_OVERFLOW:
17869 	case KEY_MISCOMPARE:
17870 		sd_sense_key_fail_command(un, bp, xp, pktp);
17871 		break;
17872 	case KEY_BLANK_CHECK:
17873 		sd_sense_key_blank_check(un, bp, xp, pktp);
17874 		break;
17875 	case KEY_ABORTED_COMMAND:
17876 		sd_sense_key_aborted_command(un, bp, xp, pktp);
17877 		break;
17878 	case KEY_VENDOR_UNIQUE:
17879 	case KEY_COPY_ABORTED:
17880 	case KEY_EQUAL:
17881 	case KEY_RESERVED:
17882 	default:
17883 		sd_sense_key_default(un, xp->xb_sense_data,
17884 		    bp, xp, pktp);
17885 		break;
17886 	}
17887 }
17888 
17889 
17890 /*
17891  *    Function: sd_dump_memory
17892  *
17893  * Description: Debug logging routine to print the contents of a user provided
17894  *		buffer. The output of the buffer is broken up into 256 byte
17895  *		segments due to a size constraint of the scsi_log.
17896  *		implementation.
17897  *
17898  *   Arguments: un - ptr to softstate
17899  *		comp - component mask
17900  *		title - "title" string to preceed data when printed
17901  *		data - ptr to data block to be printed
17902  *		len - size of data block to be printed
17903  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
17904  *
17905  *     Context: May be called from interrupt context
17906  */
17907 
17908 #define	SD_DUMP_MEMORY_BUF_SIZE	256
17909 
17910 static char *sd_dump_format_string[] = {
17911 		" 0x%02x",
17912 		" %c"
17913 };
17914 
17915 static void
17916 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
17917     int len, int fmt)
17918 {
17919 	int	i, j;
17920 	int	avail_count;
17921 	int	start_offset;
17922 	int	end_offset;
17923 	size_t	entry_len;
17924 	char	*bufp;
17925 	char	*local_buf;
17926 	char	*format_string;
17927 
17928 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
17929 
17930 	/*
17931 	 * In the debug version of the driver, this function is called from a
17932 	 * number of places which are NOPs in the release driver.
17933 	 * The debug driver therefore has additional methods of filtering
17934 	 * debug output.
17935 	 */
17936 #ifdef SDDEBUG
17937 	/*
17938 	 * In the debug version of the driver we can reduce the amount of debug
17939 	 * messages by setting sd_error_level to something other than
17940 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17941 	 * sd_component_mask.
17942 	 */
17943 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17944 	    (sd_error_level != SCSI_ERR_ALL)) {
17945 		return;
17946 	}
17947 	if (((sd_component_mask & comp) == 0) ||
17948 	    (sd_error_level != SCSI_ERR_ALL)) {
17949 		return;
17950 	}
17951 #else
17952 	if (sd_error_level != SCSI_ERR_ALL) {
17953 		return;
17954 	}
17955 #endif
17956 
17957 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17958 	bufp = local_buf;
17959 	/*
17960 	 * Available length is the length of local_buf[], minus the
17961 	 * length of the title string, minus one for the ":", minus
17962 	 * one for the newline, minus one for the NULL terminator.
17963 	 * This gives the #bytes available for holding the printed
17964 	 * values from the given data buffer.
17965 	 */
17966 	if (fmt == SD_LOG_HEX) {
17967 		format_string = sd_dump_format_string[0];
17968 	} else /* SD_LOG_CHAR */ {
17969 		format_string = sd_dump_format_string[1];
17970 	}
17971 	/*
17972 	 * Available count is the number of elements from the given
17973 	 * data buffer that we can fit into the available length.
17974 	 * This is based upon the size of the format string used.
17975 	 * Make one entry and find it's size.
17976 	 */
17977 	(void) sprintf(bufp, format_string, data[0]);
17978 	entry_len = strlen(bufp);
17979 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17980 
17981 	j = 0;
17982 	while (j < len) {
17983 		bufp = local_buf;
17984 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17985 		start_offset = j;
17986 
17987 		end_offset = start_offset + avail_count;
17988 
17989 		(void) sprintf(bufp, "%s:", title);
17990 		bufp += strlen(bufp);
17991 		for (i = start_offset; ((i < end_offset) && (j < len));
17992 		    i++, j++) {
17993 			(void) sprintf(bufp, format_string, data[i]);
17994 			bufp += entry_len;
17995 		}
17996 		(void) sprintf(bufp, "\n");
17997 
17998 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17999 	}
18000 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
18001 }
18002 
18003 /*
18004  *    Function: sd_print_sense_msg
18005  *
18006  * Description: Log a message based upon the given sense data.
18007  *
18008  *   Arguments: un - ptr to associated softstate
18009  *		bp - ptr to buf(9S) for the command
18010  *		arg - ptr to associate sd_sense_info struct
18011  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18012  *			or SD_NO_RETRY_ISSUED
18013  *
18014  *     Context: May be called from interrupt context
18015  */
18016 
18017 static void
18018 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
18019 {
18020 	struct sd_xbuf	*xp;
18021 	struct scsi_pkt	*pktp;
18022 	uint8_t *sensep;
18023 	daddr_t request_blkno;
18024 	diskaddr_t err_blkno;
18025 	int severity;
18026 	int pfa_flag;
18027 	extern struct scsi_key_strings scsi_cmds[];
18028 
18029 	ASSERT(un != NULL);
18030 	ASSERT(mutex_owned(SD_MUTEX(un)));
18031 	ASSERT(bp != NULL);
18032 	xp = SD_GET_XBUF(bp);
18033 	ASSERT(xp != NULL);
18034 	pktp = SD_GET_PKTP(bp);
18035 	ASSERT(pktp != NULL);
18036 	ASSERT(arg != NULL);
18037 
18038 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
18039 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
18040 
18041 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
18042 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
18043 		severity = SCSI_ERR_RETRYABLE;
18044 	}
18045 
18046 	/* Use absolute block number for the request block number */
18047 	request_blkno = xp->xb_blkno;
18048 
18049 	/*
18050 	 * Now try to get the error block number from the sense data
18051 	 */
18052 	sensep = xp->xb_sense_data;
18053 
18054 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
18055 	    (uint64_t *)&err_blkno)) {
18056 		/*
18057 		 * We retrieved the error block number from the information
18058 		 * portion of the sense data.
18059 		 *
18060 		 * For USCSI commands we are better off using the error
18061 		 * block no. as the requested block no. (This is the best
18062 		 * we can estimate.)
18063 		 */
18064 		if ((SD_IS_BUFIO(xp) == FALSE) &&
18065 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
18066 			request_blkno = err_blkno;
18067 		}
18068 	} else {
18069 		/*
18070 		 * Without the es_valid bit set (for fixed format) or an
18071 		 * information descriptor (for descriptor format) we cannot
18072 		 * be certain of the error blkno, so just use the
18073 		 * request_blkno.
18074 		 */
18075 		err_blkno = (diskaddr_t)request_blkno;
18076 	}
18077 
18078 	/*
18079 	 * The following will log the buffer contents for the release driver
18080 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
18081 	 * level is set to verbose.
18082 	 */
18083 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
18084 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
18085 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
18086 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
18087 
18088 	if (pfa_flag == FALSE) {
18089 		/* This is normally only set for USCSI */
18090 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
18091 			return;
18092 		}
18093 
18094 		if ((SD_IS_BUFIO(xp) == TRUE) &&
18095 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
18096 		    (severity < sd_error_level))) {
18097 			return;
18098 		}
18099 	}
18100 	/*
18101 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
18102 	 */
18103 	if ((SD_IS_LSI(un)) &&
18104 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
18105 	    (scsi_sense_asc(sensep) == 0x94) &&
18106 	    (scsi_sense_ascq(sensep) == 0x01)) {
18107 		un->un_sonoma_failure_count++;
18108 		if (un->un_sonoma_failure_count > 1) {
18109 			return;
18110 		}
18111 	}
18112 
18113 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP ||
18114 	    ((scsi_sense_key(sensep) == KEY_RECOVERABLE_ERROR) &&
18115 	    (pktp->pkt_resid == 0))) {
18116 		scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
18117 		    request_blkno, err_blkno, scsi_cmds,
18118 		    (struct scsi_extended_sense *)sensep,
18119 		    un->un_additional_codes, NULL);
18120 	}
18121 }
18122 
18123 /*
18124  *    Function: sd_sense_key_no_sense
18125  *
18126  * Description: Recovery action when sense data was not received.
18127  *
18128  *     Context: May be called from interrupt context
18129  */
18130 
18131 static void
18132 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18133     struct scsi_pkt *pktp)
18134 {
18135 	struct sd_sense_info	si;
18136 
18137 	ASSERT(un != NULL);
18138 	ASSERT(mutex_owned(SD_MUTEX(un)));
18139 	ASSERT(bp != NULL);
18140 	ASSERT(xp != NULL);
18141 	ASSERT(pktp != NULL);
18142 
18143 	si.ssi_severity = SCSI_ERR_FATAL;
18144 	si.ssi_pfa_flag = FALSE;
18145 
18146 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
18147 
18148 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18149 	    &si, EIO, (clock_t)0, NULL);
18150 }
18151 
18152 
18153 /*
18154  *    Function: sd_sense_key_recoverable_error
18155  *
18156  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
18157  *
18158  *     Context: May be called from interrupt context
18159  */
18160 
18161 static void
18162 sd_sense_key_recoverable_error(struct sd_lun *un, uint8_t *sense_datap,
18163     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18164 {
18165 	struct sd_sense_info	si;
18166 	uint8_t asc = scsi_sense_asc(sense_datap);
18167 	uint8_t ascq = scsi_sense_ascq(sense_datap);
18168 
18169 	ASSERT(un != NULL);
18170 	ASSERT(mutex_owned(SD_MUTEX(un)));
18171 	ASSERT(bp != NULL);
18172 	ASSERT(xp != NULL);
18173 	ASSERT(pktp != NULL);
18174 
18175 	/*
18176 	 * 0x00, 0x1D: ATA PASSTHROUGH INFORMATION AVAILABLE
18177 	 */
18178 	if (asc == 0x00 && ascq == 0x1D) {
18179 		sd_return_command(un, bp);
18180 		return;
18181 	}
18182 
18183 	/*
18184 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
18185 	 */
18186 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
18187 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18188 		si.ssi_severity = SCSI_ERR_INFO;
18189 		si.ssi_pfa_flag = TRUE;
18190 	} else {
18191 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
18192 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
18193 		si.ssi_severity = SCSI_ERR_RECOVERED;
18194 		si.ssi_pfa_flag = FALSE;
18195 	}
18196 
18197 	if (pktp->pkt_resid == 0) {
18198 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18199 		sd_return_command(un, bp);
18200 		return;
18201 	}
18202 
18203 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18204 	    &si, EIO, (clock_t)0, NULL);
18205 }
18206 
18207 
18208 
18209 
18210 /*
18211  *    Function: sd_sense_key_not_ready
18212  *
18213  * Description: Recovery actions for a SCSI "Not Ready" sense key.
18214  *
18215  *     Context: May be called from interrupt context
18216  */
18217 
18218 static void
18219 sd_sense_key_not_ready(struct sd_lun *un, uint8_t *sense_datap, struct buf *bp,
18220     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18221 {
18222 	struct sd_sense_info	si;
18223 	uint8_t asc = scsi_sense_asc(sense_datap);
18224 	uint8_t ascq = scsi_sense_ascq(sense_datap);
18225 
18226 	ASSERT(un != NULL);
18227 	ASSERT(mutex_owned(SD_MUTEX(un)));
18228 	ASSERT(bp != NULL);
18229 	ASSERT(xp != NULL);
18230 	ASSERT(pktp != NULL);
18231 
18232 	si.ssi_severity = SCSI_ERR_FATAL;
18233 	si.ssi_pfa_flag = FALSE;
18234 
18235 	/*
18236 	 * Update error stats after first NOT READY error. Disks may have
18237 	 * been powered down and may need to be restarted.  For CDROMs,
18238 	 * report NOT READY errors only if media is present.
18239 	 */
18240 	if ((ISCD(un) && (asc == 0x3A)) ||
18241 	    (xp->xb_nr_retry_count > 0)) {
18242 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18243 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
18244 	}
18245 
18246 	/*
18247 	 * Just fail if the "not ready" retry limit has been reached.
18248 	 */
18249 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
18250 		/* Special check for error message printing for removables. */
18251 		if (un->un_f_has_removable_media && (asc == 0x04) &&
18252 		    (ascq >= 0x04)) {
18253 			si.ssi_severity = SCSI_ERR_ALL;
18254 		}
18255 		goto fail_command;
18256 	}
18257 
18258 	/*
18259 	 * Check the ASC and ASCQ in the sense data as needed, to determine
18260 	 * what to do.
18261 	 */
18262 	switch (asc) {
18263 	case 0x04:	/* LOGICAL UNIT NOT READY */
18264 		/*
18265 		 * disk drives that don't spin up result in a very long delay
18266 		 * in format without warning messages. We will log a message
18267 		 * if the error level is set to verbose.
18268 		 */
18269 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18270 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18271 			    "logical unit not ready, resetting disk\n");
18272 		}
18273 
18274 		/*
18275 		 * There are different requirements for CDROMs and disks for
18276 		 * the number of retries.  If a CD-ROM is giving this, it is
18277 		 * probably reading TOC and is in the process of getting
18278 		 * ready, so we should keep on trying for a long time to make
18279 		 * sure that all types of media are taken in account (for
18280 		 * some media the drive takes a long time to read TOC).  For
18281 		 * disks we do not want to retry this too many times as this
18282 		 * can cause a long hang in format when the drive refuses to
18283 		 * spin up (a very common failure).
18284 		 */
18285 		switch (ascq) {
18286 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
18287 			/*
18288 			 * Disk drives frequently refuse to spin up which
18289 			 * results in a very long hang in format without
18290 			 * warning messages.
18291 			 *
18292 			 * Note: This code preserves the legacy behavior of
18293 			 * comparing xb_nr_retry_count against zero for fibre
18294 			 * channel targets instead of comparing against the
18295 			 * un_reset_retry_count value.  The reason for this
18296 			 * discrepancy has been so utterly lost beneath the
18297 			 * Sands of Time that even Indiana Jones could not
18298 			 * find it.
18299 			 */
18300 			if (un->un_f_is_fibre == TRUE) {
18301 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18302 				    (xp->xb_nr_retry_count > 0)) &&
18303 				    (un->un_startstop_timeid == NULL)) {
18304 					scsi_log(SD_DEVINFO(un), sd_label,
18305 					    CE_WARN, "logical unit not ready, "
18306 					    "resetting disk\n");
18307 					sd_reset_target(un, pktp);
18308 				}
18309 			} else {
18310 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18311 				    (xp->xb_nr_retry_count >
18312 				    un->un_reset_retry_count)) &&
18313 				    (un->un_startstop_timeid == NULL)) {
18314 					scsi_log(SD_DEVINFO(un), sd_label,
18315 					    CE_WARN, "logical unit not ready, "
18316 					    "resetting disk\n");
18317 					sd_reset_target(un, pktp);
18318 				}
18319 			}
18320 			break;
18321 
18322 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
18323 			/*
18324 			 * If the target is in the process of becoming
18325 			 * ready, just proceed with the retry. This can
18326 			 * happen with CD-ROMs that take a long time to
18327 			 * read TOC after a power cycle or reset.
18328 			 */
18329 			goto do_retry;
18330 
18331 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
18332 			break;
18333 
18334 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
18335 			/*
18336 			 * Retries cannot help here so just fail right away.
18337 			 */
18338 			goto fail_command;
18339 
18340 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
18341 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
18342 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
18343 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
18344 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
18345 		default:    /* Possible future codes in SCSI spec? */
18346 			/*
18347 			 * For removable-media devices, do not retry if
18348 			 * ASCQ > 2 as these result mostly from USCSI commands
18349 			 * on MMC devices issued to check status of an
18350 			 * operation initiated in immediate mode.  Also for
18351 			 * ASCQ >= 4 do not print console messages as these
18352 			 * mainly represent a user-initiated operation
18353 			 * instead of a system failure.
18354 			 */
18355 			if (un->un_f_has_removable_media) {
18356 				si.ssi_severity = SCSI_ERR_ALL;
18357 				goto fail_command;
18358 			}
18359 			break;
18360 		}
18361 
18362 		/*
18363 		 * As part of our recovery attempt for the NOT READY
18364 		 * condition, we issue a START STOP UNIT command. However
18365 		 * we want to wait for a short delay before attempting this
18366 		 * as there may still be more commands coming back from the
18367 		 * target with the check condition. To do this we use
18368 		 * timeout(9F) to call sd_start_stop_unit_callback() after
18369 		 * the delay interval expires. (sd_start_stop_unit_callback()
18370 		 * dispatches sd_start_stop_unit_task(), which will issue
18371 		 * the actual START STOP UNIT command. The delay interval
18372 		 * is one-half of the delay that we will use to retry the
18373 		 * command that generated the NOT READY condition.
18374 		 *
18375 		 * Note that we could just dispatch sd_start_stop_unit_task()
18376 		 * from here and allow it to sleep for the delay interval,
18377 		 * but then we would be tying up the taskq thread
18378 		 * uncesessarily for the duration of the delay.
18379 		 *
18380 		 * Do not issue the START STOP UNIT if the current command
18381 		 * is already a START STOP UNIT.
18382 		 */
18383 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
18384 			break;
18385 		}
18386 
18387 		/*
18388 		 * Do not schedule the timeout if one is already pending.
18389 		 */
18390 		if (un->un_startstop_timeid != NULL) {
18391 			SD_INFO(SD_LOG_ERROR, un,
18392 			    "sd_sense_key_not_ready: restart already issued to"
18393 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
18394 			    ddi_get_instance(SD_DEVINFO(un)));
18395 			break;
18396 		}
18397 
18398 		/*
18399 		 * Schedule the START STOP UNIT command, then queue the command
18400 		 * for a retry.
18401 		 *
18402 		 * Note: A timeout is not scheduled for this retry because we
18403 		 * want the retry to be serial with the START_STOP_UNIT. The
18404 		 * retry will be started when the START_STOP_UNIT is completed
18405 		 * in sd_start_stop_unit_task.
18406 		 */
18407 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
18408 		    un, un->un_busy_timeout / 2);
18409 		xp->xb_nr_retry_count++;
18410 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
18411 		return;
18412 
18413 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
18414 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18415 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18416 			    "unit does not respond to selection\n");
18417 		}
18418 		break;
18419 
18420 	case 0x3A:	/* MEDIUM NOT PRESENT */
18421 		if (sd_error_level >= SCSI_ERR_FATAL) {
18422 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18423 			    "Caddy not inserted in drive\n");
18424 		}
18425 
18426 		sr_ejected(un);
18427 		un->un_mediastate = DKIO_EJECTED;
18428 		/* The state has changed, inform the media watch routines */
18429 		cv_broadcast(&un->un_state_cv);
18430 		/* Just fail if no media is present in the drive. */
18431 		goto fail_command;
18432 
18433 	default:
18434 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18435 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
18436 			    "Unit not Ready. Additional sense code 0x%x\n",
18437 			    asc);
18438 		}
18439 		break;
18440 	}
18441 
18442 do_retry:
18443 
18444 	/*
18445 	 * Retry the command, as some targets may report NOT READY for
18446 	 * several seconds after being reset.
18447 	 */
18448 	xp->xb_nr_retry_count++;
18449 	si.ssi_severity = SCSI_ERR_RETRYABLE;
18450 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
18451 	    &si, EIO, un->un_busy_timeout, NULL);
18452 
18453 	return;
18454 
18455 fail_command:
18456 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18457 	sd_return_failed_command(un, bp, EIO);
18458 }
18459 
18460 
18461 
18462 /*
18463  *    Function: sd_sense_key_medium_or_hardware_error
18464  *
18465  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
18466  *		sense key.
18467  *
18468  *     Context: May be called from interrupt context
18469  */
18470 
18471 static void
18472 sd_sense_key_medium_or_hardware_error(struct sd_lun *un, uint8_t *sense_datap,
18473     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18474 {
18475 	struct sd_sense_info	si;
18476 	uint8_t sense_key = scsi_sense_key(sense_datap);
18477 	uint8_t asc = scsi_sense_asc(sense_datap);
18478 
18479 	ASSERT(un != NULL);
18480 	ASSERT(mutex_owned(SD_MUTEX(un)));
18481 	ASSERT(bp != NULL);
18482 	ASSERT(xp != NULL);
18483 	ASSERT(pktp != NULL);
18484 
18485 	si.ssi_severity = SCSI_ERR_FATAL;
18486 	si.ssi_pfa_flag = FALSE;
18487 
18488 	if (sense_key == KEY_MEDIUM_ERROR) {
18489 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
18490 	}
18491 
18492 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18493 
18494 	if ((un->un_reset_retry_count != 0) &&
18495 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
18496 		mutex_exit(SD_MUTEX(un));
18497 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
18498 		if (un->un_f_allow_bus_device_reset == TRUE) {
18499 
18500 			boolean_t try_resetting_target = B_TRUE;
18501 
18502 			/*
18503 			 * We need to be able to handle specific ASC when we are
18504 			 * handling a KEY_HARDWARE_ERROR. In particular
18505 			 * taking the default action of resetting the target may
18506 			 * not be the appropriate way to attempt recovery.
18507 			 * Resetting a target because of a single LUN failure
18508 			 * victimizes all LUNs on that target.
18509 			 *
18510 			 * This is true for the LSI arrays, if an LSI
18511 			 * array controller returns an ASC of 0x84 (LUN Dead) we
18512 			 * should trust it.
18513 			 */
18514 
18515 			if (sense_key == KEY_HARDWARE_ERROR) {
18516 				switch (asc) {
18517 				case 0x84:
18518 					if (SD_IS_LSI(un)) {
18519 						try_resetting_target = B_FALSE;
18520 					}
18521 					break;
18522 				default:
18523 					break;
18524 				}
18525 			}
18526 
18527 			if (try_resetting_target == B_TRUE) {
18528 				int reset_retval = 0;
18529 				if (un->un_f_lun_reset_enabled == TRUE) {
18530 					SD_TRACE(SD_LOG_IO_CORE, un,
18531 					    "sd_sense_key_medium_or_hardware_"
18532 					    "error: issuing RESET_LUN\n");
18533 					reset_retval =
18534 					    scsi_reset(SD_ADDRESS(un),
18535 					    RESET_LUN);
18536 				}
18537 				if (reset_retval == 0) {
18538 					SD_TRACE(SD_LOG_IO_CORE, un,
18539 					    "sd_sense_key_medium_or_hardware_"
18540 					    "error: issuing RESET_TARGET\n");
18541 					(void) scsi_reset(SD_ADDRESS(un),
18542 					    RESET_TARGET);
18543 				}
18544 			}
18545 		}
18546 		mutex_enter(SD_MUTEX(un));
18547 	}
18548 
18549 	/*
18550 	 * This really ought to be a fatal error, but we will retry anyway
18551 	 * as some drives report this as a spurious error.
18552 	 */
18553 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18554 	    &si, EIO, (clock_t)0, NULL);
18555 }
18556 
18557 
18558 
18559 /*
18560  *    Function: sd_sense_key_illegal_request
18561  *
18562  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
18563  *
18564  *     Context: May be called from interrupt context
18565  */
18566 
18567 static void
18568 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
18569     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18570 {
18571 	struct sd_sense_info	si;
18572 
18573 	ASSERT(un != NULL);
18574 	ASSERT(mutex_owned(SD_MUTEX(un)));
18575 	ASSERT(bp != NULL);
18576 	ASSERT(xp != NULL);
18577 	ASSERT(pktp != NULL);
18578 
18579 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
18580 
18581 	si.ssi_severity = SCSI_ERR_INFO;
18582 	si.ssi_pfa_flag = FALSE;
18583 
18584 	/* Pointless to retry if the target thinks it's an illegal request */
18585 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18586 	sd_return_failed_command(un, bp, EIO);
18587 }
18588 
18589 
18590 
18591 
18592 /*
18593  *    Function: sd_sense_key_unit_attention
18594  *
18595  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
18596  *
18597  *     Context: May be called from interrupt context
18598  */
18599 
18600 static void
18601 sd_sense_key_unit_attention(struct sd_lun *un, uint8_t *sense_datap,
18602     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18603 {
18604 	/*
18605 	 * For UNIT ATTENTION we allow retries for one minute. Devices
18606 	 * like Sonoma can return UNIT ATTENTION close to a minute
18607 	 * under certain conditions.
18608 	 */
18609 	int	retry_check_flag = SD_RETRIES_UA;
18610 	boolean_t	kstat_updated = B_FALSE;
18611 	struct	sd_sense_info		si;
18612 	uint8_t asc = scsi_sense_asc(sense_datap);
18613 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
18614 
18615 	ASSERT(un != NULL);
18616 	ASSERT(mutex_owned(SD_MUTEX(un)));
18617 	ASSERT(bp != NULL);
18618 	ASSERT(xp != NULL);
18619 	ASSERT(pktp != NULL);
18620 
18621 	si.ssi_severity = SCSI_ERR_INFO;
18622 	si.ssi_pfa_flag = FALSE;
18623 
18624 
18625 	switch (asc) {
18626 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
18627 		if (sd_report_pfa != 0) {
18628 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18629 			si.ssi_pfa_flag = TRUE;
18630 			retry_check_flag = SD_RETRIES_STANDARD;
18631 			goto do_retry;
18632 		}
18633 
18634 		break;
18635 
18636 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
18637 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
18638 			un->un_resvd_status |=
18639 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
18640 		}
18641 #ifdef _LP64
18642 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
18643 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
18644 			    un, KM_NOSLEEP) == TASKQID_INVALID) {
18645 				/*
18646 				 * If we can't dispatch the task we'll just
18647 				 * live without descriptor sense.  We can
18648 				 * try again on the next "unit attention"
18649 				 */
18650 				SD_ERROR(SD_LOG_ERROR, un,
18651 				    "sd_sense_key_unit_attention: "
18652 				    "Could not dispatch "
18653 				    "sd_reenable_dsense_task\n");
18654 			}
18655 		}
18656 #endif /* _LP64 */
18657 		/* FALLTHRU */
18658 
18659 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
18660 		if (!un->un_f_has_removable_media) {
18661 			break;
18662 		}
18663 
18664 		/*
18665 		 * When we get a unit attention from a removable-media device,
18666 		 * it may be in a state that will take a long time to recover
18667 		 * (e.g., from a reset).  Since we are executing in interrupt
18668 		 * context here, we cannot wait around for the device to come
18669 		 * back. So hand this command off to sd_media_change_task()
18670 		 * for deferred processing under taskq thread context. (Note
18671 		 * that the command still may be failed if a problem is
18672 		 * encountered at a later time.)
18673 		 */
18674 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
18675 		    KM_NOSLEEP) == TASKQID_INVALID) {
18676 			/*
18677 			 * Cannot dispatch the request so fail the command.
18678 			 */
18679 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
18680 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18681 			si.ssi_severity = SCSI_ERR_FATAL;
18682 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18683 			sd_return_failed_command(un, bp, EIO);
18684 		}
18685 
18686 		/*
18687 		 * If failed to dispatch sd_media_change_task(), we already
18688 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
18689 		 * we should update kstat later if it encounters an error. So,
18690 		 * we update kstat_updated flag here.
18691 		 */
18692 		kstat_updated = B_TRUE;
18693 
18694 		/*
18695 		 * Either the command has been successfully dispatched to a
18696 		 * task Q for retrying, or the dispatch failed. In either case
18697 		 * do NOT retry again by calling sd_retry_command. This sets up
18698 		 * two retries of the same command and when one completes and
18699 		 * frees the resources the other will access freed memory,
18700 		 * a bad thing.
18701 		 */
18702 		return;
18703 
18704 	default:
18705 		break;
18706 	}
18707 
18708 	/*
18709 	 * ASC  ASCQ
18710 	 *  2A   09	Capacity data has changed
18711 	 *  2A   01	Mode parameters changed
18712 	 *  3F   0E	Reported luns data has changed
18713 	 * Arrays that support logical unit expansion should report
18714 	 * capacity changes(2Ah/09). Mode parameters changed and
18715 	 * reported luns data has changed are the approximation.
18716 	 */
18717 	if (((asc == 0x2a) && (ascq == 0x09)) ||
18718 	    ((asc == 0x2a) && (ascq == 0x01)) ||
18719 	    ((asc == 0x3f) && (ascq == 0x0e))) {
18720 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
18721 		    KM_NOSLEEP) == TASKQID_INVALID) {
18722 			SD_ERROR(SD_LOG_ERROR, un,
18723 			    "sd_sense_key_unit_attention: "
18724 			    "Could not dispatch sd_target_change_task\n");
18725 		}
18726 	}
18727 
18728 	/*
18729 	 * Update kstat if we haven't done that.
18730 	 */
18731 	if (!kstat_updated) {
18732 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18733 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18734 	}
18735 
18736 do_retry:
18737 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
18738 	    EIO, SD_UA_RETRY_DELAY, NULL);
18739 }
18740 
18741 
18742 
18743 /*
18744  *    Function: sd_sense_key_fail_command
18745  *
18746  * Description: Use to fail a command when we don't like the sense key that
18747  *		was returned.
18748  *
18749  *     Context: May be called from interrupt context
18750  */
18751 
18752 static void
18753 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18754     struct scsi_pkt *pktp)
18755 {
18756 	struct sd_sense_info	si;
18757 
18758 	ASSERT(un != NULL);
18759 	ASSERT(mutex_owned(SD_MUTEX(un)));
18760 	ASSERT(bp != NULL);
18761 	ASSERT(xp != NULL);
18762 	ASSERT(pktp != NULL);
18763 
18764 	si.ssi_severity = SCSI_ERR_FATAL;
18765 	si.ssi_pfa_flag = FALSE;
18766 
18767 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18768 	sd_return_failed_command(un, bp, EIO);
18769 }
18770 
18771 
18772 
18773 /*
18774  *    Function: sd_sense_key_blank_check
18775  *
18776  * Description: Recovery actions for a SCSI "Blank Check" sense key.
18777  *		Has no monetary connotation.
18778  *
18779  *     Context: May be called from interrupt context
18780  */
18781 
18782 static void
18783 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18784     struct scsi_pkt *pktp)
18785 {
18786 	struct sd_sense_info	si;
18787 
18788 	ASSERT(un != NULL);
18789 	ASSERT(mutex_owned(SD_MUTEX(un)));
18790 	ASSERT(bp != NULL);
18791 	ASSERT(xp != NULL);
18792 	ASSERT(pktp != NULL);
18793 
18794 	/*
18795 	 * Blank check is not fatal for removable devices, therefore
18796 	 * it does not require a console message.
18797 	 */
18798 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
18799 	    SCSI_ERR_FATAL;
18800 	si.ssi_pfa_flag = FALSE;
18801 
18802 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18803 	sd_return_failed_command(un, bp, EIO);
18804 }
18805 
18806 
18807 
18808 
18809 /*
18810  *    Function: sd_sense_key_aborted_command
18811  *
18812  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
18813  *
18814  *     Context: May be called from interrupt context
18815  */
18816 
18817 static void
18818 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
18819     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18820 {
18821 	struct sd_sense_info	si;
18822 
18823 	ASSERT(un != NULL);
18824 	ASSERT(mutex_owned(SD_MUTEX(un)));
18825 	ASSERT(bp != NULL);
18826 	ASSERT(xp != NULL);
18827 	ASSERT(pktp != NULL);
18828 
18829 	si.ssi_severity = SCSI_ERR_FATAL;
18830 	si.ssi_pfa_flag = FALSE;
18831 
18832 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18833 
18834 	/*
18835 	 * This really ought to be a fatal error, but we will retry anyway
18836 	 * as some drives report this as a spurious error.
18837 	 */
18838 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18839 	    &si, EIO, drv_usectohz(100000), NULL);
18840 }
18841 
18842 
18843 
18844 /*
18845  *    Function: sd_sense_key_default
18846  *
18847  * Description: Default recovery action for several SCSI sense keys (basically
18848  *		attempts a retry).
18849  *
18850  *     Context: May be called from interrupt context
18851  */
18852 
18853 static void
18854 sd_sense_key_default(struct sd_lun *un, uint8_t *sense_datap, struct buf *bp,
18855     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18856 {
18857 	struct sd_sense_info	si;
18858 	uint8_t sense_key = scsi_sense_key(sense_datap);
18859 
18860 	ASSERT(un != NULL);
18861 	ASSERT(mutex_owned(SD_MUTEX(un)));
18862 	ASSERT(bp != NULL);
18863 	ASSERT(xp != NULL);
18864 	ASSERT(pktp != NULL);
18865 
18866 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18867 
18868 	/*
18869 	 * Undecoded sense key.	Attempt retries and hope that will fix
18870 	 * the problem.  Otherwise, we're dead.
18871 	 */
18872 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18873 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18874 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18875 	}
18876 
18877 	si.ssi_severity = SCSI_ERR_FATAL;
18878 	si.ssi_pfa_flag = FALSE;
18879 
18880 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18881 	    &si, EIO, (clock_t)0, NULL);
18882 }
18883 
18884 
18885 
18886 /*
18887  *    Function: sd_print_retry_msg
18888  *
18889  * Description: Print a message indicating the retry action being taken.
18890  *
18891  *   Arguments: un - ptr to associated softstate
18892  *		bp - ptr to buf(9S) for the command
18893  *		arg - not used.
18894  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18895  *			or SD_NO_RETRY_ISSUED
18896  *
18897  *     Context: May be called from interrupt context
18898  */
18899 /* ARGSUSED */
18900 static void
18901 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18902 {
18903 	struct sd_xbuf	*xp;
18904 	struct scsi_pkt *pktp;
18905 	char *reasonp;
18906 	char *msgp;
18907 
18908 	ASSERT(un != NULL);
18909 	ASSERT(mutex_owned(SD_MUTEX(un)));
18910 	ASSERT(bp != NULL);
18911 	pktp = SD_GET_PKTP(bp);
18912 	ASSERT(pktp != NULL);
18913 	xp = SD_GET_XBUF(bp);
18914 	ASSERT(xp != NULL);
18915 
18916 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18917 	mutex_enter(&un->un_pm_mutex);
18918 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18919 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18920 	    (pktp->pkt_flags & FLAG_SILENT)) {
18921 		mutex_exit(&un->un_pm_mutex);
18922 		goto update_pkt_reason;
18923 	}
18924 	mutex_exit(&un->un_pm_mutex);
18925 
18926 	/*
18927 	 * Suppress messages if they are all the same pkt_reason; with
18928 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18929 	 * If we are in panic, then suppress the retry messages.
18930 	 */
18931 	switch (flag) {
18932 	case SD_NO_RETRY_ISSUED:
18933 		msgp = "giving up";
18934 		break;
18935 	case SD_IMMEDIATE_RETRY_ISSUED:
18936 	case SD_DELAYED_RETRY_ISSUED:
18937 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18938 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18939 		    (sd_error_level != SCSI_ERR_ALL))) {
18940 			return;
18941 		}
18942 		msgp = "retrying command";
18943 		break;
18944 	default:
18945 		goto update_pkt_reason;
18946 	}
18947 
18948 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18949 	    scsi_rname(pktp->pkt_reason));
18950 
18951 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
18952 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18953 		    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18954 	}
18955 
18956 update_pkt_reason:
18957 	/*
18958 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18959 	 * This is to prevent multiple console messages for the same failure
18960 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18961 	 * when the command is retried successfully because there still may be
18962 	 * more commands coming back with the same value of pktp->pkt_reason.
18963 	 */
18964 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18965 		un->un_last_pkt_reason = pktp->pkt_reason;
18966 	}
18967 }
18968 
18969 
18970 /*
18971  *    Function: sd_print_cmd_incomplete_msg
18972  *
18973  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18974  *
18975  *   Arguments: un - ptr to associated softstate
18976  *		bp - ptr to buf(9S) for the command
18977  *		arg - passed to sd_print_retry_msg()
18978  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18979  *			or SD_NO_RETRY_ISSUED
18980  *
18981  *     Context: May be called from interrupt context
18982  */
18983 
18984 static void
18985 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18986     int code)
18987 {
18988 	dev_info_t	*dip;
18989 
18990 	ASSERT(un != NULL);
18991 	ASSERT(mutex_owned(SD_MUTEX(un)));
18992 	ASSERT(bp != NULL);
18993 
18994 	switch (code) {
18995 	case SD_NO_RETRY_ISSUED:
18996 		/* Command was failed. Someone turned off this target? */
18997 		if (un->un_state != SD_STATE_OFFLINE) {
18998 			/*
18999 			 * Suppress message if we are detaching and
19000 			 * device has been disconnected
19001 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
19002 			 * private interface and not part of the DDI
19003 			 */
19004 			dip = un->un_sd->sd_dev;
19005 			if (!(DEVI_IS_DETACHING(dip) &&
19006 			    DEVI_IS_DEVICE_REMOVED(dip))) {
19007 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19008 				"disk not responding to selection\n");
19009 			}
19010 			New_state(un, SD_STATE_OFFLINE);
19011 		}
19012 		break;
19013 
19014 	case SD_DELAYED_RETRY_ISSUED:
19015 	case SD_IMMEDIATE_RETRY_ISSUED:
19016 	default:
19017 		/* Command was successfully queued for retry */
19018 		sd_print_retry_msg(un, bp, arg, code);
19019 		break;
19020 	}
19021 }
19022 
19023 
19024 /*
19025  *    Function: sd_pkt_reason_cmd_incomplete
19026  *
19027  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
19028  *
19029  *     Context: May be called from interrupt context
19030  */
19031 
19032 static void
19033 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
19034     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19035 {
19036 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
19037 
19038 	ASSERT(un != NULL);
19039 	ASSERT(mutex_owned(SD_MUTEX(un)));
19040 	ASSERT(bp != NULL);
19041 	ASSERT(xp != NULL);
19042 	ASSERT(pktp != NULL);
19043 
19044 	/* Do not do a reset if selection did not complete */
19045 	/* Note: Should this not just check the bit? */
19046 	if (pktp->pkt_state != STATE_GOT_BUS) {
19047 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
19048 		sd_reset_target(un, pktp);
19049 	}
19050 
19051 	/*
19052 	 * If the target was not successfully selected, then set
19053 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
19054 	 * with the target, and further retries and/or commands are
19055 	 * likely to take a long time.
19056 	 */
19057 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
19058 		flag |= SD_RETRIES_FAILFAST;
19059 	}
19060 
19061 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19062 
19063 	sd_retry_command(un, bp, flag,
19064 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19065 }
19066 
19067 
19068 
19069 /*
19070  *    Function: sd_pkt_reason_cmd_tran_err
19071  *
19072  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
19073  *
19074  *     Context: May be called from interrupt context
19075  */
19076 
19077 static void
19078 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
19079     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19080 {
19081 	ASSERT(un != NULL);
19082 	ASSERT(mutex_owned(SD_MUTEX(un)));
19083 	ASSERT(bp != NULL);
19084 	ASSERT(xp != NULL);
19085 	ASSERT(pktp != NULL);
19086 
19087 	/*
19088 	 * Do not reset if we got a parity error, or if
19089 	 * selection did not complete.
19090 	 */
19091 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19092 	/* Note: Should this not just check the bit for pkt_state? */
19093 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
19094 	    (pktp->pkt_state != STATE_GOT_BUS)) {
19095 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
19096 		sd_reset_target(un, pktp);
19097 	}
19098 
19099 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19100 
19101 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19102 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19103 }
19104 
19105 
19106 
19107 /*
19108  *    Function: sd_pkt_reason_cmd_reset
19109  *
19110  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
19111  *
19112  *     Context: May be called from interrupt context
19113  */
19114 
19115 static void
19116 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19117     struct scsi_pkt *pktp)
19118 {
19119 	ASSERT(un != NULL);
19120 	ASSERT(mutex_owned(SD_MUTEX(un)));
19121 	ASSERT(bp != NULL);
19122 	ASSERT(xp != NULL);
19123 	ASSERT(pktp != NULL);
19124 
19125 	/* The target may still be running the command, so try to reset. */
19126 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19127 	sd_reset_target(un, pktp);
19128 
19129 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19130 
19131 	/*
19132 	 * If pkt_reason is CMD_RESET chances are that this pkt got
19133 	 * reset because another target on this bus caused it. The target
19134 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
19135 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
19136 	 */
19137 
19138 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
19139 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19140 }
19141 
19142 
19143 
19144 
19145 /*
19146  *    Function: sd_pkt_reason_cmd_aborted
19147  *
19148  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
19149  *
19150  *     Context: May be called from interrupt context
19151  */
19152 
19153 static void
19154 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19155     struct scsi_pkt *pktp)
19156 {
19157 	ASSERT(un != NULL);
19158 	ASSERT(mutex_owned(SD_MUTEX(un)));
19159 	ASSERT(bp != NULL);
19160 	ASSERT(xp != NULL);
19161 	ASSERT(pktp != NULL);
19162 
19163 	/* The target may still be running the command, so try to reset. */
19164 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19165 	sd_reset_target(un, pktp);
19166 
19167 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19168 
19169 	/*
19170 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
19171 	 * aborted because another target on this bus caused it. The target
19172 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
19173 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
19174 	 */
19175 
19176 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
19177 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19178 }
19179 
19180 
19181 
19182 /*
19183  *    Function: sd_pkt_reason_cmd_timeout
19184  *
19185  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
19186  *
19187  *     Context: May be called from interrupt context
19188  */
19189 
19190 static void
19191 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19192     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 
19201 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19202 	sd_reset_target(un, pktp);
19203 
19204 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19205 
19206 	/*
19207 	 * A command timeout indicates that we could not establish
19208 	 * communication with the target, so set SD_RETRIES_FAILFAST
19209 	 * as further retries/commands are likely to take a long time.
19210 	 */
19211 	sd_retry_command(un, bp,
19212 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
19213 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19214 }
19215 
19216 
19217 
19218 /*
19219  *    Function: sd_pkt_reason_cmd_unx_bus_free
19220  *
19221  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
19222  *
19223  *     Context: May be called from interrupt context
19224  */
19225 
19226 static void
19227 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
19228     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19229 {
19230 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
19231 
19232 	ASSERT(un != NULL);
19233 	ASSERT(mutex_owned(SD_MUTEX(un)));
19234 	ASSERT(bp != NULL);
19235 	ASSERT(xp != NULL);
19236 	ASSERT(pktp != NULL);
19237 
19238 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19239 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19240 
19241 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
19242 	    sd_print_retry_msg : NULL;
19243 
19244 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19245 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19246 }
19247 
19248 
19249 /*
19250  *    Function: sd_pkt_reason_cmd_tag_reject
19251  *
19252  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
19253  *
19254  *     Context: May be called from interrupt context
19255  */
19256 
19257 static void
19258 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
19259     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19260 {
19261 	ASSERT(un != NULL);
19262 	ASSERT(mutex_owned(SD_MUTEX(un)));
19263 	ASSERT(bp != NULL);
19264 	ASSERT(xp != NULL);
19265 	ASSERT(pktp != NULL);
19266 
19267 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19268 	pktp->pkt_flags = 0;
19269 	un->un_tagflags = 0;
19270 	if (un->un_f_opt_queueing == TRUE) {
19271 		un->un_throttle = min(un->un_throttle, 3);
19272 	} else {
19273 		un->un_throttle = 1;
19274 	}
19275 	mutex_exit(SD_MUTEX(un));
19276 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
19277 	mutex_enter(SD_MUTEX(un));
19278 
19279 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19280 
19281 	/* Legacy behavior not to check retry counts here. */
19282 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
19283 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19284 }
19285 
19286 
19287 /*
19288  *    Function: sd_pkt_reason_default
19289  *
19290  * Description: Default recovery actions for SCSA pkt_reason values that
19291  *		do not have more explicit recovery actions.
19292  *
19293  *     Context: May be called from interrupt context
19294  */
19295 
19296 static void
19297 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19298     struct scsi_pkt *pktp)
19299 {
19300 	ASSERT(un != NULL);
19301 	ASSERT(mutex_owned(SD_MUTEX(un)));
19302 	ASSERT(bp != NULL);
19303 	ASSERT(xp != NULL);
19304 	ASSERT(pktp != NULL);
19305 
19306 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19307 	sd_reset_target(un, pktp);
19308 
19309 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19310 
19311 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19312 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19313 }
19314 
19315 
19316 
19317 /*
19318  *    Function: sd_pkt_status_check_condition
19319  *
19320  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
19321  *
19322  *     Context: May be called from interrupt context
19323  */
19324 
19325 static void
19326 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
19327     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19328 {
19329 	ASSERT(un != NULL);
19330 	ASSERT(mutex_owned(SD_MUTEX(un)));
19331 	ASSERT(bp != NULL);
19332 	ASSERT(xp != NULL);
19333 	ASSERT(pktp != NULL);
19334 
19335 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
19336 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
19337 
19338 	/*
19339 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
19340 	 * command will be retried after the request sense). Otherwise, retry
19341 	 * the command. Note: we are issuing the request sense even though the
19342 	 * retry limit may have been reached for the failed command.
19343 	 */
19344 	if (un->un_f_arq_enabled == FALSE) {
19345 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19346 		    "no ARQ, sending request sense command\n");
19347 		sd_send_request_sense_command(un, bp, pktp);
19348 	} else {
19349 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19350 		    "ARQ,retrying request sense command\n");
19351 #if defined(__x86)
19352 		/*
19353 		 * The SD_RETRY_DELAY value need to be adjusted here
19354 		 * when SD_RETRY_DELAY change in sddef.h
19355 		 */
19356 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19357 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
19358 		    NULL);
19359 #else
19360 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
19361 		    EIO, SD_RETRY_DELAY, NULL);
19362 #endif
19363 	}
19364 
19365 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
19366 }
19367 
19368 
19369 /*
19370  *    Function: sd_pkt_status_busy
19371  *
19372  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
19373  *
19374  *     Context: May be called from interrupt context
19375  */
19376 
19377 static void
19378 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19379     struct scsi_pkt *pktp)
19380 {
19381 	ASSERT(un != NULL);
19382 	ASSERT(mutex_owned(SD_MUTEX(un)));
19383 	ASSERT(bp != NULL);
19384 	ASSERT(xp != NULL);
19385 	ASSERT(pktp != NULL);
19386 
19387 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19388 	    "sd_pkt_status_busy: entry\n");
19389 
19390 	/* If retries are exhausted, just fail the command. */
19391 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
19392 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19393 		    "device busy too long\n");
19394 		sd_return_failed_command(un, bp, EIO);
19395 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19396 		    "sd_pkt_status_busy: exit\n");
19397 		return;
19398 	}
19399 	xp->xb_retry_count++;
19400 
19401 	/*
19402 	 * Try to reset the target. However, we do not want to perform
19403 	 * more than one reset if the device continues to fail. The reset
19404 	 * will be performed when the retry count reaches the reset
19405 	 * threshold.  This threshold should be set such that at least
19406 	 * one retry is issued before the reset is performed.
19407 	 */
19408 	if (xp->xb_retry_count ==
19409 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
19410 		int rval = 0;
19411 		mutex_exit(SD_MUTEX(un));
19412 		if (un->un_f_allow_bus_device_reset == TRUE) {
19413 			/*
19414 			 * First try to reset the LUN; if we cannot then
19415 			 * try to reset the target.
19416 			 */
19417 			if (un->un_f_lun_reset_enabled == TRUE) {
19418 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19419 				    "sd_pkt_status_busy: RESET_LUN\n");
19420 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19421 			}
19422 			if (rval == 0) {
19423 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19424 				    "sd_pkt_status_busy: RESET_TARGET\n");
19425 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19426 			}
19427 		}
19428 		if (rval == 0) {
19429 			/*
19430 			 * If the RESET_LUN and/or RESET_TARGET failed,
19431 			 * try RESET_ALL
19432 			 */
19433 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19434 			    "sd_pkt_status_busy: RESET_ALL\n");
19435 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
19436 		}
19437 		mutex_enter(SD_MUTEX(un));
19438 		if (rval == 0) {
19439 			/*
19440 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
19441 			 * At this point we give up & fail the command.
19442 			 */
19443 			sd_return_failed_command(un, bp, EIO);
19444 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19445 			    "sd_pkt_status_busy: exit (failed cmd)\n");
19446 			return;
19447 		}
19448 	}
19449 
19450 	/*
19451 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
19452 	 * we have already checked the retry counts above.
19453 	 */
19454 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
19455 	    EIO, un->un_busy_timeout, NULL);
19456 
19457 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19458 	    "sd_pkt_status_busy: exit\n");
19459 }
19460 
19461 
19462 /*
19463  *    Function: sd_pkt_status_reservation_conflict
19464  *
19465  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
19466  *		command status.
19467  *
19468  *     Context: May be called from interrupt context
19469  */
19470 
19471 static void
19472 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
19473     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19474 {
19475 	ASSERT(un != NULL);
19476 	ASSERT(mutex_owned(SD_MUTEX(un)));
19477 	ASSERT(bp != NULL);
19478 	ASSERT(xp != NULL);
19479 	ASSERT(pktp != NULL);
19480 
19481 	/*
19482 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
19483 	 * conflict could be due to various reasons like incorrect keys, not
19484 	 * registered or not reserved etc. So, we return EACCES to the caller.
19485 	 */
19486 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
19487 		int cmd = SD_GET_PKT_OPCODE(pktp);
19488 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
19489 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
19490 			sd_return_failed_command(un, bp, EACCES);
19491 			return;
19492 		}
19493 	}
19494 
19495 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
19496 
19497 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
19498 		if (sd_failfast_enable != 0) {
19499 			/* By definition, we must panic here.... */
19500 			sd_panic_for_res_conflict(un);
19501 			/*NOTREACHED*/
19502 		}
19503 		SD_ERROR(SD_LOG_IO, un,
19504 		    "sd_handle_resv_conflict: Disk Reserved\n");
19505 		sd_return_failed_command(un, bp, EACCES);
19506 		return;
19507 	}
19508 
19509 	/*
19510 	 * 1147670: retry only if sd_retry_on_reservation_conflict
19511 	 * property is set (default is 1). Retries will not succeed
19512 	 * on a disk reserved by another initiator. HA systems
19513 	 * may reset this via sd.conf to avoid these retries.
19514 	 *
19515 	 * Note: The legacy return code for this failure is EIO, however EACCES
19516 	 * seems more appropriate for a reservation conflict.
19517 	 */
19518 	if (sd_retry_on_reservation_conflict == 0) {
19519 		SD_ERROR(SD_LOG_IO, un,
19520 		    "sd_handle_resv_conflict: Device Reserved\n");
19521 		sd_return_failed_command(un, bp, EIO);
19522 		return;
19523 	}
19524 
19525 	/*
19526 	 * Retry the command if we can.
19527 	 *
19528 	 * Note: The legacy return code for this failure is EIO, however EACCES
19529 	 * seems more appropriate for a reservation conflict.
19530 	 */
19531 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19532 	    (clock_t)2, NULL);
19533 }
19534 
19535 
19536 
19537 /*
19538  *    Function: sd_pkt_status_qfull
19539  *
19540  * Description: Handle a QUEUE FULL condition from the target.  This can
19541  *		occur if the HBA does not handle the queue full condition.
19542  *		(Basically this means third-party HBAs as Sun HBAs will
19543  *		handle the queue full condition.)  Note that if there are
19544  *		some commands already in the transport, then the queue full
19545  *		has occurred because the queue for this nexus is actually
19546  *		full. If there are no commands in the transport, then the
19547  *		queue full is resulting from some other initiator or lun
19548  *		consuming all the resources at the target.
19549  *
19550  *     Context: May be called from interrupt context
19551  */
19552 
19553 static void
19554 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19555     struct scsi_pkt *pktp)
19556 {
19557 	ASSERT(un != NULL);
19558 	ASSERT(mutex_owned(SD_MUTEX(un)));
19559 	ASSERT(bp != NULL);
19560 	ASSERT(xp != NULL);
19561 	ASSERT(pktp != NULL);
19562 
19563 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19564 	    "sd_pkt_status_qfull: entry\n");
19565 
19566 	/*
19567 	 * Just lower the QFULL throttle and retry the command.  Note that
19568 	 * we do not limit the number of retries here.
19569 	 */
19570 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
19571 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
19572 	    SD_RESTART_TIMEOUT, NULL);
19573 
19574 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19575 	    "sd_pkt_status_qfull: exit\n");
19576 }
19577 
19578 
19579 /*
19580  *    Function: sd_reset_target
19581  *
19582  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
19583  *		RESET_TARGET, or RESET_ALL.
19584  *
19585  *     Context: May be called under interrupt context.
19586  */
19587 
19588 static void
19589 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
19590 {
19591 	int rval = 0;
19592 
19593 	ASSERT(un != NULL);
19594 	ASSERT(mutex_owned(SD_MUTEX(un)));
19595 	ASSERT(pktp != NULL);
19596 
19597 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
19598 
19599 	/*
19600 	 * No need to reset if the transport layer has already done so.
19601 	 */
19602 	if ((pktp->pkt_statistics &
19603 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
19604 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19605 		    "sd_reset_target: no reset\n");
19606 		return;
19607 	}
19608 
19609 	mutex_exit(SD_MUTEX(un));
19610 
19611 	if (un->un_f_allow_bus_device_reset == TRUE) {
19612 		if (un->un_f_lun_reset_enabled == TRUE) {
19613 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19614 			    "sd_reset_target: RESET_LUN\n");
19615 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19616 		}
19617 		if (rval == 0) {
19618 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19619 			    "sd_reset_target: RESET_TARGET\n");
19620 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19621 		}
19622 	}
19623 
19624 	if (rval == 0) {
19625 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19626 		    "sd_reset_target: RESET_ALL\n");
19627 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
19628 	}
19629 
19630 	mutex_enter(SD_MUTEX(un));
19631 
19632 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
19633 }
19634 
19635 /*
19636  *    Function: sd_target_change_task
19637  *
19638  * Description: Handle dynamic target change
19639  *
19640  *     Context: Executes in a taskq() thread context
19641  */
19642 static void
19643 sd_target_change_task(void *arg)
19644 {
19645 	struct sd_lun		*un = arg;
19646 	uint64_t		capacity;
19647 	diskaddr_t		label_cap;
19648 	uint_t			lbasize;
19649 	sd_ssc_t		*ssc;
19650 
19651 	ASSERT(un != NULL);
19652 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19653 
19654 	if ((un->un_f_blockcount_is_valid == FALSE) ||
19655 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
19656 		return;
19657 	}
19658 
19659 	ssc = sd_ssc_init(un);
19660 
19661 	if (sd_send_scsi_READ_CAPACITY(ssc, &capacity,
19662 	    &lbasize, SD_PATH_DIRECT) != 0) {
19663 		SD_ERROR(SD_LOG_ERROR, un,
19664 		    "sd_target_change_task: fail to read capacity\n");
19665 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19666 		goto task_exit;
19667 	}
19668 
19669 	mutex_enter(SD_MUTEX(un));
19670 	if (capacity <= un->un_blockcount) {
19671 		mutex_exit(SD_MUTEX(un));
19672 		goto task_exit;
19673 	}
19674 
19675 	sd_update_block_info(un, lbasize, capacity);
19676 	mutex_exit(SD_MUTEX(un));
19677 
19678 	/*
19679 	 * If lun is EFI labeled and lun capacity is greater than the
19680 	 * capacity contained in the label, log a sys event.
19681 	 */
19682 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
19683 	    (void*)SD_PATH_DIRECT) == 0) {
19684 		mutex_enter(SD_MUTEX(un));
19685 		if (un->un_f_blockcount_is_valid &&
19686 		    un->un_blockcount > label_cap) {
19687 			mutex_exit(SD_MUTEX(un));
19688 			sd_log_lun_expansion_event(un, KM_SLEEP);
19689 		} else {
19690 			mutex_exit(SD_MUTEX(un));
19691 		}
19692 	}
19693 
19694 task_exit:
19695 	sd_ssc_fini(ssc);
19696 }
19697 
19698 
19699 /*
19700  *    Function: sd_log_dev_status_event
19701  *
19702  * Description: Log EC_dev_status sysevent
19703  *
19704  *     Context: Never called from interrupt context
19705  */
19706 static void
19707 sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag)
19708 {
19709 	int err;
19710 	char			*path;
19711 	nvlist_t		*attr_list;
19712 	size_t			n;
19713 
19714 	/* Allocate and build sysevent attribute list */
19715 	err = nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
19716 	if (err != 0) {
19717 		SD_ERROR(SD_LOG_ERROR, un,
19718 		    "sd_log_dev_status_event: fail to allocate space\n");
19719 		return;
19720 	}
19721 
19722 	path = kmem_alloc(MAXPATHLEN, km_flag);
19723 	if (path == NULL) {
19724 		nvlist_free(attr_list);
19725 		SD_ERROR(SD_LOG_ERROR, un,
19726 		    "sd_log_dev_status_event: fail to allocate space\n");
19727 		return;
19728 	}
19729 
19730 	n = snprintf(path, MAXPATHLEN, "/devices");
19731 	(void) ddi_pathname(SD_DEVINFO(un), path + n);
19732 	n = strlen(path);
19733 	n += snprintf(path + n, MAXPATHLEN - n, ":x");
19734 
19735 	/*
19736 	 * On receipt of this event, the ZFS sysevent module will scan
19737 	 * active zpools for child vdevs matching this physical path.
19738 	 * In order to catch both whole disk pools and those with an
19739 	 * EFI boot partition, generate separate sysevents for minor
19740 	 * node 'a' and 'b'.
19741 	 */
19742 	for (char c = 'a'; c < 'c'; c++) {
19743 		path[n - 1] = c;
19744 
19745 		err = nvlist_add_string(attr_list, DEV_PHYS_PATH, path);
19746 		if (err != 0) {
19747 			SD_ERROR(SD_LOG_ERROR, un,
19748 			    "sd_log_dev_status_event: fail to add attribute\n");
19749 			break;
19750 		}
19751 
19752 		err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR,
19753 		    EC_DEV_STATUS, esc, attr_list, NULL, km_flag);
19754 		if (err != DDI_SUCCESS) {
19755 			SD_ERROR(SD_LOG_ERROR, un,
19756 			    "sd_log_dev_status_event: fail to log sysevent\n");
19757 			break;
19758 		}
19759 	}
19760 
19761 	nvlist_free(attr_list);
19762 	kmem_free(path, MAXPATHLEN);
19763 }
19764 
19765 
19766 /*
19767  *    Function: sd_log_lun_expansion_event
19768  *
19769  * Description: Log lun expansion sys event
19770  *
19771  *     Context: Never called from interrupt context
19772  */
19773 static void
19774 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
19775 {
19776 	sd_log_dev_status_event(un, ESC_DEV_DLE, km_flag);
19777 }
19778 
19779 
19780 /*
19781  *    Function: sd_log_eject_request_event
19782  *
19783  * Description: Log eject request sysevent
19784  *
19785  *     Context: Never called from interrupt context
19786  */
19787 static void
19788 sd_log_eject_request_event(struct sd_lun *un, int km_flag)
19789 {
19790 	sd_log_dev_status_event(un, ESC_DEV_EJECT_REQUEST, km_flag);
19791 }
19792 
19793 
19794 /*
19795  *    Function: sd_media_change_task
19796  *
19797  * Description: Recovery action for CDROM to become available.
19798  *
19799  *     Context: Executes in a taskq() thread context
19800  */
19801 
19802 static void
19803 sd_media_change_task(void *arg)
19804 {
19805 	struct	scsi_pkt	*pktp = arg;
19806 	struct	sd_lun		*un;
19807 	struct	buf		*bp;
19808 	struct	sd_xbuf		*xp;
19809 	int	err		= 0;
19810 	int	retry_count	= 0;
19811 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
19812 	struct	sd_sense_info	si;
19813 
19814 	ASSERT(pktp != NULL);
19815 	bp = (struct buf *)pktp->pkt_private;
19816 	ASSERT(bp != NULL);
19817 	xp = SD_GET_XBUF(bp);
19818 	ASSERT(xp != NULL);
19819 	un = SD_GET_UN(bp);
19820 	ASSERT(un != NULL);
19821 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19822 	ASSERT(un->un_f_monitor_media_state);
19823 
19824 	si.ssi_severity = SCSI_ERR_INFO;
19825 	si.ssi_pfa_flag = FALSE;
19826 
19827 	/*
19828 	 * When a reset is issued on a CDROM, it takes a long time to
19829 	 * recover. First few attempts to read capacity and other things
19830 	 * related to handling unit attention fail (with a ASC 0x4 and
19831 	 * ASCQ 0x1). In that case we want to do enough retries and we want
19832 	 * to limit the retries in other cases of genuine failures like
19833 	 * no media in drive.
19834 	 */
19835 	while (retry_count++ < retry_limit) {
19836 		if ((err = sd_handle_mchange(un)) == 0) {
19837 			break;
19838 		}
19839 		if (err == EAGAIN) {
19840 			retry_limit = SD_UNIT_ATTENTION_RETRY;
19841 		}
19842 		/* Sleep for 0.5 sec. & try again */
19843 		delay(drv_usectohz(500000));
19844 	}
19845 
19846 	/*
19847 	 * Dispatch (retry or fail) the original command here,
19848 	 * along with appropriate console messages....
19849 	 *
19850 	 * Must grab the mutex before calling sd_retry_command,
19851 	 * sd_print_sense_msg and sd_return_failed_command.
19852 	 */
19853 	mutex_enter(SD_MUTEX(un));
19854 	if (err != SD_CMD_SUCCESS) {
19855 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
19856 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
19857 		si.ssi_severity = SCSI_ERR_FATAL;
19858 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
19859 		sd_return_failed_command(un, bp, EIO);
19860 	} else {
19861 		sd_retry_command(un, bp, SD_RETRIES_UA, sd_print_sense_msg,
19862 		    &si, EIO, (clock_t)0, NULL);
19863 	}
19864 	mutex_exit(SD_MUTEX(un));
19865 }
19866 
19867 
19868 
19869 /*
19870  *    Function: sd_handle_mchange
19871  *
19872  * Description: Perform geometry validation & other recovery when CDROM
19873  *		has been removed from drive.
19874  *
19875  * Return Code: 0 for success
19876  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
19877  *		sd_send_scsi_READ_CAPACITY()
19878  *
19879  *     Context: Executes in a taskq() thread context
19880  */
19881 
19882 static int
19883 sd_handle_mchange(struct sd_lun *un)
19884 {
19885 	uint64_t	capacity;
19886 	uint32_t	lbasize;
19887 	int		rval;
19888 	sd_ssc_t	*ssc;
19889 
19890 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19891 	ASSERT(un->un_f_monitor_media_state);
19892 
19893 	ssc = sd_ssc_init(un);
19894 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
19895 	    SD_PATH_DIRECT_PRIORITY);
19896 
19897 	if (rval != 0)
19898 		goto failed;
19899 
19900 	mutex_enter(SD_MUTEX(un));
19901 	sd_update_block_info(un, lbasize, capacity);
19902 
19903 	if (un->un_errstats != NULL) {
19904 		struct	sd_errstats *stp =
19905 		    (struct sd_errstats *)un->un_errstats->ks_data;
19906 		stp->sd_capacity.value.ui64 = (uint64_t)
19907 		    ((uint64_t)un->un_blockcount *
19908 		    (uint64_t)un->un_tgt_blocksize);
19909 	}
19910 
19911 	/*
19912 	 * Check if the media in the device is writable or not
19913 	 */
19914 	if (ISCD(un)) {
19915 		sd_check_for_writable_cd(ssc, SD_PATH_DIRECT_PRIORITY);
19916 	}
19917 
19918 	/*
19919 	 * Note: Maybe let the strategy/partitioning chain worry about getting
19920 	 * valid geometry.
19921 	 */
19922 	mutex_exit(SD_MUTEX(un));
19923 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
19924 
19925 
19926 	if (cmlb_validate(un->un_cmlbhandle, 0,
19927 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
19928 		sd_ssc_fini(ssc);
19929 		return (EIO);
19930 	} else {
19931 		if (un->un_f_pkstats_enabled) {
19932 			sd_set_pstats(un);
19933 			SD_TRACE(SD_LOG_IO_PARTITION, un,
19934 			    "sd_handle_mchange: un:0x%p pstats created and "
19935 			    "set\n", un);
19936 		}
19937 	}
19938 
19939 	/*
19940 	 * Try to lock the door
19941 	 */
19942 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
19943 	    SD_PATH_DIRECT_PRIORITY);
19944 failed:
19945 	if (rval != 0)
19946 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19947 	sd_ssc_fini(ssc);
19948 	return (rval);
19949 }
19950 
19951 
19952 /*
19953  *    Function: sd_send_scsi_DOORLOCK
19954  *
19955  * Description: Issue the scsi DOOR LOCK command
19956  *
19957  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19958  *                      structure for this target.
19959  *		flag  - SD_REMOVAL_ALLOW
19960  *			SD_REMOVAL_PREVENT
19961  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19962  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19963  *			to use the USCSI "direct" chain and bypass the normal
19964  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19965  *			command is issued as part of an error recovery action.
19966  *
19967  * Return Code: 0   - Success
19968  *		errno return code from sd_ssc_send()
19969  *
19970  *     Context: Can sleep.
19971  */
19972 
19973 static int
19974 sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag)
19975 {
19976 	struct scsi_extended_sense	sense_buf;
19977 	union scsi_cdb		cdb;
19978 	struct uscsi_cmd	ucmd_buf;
19979 	int			status;
19980 	struct sd_lun		*un;
19981 
19982 	ASSERT(ssc != NULL);
19983 	un = ssc->ssc_un;
19984 	ASSERT(un != NULL);
19985 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19986 
19987 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
19988 
19989 	/* already determined doorlock is not supported, fake success */
19990 	if (un->un_f_doorlock_supported == FALSE) {
19991 		return (0);
19992 	}
19993 
19994 	/*
19995 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
19996 	 * ignore the command so we can complete the eject
19997 	 * operation.
19998 	 */
19999 	if (flag == SD_REMOVAL_PREVENT) {
20000 		mutex_enter(SD_MUTEX(un));
20001 		if (un->un_f_ejecting == TRUE) {
20002 			mutex_exit(SD_MUTEX(un));
20003 			return (EAGAIN);
20004 		}
20005 		mutex_exit(SD_MUTEX(un));
20006 	}
20007 
20008 	bzero(&cdb, sizeof (cdb));
20009 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20010 
20011 	cdb.scc_cmd = SCMD_DOORLOCK;
20012 	cdb.cdb_opaque[4] = (uchar_t)flag;
20013 
20014 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20015 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20016 	ucmd_buf.uscsi_bufaddr	= NULL;
20017 	ucmd_buf.uscsi_buflen	= 0;
20018 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20019 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20020 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20021 	ucmd_buf.uscsi_timeout	= 15;
20022 
20023 	SD_TRACE(SD_LOG_IO, un,
20024 	    "sd_send_scsi_DOORLOCK: returning sd_ssc_send\n");
20025 
20026 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20027 	    UIO_SYSSPACE, path_flag);
20028 
20029 	if (status == 0)
20030 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20031 
20032 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
20033 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20034 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
20035 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20036 
20037 		/* fake success and skip subsequent doorlock commands */
20038 		un->un_f_doorlock_supported = FALSE;
20039 		return (0);
20040 	}
20041 
20042 	return (status);
20043 }
20044 
20045 /*
20046  *    Function: sd_send_scsi_READ_CAPACITY
20047  *
20048  * Description: This routine uses the scsi READ CAPACITY command to determine
20049  *		the device capacity in number of blocks and the device native
20050  *		block size. If this function returns a failure, then the
20051  *		values in *capp and *lbap are undefined.  If the capacity
20052  *		returned is 0xffffffff then the lun is too large for a
20053  *		normal READ CAPACITY command and the results of a
20054  *		READ CAPACITY 16 will be used instead.
20055  *
20056  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
20057  *		capp - ptr to unsigned 64-bit variable to receive the
20058  *			capacity value from the command.
20059  *		lbap - ptr to unsigned 32-bit varaible to receive the
20060  *			block size value from the command
20061  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20062  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20063  *			to use the USCSI "direct" chain and bypass the normal
20064  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
20065  *			command is issued as part of an error recovery action.
20066  *
20067  * Return Code: 0   - Success
20068  *		EIO - IO error
20069  *		EACCES - Reservation conflict detected
20070  *		EAGAIN - Device is becoming ready
20071  *		errno return code from sd_ssc_send()
20072  *
20073  *     Context: Can sleep.  Blocks until command completes.
20074  */
20075 
20076 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
20077 
20078 static int
20079 sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
20080     int path_flag)
20081 {
20082 	struct	scsi_extended_sense	sense_buf;
20083 	struct	uscsi_cmd	ucmd_buf;
20084 	union	scsi_cdb	cdb;
20085 	uint32_t		*capacity_buf;
20086 	uint64_t		capacity;
20087 	uint32_t		lbasize;
20088 	uint32_t		pbsize;
20089 	int			status;
20090 	struct sd_lun		*un;
20091 
20092 	ASSERT(ssc != NULL);
20093 
20094 	un = ssc->ssc_un;
20095 	ASSERT(un != NULL);
20096 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20097 	ASSERT(capp != NULL);
20098 	ASSERT(lbap != NULL);
20099 
20100 	SD_TRACE(SD_LOG_IO, un,
20101 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20102 
20103 	/*
20104 	 * First send a READ_CAPACITY command to the target.
20105 	 * (This command is mandatory under SCSI-2.)
20106 	 *
20107 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
20108 	 * Medium Indicator bit is cleared.  The address field must be
20109 	 * zero if the PMI bit is zero.
20110 	 */
20111 	bzero(&cdb, sizeof (cdb));
20112 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20113 
20114 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
20115 
20116 	cdb.scc_cmd = SCMD_READ_CAPACITY;
20117 
20118 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20119 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20120 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
20121 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
20122 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20123 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20124 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20125 	ucmd_buf.uscsi_timeout	= 60;
20126 
20127 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20128 	    UIO_SYSSPACE, path_flag);
20129 
20130 	switch (status) {
20131 	case 0:
20132 		/* Return failure if we did not get valid capacity data. */
20133 		if (ucmd_buf.uscsi_resid != 0) {
20134 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20135 			    "sd_send_scsi_READ_CAPACITY received invalid "
20136 			    "capacity data");
20137 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20138 			return (EIO);
20139 		}
20140 		/*
20141 		 * Read capacity and block size from the READ CAPACITY 10 data.
20142 		 * This data may be adjusted later due to device specific
20143 		 * issues.
20144 		 *
20145 		 * According to the SCSI spec, the READ CAPACITY 10
20146 		 * command returns the following:
20147 		 *
20148 		 *  bytes 0-3: Maximum logical block address available.
20149 		 *		(MSB in byte:0 & LSB in byte:3)
20150 		 *
20151 		 *  bytes 4-7: Block length in bytes
20152 		 *		(MSB in byte:4 & LSB in byte:7)
20153 		 *
20154 		 */
20155 		capacity = BE_32(capacity_buf[0]);
20156 		lbasize = BE_32(capacity_buf[1]);
20157 
20158 		/*
20159 		 * Done with capacity_buf
20160 		 */
20161 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20162 
20163 		/*
20164 		 * if the reported capacity is set to all 0xf's, then
20165 		 * this disk is too large and requires SBC-2 commands.
20166 		 * Reissue the request using READ CAPACITY 16.
20167 		 */
20168 		if (capacity == 0xffffffff) {
20169 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20170 			status = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity,
20171 			    &lbasize, &pbsize, path_flag);
20172 			if (status != 0) {
20173 				return (status);
20174 			} else {
20175 				goto rc16_done;
20176 			}
20177 		}
20178 		break;	/* Success! */
20179 	case EIO:
20180 		switch (ucmd_buf.uscsi_status) {
20181 		case STATUS_RESERVATION_CONFLICT:
20182 			status = EACCES;
20183 			break;
20184 		case STATUS_CHECK:
20185 			/*
20186 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20187 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20188 			 */
20189 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20190 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20191 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20192 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20193 				return (EAGAIN);
20194 			}
20195 			break;
20196 		default:
20197 			break;
20198 		}
20199 		/* FALLTHRU */
20200 	default:
20201 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20202 		return (status);
20203 	}
20204 
20205 	/*
20206 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20207 	 * (2352 and 0 are common) so for these devices always force the value
20208 	 * to 2048 as required by the ATAPI specs.
20209 	 */
20210 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20211 		lbasize = 2048;
20212 	}
20213 
20214 	/*
20215 	 * Get the maximum LBA value from the READ CAPACITY data.
20216 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20217 	 * was cleared when issuing the command. This means that the LBA
20218 	 * returned from the device is the LBA of the last logical block
20219 	 * on the logical unit.  The actual logical block count will be
20220 	 * this value plus one.
20221 	 */
20222 	capacity += 1;
20223 
20224 	/*
20225 	 * Currently, for removable media, the capacity is saved in terms
20226 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20227 	 */
20228 	if (un->un_f_has_removable_media)
20229 		capacity *= (lbasize / un->un_sys_blocksize);
20230 
20231 rc16_done:
20232 
20233 	/*
20234 	 * Copy the values from the READ CAPACITY command into the space
20235 	 * provided by the caller.
20236 	 */
20237 	*capp = capacity;
20238 	*lbap = lbasize;
20239 
20240 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
20241 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
20242 
20243 	/*
20244 	 * Both the lbasize and capacity from the device must be nonzero,
20245 	 * otherwise we assume that the values are not valid and return
20246 	 * failure to the caller. (4203735)
20247 	 */
20248 	if ((capacity == 0) || (lbasize == 0)) {
20249 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20250 		    "sd_send_scsi_READ_CAPACITY received invalid value "
20251 		    "capacity %llu lbasize %d", capacity, lbasize);
20252 		return (EIO);
20253 	}
20254 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20255 	return (0);
20256 }
20257 
20258 /*
20259  *    Function: sd_send_scsi_READ_CAPACITY_16
20260  *
20261  * Description: This routine uses the scsi READ CAPACITY 16 command to
20262  *		determine the device capacity in number of blocks and the
20263  *		device native block size.  If this function returns a failure,
20264  *		then the values in *capp and *lbap are undefined.
20265  *		This routine should be called by sd_send_scsi_READ_CAPACITY
20266  *              which will apply any device specific adjustments to capacity
20267  *              and lbasize. One exception is it is also called by
20268  *              sd_get_media_info_ext. In that function, there is no need to
20269  *              adjust the capacity and lbasize.
20270  *
20271  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
20272  *		capp - ptr to unsigned 64-bit variable to receive the
20273  *			capacity value from the command.
20274  *		lbap - ptr to unsigned 32-bit varaible to receive the
20275  *			block size value from the command
20276  *              psp  - ptr to unsigned 32-bit variable to receive the
20277  *                      physical block size value from the command
20278  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20279  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20280  *			to use the USCSI "direct" chain and bypass the normal
20281  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
20282  *			this command is issued as part of an error recovery
20283  *			action.
20284  *
20285  * Return Code: 0   - Success
20286  *		EIO - IO error
20287  *		EACCES - Reservation conflict detected
20288  *		EAGAIN - Device is becoming ready
20289  *		errno return code from sd_ssc_send()
20290  *
20291  *     Context: Can sleep.  Blocks until command completes.
20292  */
20293 
20294 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
20295 
20296 static int
20297 sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
20298     uint32_t *psp, int path_flag)
20299 {
20300 	struct	scsi_extended_sense	sense_buf;
20301 	struct	uscsi_cmd	ucmd_buf;
20302 	union	scsi_cdb	cdb;
20303 	uint64_t		*capacity16_buf;
20304 	uint64_t		capacity;
20305 	uint32_t		lbasize;
20306 	uint32_t		pbsize;
20307 	uint32_t		lbpb_exp;
20308 	int			status;
20309 	struct sd_lun		*un;
20310 
20311 	ASSERT(ssc != NULL);
20312 
20313 	un = ssc->ssc_un;
20314 	ASSERT(un != NULL);
20315 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20316 	ASSERT(capp != NULL);
20317 	ASSERT(lbap != NULL);
20318 
20319 	SD_TRACE(SD_LOG_IO, un,
20320 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20321 
20322 	/*
20323 	 * First send a READ_CAPACITY_16 command to the target.
20324 	 *
20325 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
20326 	 * Medium Indicator bit is cleared.  The address field must be
20327 	 * zero if the PMI bit is zero.
20328 	 */
20329 	bzero(&cdb, sizeof (cdb));
20330 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20331 
20332 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
20333 
20334 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20335 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
20336 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
20337 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
20338 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20339 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20340 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20341 	ucmd_buf.uscsi_timeout	= 60;
20342 
20343 	/*
20344 	 * Read Capacity (16) is a Service Action In command.  One
20345 	 * command byte (0x9E) is overloaded for multiple operations,
20346 	 * with the second CDB byte specifying the desired operation
20347 	 */
20348 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
20349 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
20350 
20351 	/*
20352 	 * Fill in allocation length field
20353 	 */
20354 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
20355 
20356 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20357 	    UIO_SYSSPACE, path_flag);
20358 
20359 	switch (status) {
20360 	case 0:
20361 		/* Return failure if we did not get valid capacity data. */
20362 		if (ucmd_buf.uscsi_resid > 20) {
20363 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20364 			    "sd_send_scsi_READ_CAPACITY_16 received invalid "
20365 			    "capacity data");
20366 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20367 			return (EIO);
20368 		}
20369 
20370 		/*
20371 		 * Read capacity and block size from the READ CAPACITY 16 data.
20372 		 * This data may be adjusted later due to device specific
20373 		 * issues.
20374 		 *
20375 		 * According to the SCSI spec, the READ CAPACITY 16
20376 		 * command returns the following:
20377 		 *
20378 		 *  bytes 0-7: Maximum logical block address available.
20379 		 *		(MSB in byte:0 & LSB in byte:7)
20380 		 *
20381 		 *  bytes 8-11: Block length in bytes
20382 		 *		(MSB in byte:8 & LSB in byte:11)
20383 		 *
20384 		 *  byte 13: LOGICAL BLOCKS PER PHYSICAL BLOCK EXPONENT
20385 		 *
20386 		 *  byte 14:
20387 		 *	bit 7: Thin-Provisioning Enabled
20388 		 *	bit 6: Thin-Provisioning Read Zeros
20389 		 */
20390 		capacity = BE_64(capacity16_buf[0]);
20391 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
20392 		lbpb_exp = (BE_64(capacity16_buf[1]) >> 16) & 0x0f;
20393 
20394 		un->un_thin_flags = 0;
20395 		if (((uint8_t *)capacity16_buf)[14] & (1 << 7))
20396 			un->un_thin_flags |= SD_THIN_PROV_ENABLED;
20397 		if (((uint8_t *)capacity16_buf)[14] & (1 << 6))
20398 			un->un_thin_flags |= SD_THIN_PROV_READ_ZEROS;
20399 
20400 		pbsize = lbasize << lbpb_exp;
20401 
20402 		/*
20403 		 * Done with capacity16_buf
20404 		 */
20405 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20406 
20407 		/*
20408 		 * if the reported capacity is set to all 0xf's, then
20409 		 * this disk is too large.  This could only happen with
20410 		 * a device that supports LBAs larger than 64 bits which
20411 		 * are not defined by any current T10 standards.
20412 		 */
20413 		if (capacity == 0xffffffffffffffff) {
20414 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20415 			    "disk is too large");
20416 			return (EIO);
20417 		}
20418 		break;	/* Success! */
20419 	case EIO:
20420 		switch (ucmd_buf.uscsi_status) {
20421 		case STATUS_RESERVATION_CONFLICT:
20422 			status = EACCES;
20423 			break;
20424 		case STATUS_CHECK:
20425 			/*
20426 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20427 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20428 			 */
20429 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20430 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20431 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20432 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20433 				return (EAGAIN);
20434 			}
20435 			break;
20436 		default:
20437 			break;
20438 		}
20439 		/* FALLTHRU */
20440 	default:
20441 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20442 		return (status);
20443 	}
20444 
20445 	/*
20446 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20447 	 * (2352 and 0 are common) so for these devices always force the value
20448 	 * to 2048 as required by the ATAPI specs.
20449 	 */
20450 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20451 		lbasize = 2048;
20452 	}
20453 
20454 	/*
20455 	 * Get the maximum LBA value from the READ CAPACITY 16 data.
20456 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20457 	 * was cleared when issuing the command. This means that the LBA
20458 	 * returned from the device is the LBA of the last logical block
20459 	 * on the logical unit.  The actual logical block count will be
20460 	 * this value plus one.
20461 	 */
20462 	capacity += 1;
20463 
20464 	/*
20465 	 * Currently, for removable media, the capacity is saved in terms
20466 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20467 	 */
20468 	if (un->un_f_has_removable_media)
20469 		capacity *= (lbasize / un->un_sys_blocksize);
20470 
20471 	*capp = capacity;
20472 	*lbap = lbasize;
20473 	*psp = pbsize;
20474 
20475 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
20476 	    "capacity:0x%llx  lbasize:0x%x, pbsize: 0x%x\n",
20477 	    capacity, lbasize, pbsize);
20478 
20479 	if ((capacity == 0) || (lbasize == 0) || (pbsize == 0)) {
20480 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20481 		    "sd_send_scsi_READ_CAPACITY_16 received invalid value "
20482 		    "capacity %llu lbasize %d pbsize %d", capacity, lbasize);
20483 		return (EIO);
20484 	}
20485 
20486 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20487 	return (0);
20488 }
20489 
20490 
20491 /*
20492  *    Function: sd_send_scsi_START_STOP_UNIT
20493  *
20494  * Description: Issue a scsi START STOP UNIT command to the target.
20495  *
20496  *   Arguments: ssc    - ssc contatins pointer to driver soft state (unit)
20497  *                       structure for this target.
20498  *      pc_flag - SD_POWER_CONDITION
20499  *                SD_START_STOP
20500  *		flag  - SD_TARGET_START
20501  *			SD_TARGET_STOP
20502  *			SD_TARGET_EJECT
20503  *			SD_TARGET_CLOSE
20504  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20505  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20506  *			to use the USCSI "direct" chain and bypass the normal
20507  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
20508  *			command is issued as part of an error recovery action.
20509  *
20510  * Return Code: 0   - Success
20511  *		EIO - IO error
20512  *		EACCES - Reservation conflict detected
20513  *		ENXIO  - Not Ready, medium not present
20514  *		errno return code from sd_ssc_send()
20515  *
20516  *     Context: Can sleep.
20517  */
20518 
20519 static int
20520 sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag, int flag,
20521     int path_flag)
20522 {
20523 	struct	scsi_extended_sense	sense_buf;
20524 	union scsi_cdb		cdb;
20525 	struct uscsi_cmd	ucmd_buf;
20526 	int			status;
20527 	struct sd_lun		*un;
20528 
20529 	ASSERT(ssc != NULL);
20530 	un = ssc->ssc_un;
20531 	ASSERT(un != NULL);
20532 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20533 
20534 	SD_TRACE(SD_LOG_IO, un,
20535 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
20536 
20537 	if (un->un_f_check_start_stop &&
20538 	    (pc_flag == SD_START_STOP) &&
20539 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
20540 	    (un->un_f_start_stop_supported != TRUE)) {
20541 		return (0);
20542 	}
20543 
20544 	/*
20545 	 * If we are performing an eject operation and
20546 	 * we receive any command other than SD_TARGET_EJECT
20547 	 * we should immediately return.
20548 	 */
20549 	if (flag != SD_TARGET_EJECT) {
20550 		mutex_enter(SD_MUTEX(un));
20551 		if (un->un_f_ejecting == TRUE) {
20552 			mutex_exit(SD_MUTEX(un));
20553 			return (EAGAIN);
20554 		}
20555 		mutex_exit(SD_MUTEX(un));
20556 	}
20557 
20558 	bzero(&cdb, sizeof (cdb));
20559 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20560 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20561 
20562 	cdb.scc_cmd = SCMD_START_STOP;
20563 	cdb.cdb_opaque[4] = (pc_flag == SD_POWER_CONDITION) ?
20564 	    (uchar_t)(flag << 4) : (uchar_t)flag;
20565 
20566 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20567 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20568 	ucmd_buf.uscsi_bufaddr	= NULL;
20569 	ucmd_buf.uscsi_buflen	= 0;
20570 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20571 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20572 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20573 	ucmd_buf.uscsi_timeout	= 200;
20574 
20575 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20576 	    UIO_SYSSPACE, path_flag);
20577 
20578 	switch (status) {
20579 	case 0:
20580 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20581 		break;	/* Success! */
20582 	case EIO:
20583 		switch (ucmd_buf.uscsi_status) {
20584 		case STATUS_RESERVATION_CONFLICT:
20585 			status = EACCES;
20586 			break;
20587 		case STATUS_CHECK:
20588 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
20589 				switch (scsi_sense_key(
20590 				    (uint8_t *)&sense_buf)) {
20591 				case KEY_ILLEGAL_REQUEST:
20592 					status = ENOTSUP;
20593 					break;
20594 				case KEY_NOT_READY:
20595 					if (scsi_sense_asc(
20596 					    (uint8_t *)&sense_buf)
20597 					    == 0x3A) {
20598 						status = ENXIO;
20599 					}
20600 					break;
20601 				default:
20602 					break;
20603 				}
20604 			}
20605 			break;
20606 		default:
20607 			break;
20608 		}
20609 		break;
20610 	default:
20611 		break;
20612 	}
20613 
20614 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
20615 
20616 	return (status);
20617 }
20618 
20619 
20620 /*
20621  *    Function: sd_start_stop_unit_callback
20622  *
20623  * Description: timeout(9F) callback to begin recovery process for a
20624  *		device that has spun down.
20625  *
20626  *   Arguments: arg - pointer to associated softstate struct.
20627  *
20628  *     Context: Executes in a timeout(9F) thread context
20629  */
20630 
20631 static void
20632 sd_start_stop_unit_callback(void *arg)
20633 {
20634 	struct sd_lun	*un = arg;
20635 	ASSERT(un != NULL);
20636 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20637 
20638 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
20639 
20640 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
20641 }
20642 
20643 
20644 /*
20645  *    Function: sd_start_stop_unit_task
20646  *
20647  * Description: Recovery procedure when a drive is spun down.
20648  *
20649  *   Arguments: arg - pointer to associated softstate struct.
20650  *
20651  *     Context: Executes in a taskq() thread context
20652  */
20653 
20654 static void
20655 sd_start_stop_unit_task(void *arg)
20656 {
20657 	struct sd_lun	*un = arg;
20658 	sd_ssc_t	*ssc;
20659 	int		power_level;
20660 	int		rval;
20661 
20662 	ASSERT(un != NULL);
20663 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20664 
20665 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
20666 
20667 	/*
20668 	 * Some unformatted drives report not ready error, no need to
20669 	 * restart if format has been initiated.
20670 	 */
20671 	mutex_enter(SD_MUTEX(un));
20672 	if (un->un_f_format_in_progress == TRUE) {
20673 		mutex_exit(SD_MUTEX(un));
20674 		return;
20675 	}
20676 	mutex_exit(SD_MUTEX(un));
20677 
20678 	ssc = sd_ssc_init(un);
20679 	/*
20680 	 * When a START STOP command is issued from here, it is part of a
20681 	 * failure recovery operation and must be issued before any other
20682 	 * commands, including any pending retries. Thus it must be sent
20683 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
20684 	 * succeeds or not, we will start I/O after the attempt.
20685 	 * If power condition is supported and the current power level
20686 	 * is capable of performing I/O, we should set the power condition
20687 	 * to that level. Otherwise, set the power condition to ACTIVE.
20688 	 */
20689 	if (un->un_f_power_condition_supported) {
20690 		mutex_enter(SD_MUTEX(un));
20691 		ASSERT(SD_PM_IS_LEVEL_VALID(un, un->un_power_level));
20692 		power_level = sd_pwr_pc.ran_perf[un->un_power_level]
20693 		    > 0 ? un->un_power_level : SD_SPINDLE_ACTIVE;
20694 		mutex_exit(SD_MUTEX(un));
20695 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
20696 		    sd_pl2pc[power_level], SD_PATH_DIRECT_PRIORITY);
20697 	} else {
20698 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
20699 		    SD_TARGET_START, SD_PATH_DIRECT_PRIORITY);
20700 	}
20701 
20702 	if (rval != 0)
20703 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20704 	sd_ssc_fini(ssc);
20705 	/*
20706 	 * The above call blocks until the START_STOP_UNIT command completes.
20707 	 * Now that it has completed, we must re-try the original IO that
20708 	 * received the NOT READY condition in the first place. There are
20709 	 * three possible conditions here:
20710 	 *
20711 	 *  (1) The original IO is on un_retry_bp.
20712 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
20713 	 *	is NULL.
20714 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
20715 	 *	points to some other, unrelated bp.
20716 	 *
20717 	 * For each case, we must call sd_start_cmds() with un_retry_bp
20718 	 * as the argument. If un_retry_bp is NULL, this will initiate
20719 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
20720 	 * then this will process the bp on un_retry_bp. That may or may not
20721 	 * be the original IO, but that does not matter: the important thing
20722 	 * is to keep the IO processing going at this point.
20723 	 *
20724 	 * Note: This is a very specific error recovery sequence associated
20725 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
20726 	 * serialize the I/O with completion of the spin-up.
20727 	 */
20728 	mutex_enter(SD_MUTEX(un));
20729 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
20730 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
20731 	    un, un->un_retry_bp);
20732 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
20733 	sd_start_cmds(un, un->un_retry_bp);
20734 	mutex_exit(SD_MUTEX(un));
20735 
20736 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
20737 }
20738 
20739 
20740 /*
20741  *    Function: sd_send_scsi_INQUIRY
20742  *
20743  * Description: Issue the scsi INQUIRY command.
20744  *
20745  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20746  *                      structure for this target.
20747  *		bufaddr
20748  *		buflen
20749  *		evpd
20750  *		page_code
20751  *		page_length
20752  *
20753  * Return Code: 0   - Success
20754  *		errno return code from sd_ssc_send()
20755  *
20756  *     Context: Can sleep. Does not return until command is completed.
20757  */
20758 
20759 static int
20760 sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr, size_t buflen,
20761     uchar_t evpd, uchar_t page_code, size_t *residp)
20762 {
20763 	union scsi_cdb		cdb;
20764 	struct uscsi_cmd	ucmd_buf;
20765 	int			status;
20766 	struct sd_lun		*un;
20767 
20768 	ASSERT(ssc != NULL);
20769 	un = ssc->ssc_un;
20770 	ASSERT(un != NULL);
20771 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20772 	ASSERT(bufaddr != NULL);
20773 
20774 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
20775 
20776 	bzero(&cdb, sizeof (cdb));
20777 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20778 	bzero(bufaddr, buflen);
20779 
20780 	cdb.scc_cmd = SCMD_INQUIRY;
20781 	cdb.cdb_opaque[1] = evpd;
20782 	cdb.cdb_opaque[2] = page_code;
20783 	FORMG0COUNT(&cdb, buflen);
20784 
20785 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20786 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20787 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20788 	ucmd_buf.uscsi_buflen	= buflen;
20789 	ucmd_buf.uscsi_rqbuf	= NULL;
20790 	ucmd_buf.uscsi_rqlen	= 0;
20791 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
20792 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
20793 
20794 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20795 	    UIO_SYSSPACE, SD_PATH_DIRECT);
20796 
20797 	/*
20798 	 * Only handle status == 0, the upper-level caller
20799 	 * will put different assessment based on the context.
20800 	 */
20801 	if (status == 0)
20802 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20803 
20804 	if ((status == 0) && (residp != NULL)) {
20805 		*residp = ucmd_buf.uscsi_resid;
20806 	}
20807 
20808 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
20809 
20810 	return (status);
20811 }
20812 
20813 
20814 /*
20815  *    Function: sd_send_scsi_TEST_UNIT_READY
20816  *
20817  * Description: Issue the scsi TEST UNIT READY command.
20818  *		This routine can be told to set the flag USCSI_DIAGNOSE to
20819  *		prevent retrying failed commands. Use this when the intent
20820  *		is either to check for device readiness, to clear a Unit
20821  *		Attention, or to clear any outstanding sense data.
20822  *		However under specific conditions the expected behavior
20823  *		is for retries to bring a device ready, so use the flag
20824  *		with caution.
20825  *
20826  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20827  *                      structure for this target.
20828  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
20829  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
20830  *			0: dont check for media present, do retries on cmd.
20831  *
20832  * Return Code: 0   - Success
20833  *		EIO - IO error
20834  *		EACCES - Reservation conflict detected
20835  *		ENXIO  - Not Ready, medium not present
20836  *		errno return code from sd_ssc_send()
20837  *
20838  *     Context: Can sleep. Does not return until command is completed.
20839  */
20840 
20841 static int
20842 sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag)
20843 {
20844 	struct	scsi_extended_sense	sense_buf;
20845 	union scsi_cdb		cdb;
20846 	struct uscsi_cmd	ucmd_buf;
20847 	int			status;
20848 	struct sd_lun		*un;
20849 
20850 	ASSERT(ssc != NULL);
20851 	un = ssc->ssc_un;
20852 	ASSERT(un != NULL);
20853 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20854 
20855 	SD_TRACE(SD_LOG_IO, un,
20856 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
20857 
20858 	/*
20859 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
20860 	 * timeouts when they receive a TUR and the queue is not empty. Check
20861 	 * the configuration flag set during attach (indicating the drive has
20862 	 * this firmware bug) and un_ncmds_in_transport before issuing the
20863 	 * TUR. If there are
20864 	 * pending commands return success, this is a bit arbitrary but is ok
20865 	 * for non-removables (i.e. the eliteI disks) and non-clustering
20866 	 * configurations.
20867 	 */
20868 	if (un->un_f_cfg_tur_check == TRUE) {
20869 		mutex_enter(SD_MUTEX(un));
20870 		if (un->un_ncmds_in_transport != 0) {
20871 			mutex_exit(SD_MUTEX(un));
20872 			return (0);
20873 		}
20874 		mutex_exit(SD_MUTEX(un));
20875 	}
20876 
20877 	bzero(&cdb, sizeof (cdb));
20878 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20879 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20880 
20881 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
20882 
20883 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20884 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20885 	ucmd_buf.uscsi_bufaddr	= NULL;
20886 	ucmd_buf.uscsi_buflen	= 0;
20887 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20888 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20889 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20890 
20891 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
20892 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
20893 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
20894 	}
20895 	ucmd_buf.uscsi_timeout	= 60;
20896 
20897 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20898 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
20899 	    SD_PATH_STANDARD));
20900 
20901 	switch (status) {
20902 	case 0:
20903 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20904 		break;	/* Success! */
20905 	case EIO:
20906 		switch (ucmd_buf.uscsi_status) {
20907 		case STATUS_RESERVATION_CONFLICT:
20908 			status = EACCES;
20909 			break;
20910 		case STATUS_CHECK:
20911 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
20912 				break;
20913 			}
20914 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20915 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20916 			    KEY_NOT_READY) &&
20917 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
20918 				status = ENXIO;
20919 			}
20920 			break;
20921 		default:
20922 			break;
20923 		}
20924 		break;
20925 	default:
20926 		break;
20927 	}
20928 
20929 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
20930 
20931 	return (status);
20932 }
20933 
20934 /*
20935  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
20936  *
20937  * Description: Issue the scsi PERSISTENT RESERVE IN command.
20938  *
20939  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20940  *                      structure for this target.
20941  *
20942  * Return Code: 0   - Success
20943  *		EACCES
20944  *		ENOTSUP
20945  *		errno return code from sd_ssc_send()
20946  *
20947  *     Context: Can sleep. Does not return until command is completed.
20948  */
20949 
20950 static int
20951 sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc, uchar_t usr_cmd,
20952     uint16_t data_len, uchar_t *data_bufp)
20953 {
20954 	struct scsi_extended_sense	sense_buf;
20955 	union scsi_cdb		cdb;
20956 	struct uscsi_cmd	ucmd_buf;
20957 	int			status;
20958 	int			no_caller_buf = FALSE;
20959 	struct sd_lun		*un;
20960 
20961 	ASSERT(ssc != NULL);
20962 	un = ssc->ssc_un;
20963 	ASSERT(un != NULL);
20964 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20965 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
20966 
20967 	SD_TRACE(SD_LOG_IO, un,
20968 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
20969 
20970 	bzero(&cdb, sizeof (cdb));
20971 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20972 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20973 	if (data_bufp == NULL) {
20974 		/* Allocate a default buf if the caller did not give one */
20975 		ASSERT(data_len == 0);
20976 		data_len  = MHIOC_RESV_KEY_SIZE;
20977 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
20978 		no_caller_buf = TRUE;
20979 	}
20980 
20981 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
20982 	cdb.cdb_opaque[1] = usr_cmd;
20983 	FORMG1COUNT(&cdb, data_len);
20984 
20985 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20986 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20987 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
20988 	ucmd_buf.uscsi_buflen	= data_len;
20989 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20990 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20991 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20992 	ucmd_buf.uscsi_timeout	= 60;
20993 
20994 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20995 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20996 
20997 	switch (status) {
20998 	case 0:
20999 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21000 
21001 		break;	/* Success! */
21002 	case EIO:
21003 		switch (ucmd_buf.uscsi_status) {
21004 		case STATUS_RESERVATION_CONFLICT:
21005 			status = EACCES;
21006 			break;
21007 		case STATUS_CHECK:
21008 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21009 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21010 			    KEY_ILLEGAL_REQUEST)) {
21011 				status = ENOTSUP;
21012 			}
21013 			break;
21014 		default:
21015 			break;
21016 		}
21017 		break;
21018 	default:
21019 		break;
21020 	}
21021 
21022 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
21023 
21024 	if (no_caller_buf == TRUE) {
21025 		kmem_free(data_bufp, data_len);
21026 	}
21027 
21028 	return (status);
21029 }
21030 
21031 
21032 /*
21033  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
21034  *
21035  * Description: This routine is the driver entry point for handling CD-ROM
21036  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
21037  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
21038  *		device.
21039  *
21040  *   Arguments: ssc  -  ssc contains un - pointer to soft state struct
21041  *                      for the target.
21042  *		usr_cmd SCSI-3 reservation facility command (one of
21043  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
21044  *			SD_SCSI3_PREEMPTANDABORT, SD_SCSI3_CLEAR)
21045  *		usr_bufp - user provided pointer register, reserve descriptor or
21046  *			preempt and abort structure (mhioc_register_t,
21047  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
21048  *
21049  * Return Code: 0   - Success
21050  *		EACCES
21051  *		ENOTSUP
21052  *		errno return code from sd_ssc_send()
21053  *
21054  *     Context: Can sleep. Does not return until command is completed.
21055  */
21056 
21057 static int
21058 sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc, uchar_t usr_cmd,
21059     uchar_t *usr_bufp)
21060 {
21061 	struct scsi_extended_sense	sense_buf;
21062 	union scsi_cdb		cdb;
21063 	struct uscsi_cmd	ucmd_buf;
21064 	int			status;
21065 	uchar_t			data_len = sizeof (sd_prout_t);
21066 	sd_prout_t		*prp;
21067 	struct sd_lun		*un;
21068 
21069 	ASSERT(ssc != NULL);
21070 	un = ssc->ssc_un;
21071 	ASSERT(un != NULL);
21072 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21073 	ASSERT(data_len == 24);	/* required by scsi spec */
21074 
21075 	SD_TRACE(SD_LOG_IO, un,
21076 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
21077 
21078 	if (usr_bufp == NULL) {
21079 		return (EINVAL);
21080 	}
21081 
21082 	bzero(&cdb, sizeof (cdb));
21083 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21084 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21085 	prp = kmem_zalloc(data_len, KM_SLEEP);
21086 
21087 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
21088 	cdb.cdb_opaque[1] = usr_cmd;
21089 	FORMG1COUNT(&cdb, data_len);
21090 
21091 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21092 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
21093 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
21094 	ucmd_buf.uscsi_buflen	= data_len;
21095 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21096 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21097 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
21098 	ucmd_buf.uscsi_timeout	= 60;
21099 
21100 	switch (usr_cmd) {
21101 	case SD_SCSI3_REGISTER: {
21102 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
21103 
21104 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21105 		bcopy(ptr->newkey.key, prp->service_key,
21106 		    MHIOC_RESV_KEY_SIZE);
21107 		prp->aptpl = ptr->aptpl;
21108 		break;
21109 	}
21110 	case SD_SCSI3_CLEAR: {
21111 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
21112 
21113 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21114 		break;
21115 	}
21116 	case SD_SCSI3_RESERVE:
21117 	case SD_SCSI3_RELEASE: {
21118 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
21119 
21120 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21121 		prp->scope_address = BE_32(ptr->scope_specific_addr);
21122 		cdb.cdb_opaque[2] = ptr->type;
21123 		break;
21124 	}
21125 	case SD_SCSI3_PREEMPTANDABORT: {
21126 		mhioc_preemptandabort_t *ptr =
21127 		    (mhioc_preemptandabort_t *)usr_bufp;
21128 
21129 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
21130 		bcopy(ptr->victim_key.key, prp->service_key,
21131 		    MHIOC_RESV_KEY_SIZE);
21132 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
21133 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
21134 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
21135 		break;
21136 	}
21137 	case SD_SCSI3_REGISTERANDIGNOREKEY:
21138 	{
21139 		mhioc_registerandignorekey_t *ptr;
21140 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
21141 		bcopy(ptr->newkey.key,
21142 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
21143 		prp->aptpl = ptr->aptpl;
21144 		break;
21145 	}
21146 	default:
21147 		ASSERT(FALSE);
21148 		break;
21149 	}
21150 
21151 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21152 	    UIO_SYSSPACE, SD_PATH_STANDARD);
21153 
21154 	switch (status) {
21155 	case 0:
21156 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21157 		break;	/* Success! */
21158 	case EIO:
21159 		switch (ucmd_buf.uscsi_status) {
21160 		case STATUS_RESERVATION_CONFLICT:
21161 			status = EACCES;
21162 			break;
21163 		case STATUS_CHECK:
21164 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21165 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21166 			    KEY_ILLEGAL_REQUEST)) {
21167 				status = ENOTSUP;
21168 			}
21169 			break;
21170 		default:
21171 			break;
21172 		}
21173 		break;
21174 	default:
21175 		break;
21176 	}
21177 
21178 	kmem_free(prp, data_len);
21179 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
21180 	return (status);
21181 }
21182 
21183 
21184 /*
21185  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
21186  *
21187  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
21188  *
21189  *   Arguments: un - pointer to the target's soft state struct
21190  *              dkc - pointer to the callback structure
21191  *
21192  * Return Code: 0 - success
21193  *		errno-type error code
21194  *
21195  *     Context: kernel thread context only.
21196  *
21197  *  _______________________________________________________________
21198  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
21199  * |FLUSH_VOLATILE|              | operation                       |
21200  * |______________|______________|_________________________________|
21201  * | 0            | NULL         | Synchronous flush on both       |
21202  * |              |              | volatile and non-volatile cache |
21203  * |______________|______________|_________________________________|
21204  * | 1            | NULL         | Synchronous flush on volatile   |
21205  * |              |              | cache; disk drivers may suppress|
21206  * |              |              | flush if disk table indicates   |
21207  * |              |              | non-volatile cache              |
21208  * |______________|______________|_________________________________|
21209  * | 0            | !NULL        | Asynchronous flush on both      |
21210  * |              |              | volatile and non-volatile cache;|
21211  * |______________|______________|_________________________________|
21212  * | 1            | !NULL        | Asynchronous flush on volatile  |
21213  * |              |              | cache; disk drivers may suppress|
21214  * |              |              | flush if disk table indicates   |
21215  * |              |              | non-volatile cache              |
21216  * |______________|______________|_________________________________|
21217  *
21218  */
21219 
21220 static int
21221 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
21222 {
21223 	struct sd_uscsi_info	*uip;
21224 	struct uscsi_cmd	*uscmd;
21225 	union scsi_cdb		*cdb;
21226 	struct buf		*bp;
21227 	int			rval = 0;
21228 	int			is_async;
21229 
21230 	SD_TRACE(SD_LOG_IO, un,
21231 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
21232 
21233 	ASSERT(un != NULL);
21234 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21235 
21236 	if (dkc == NULL || dkc->dkc_callback == NULL) {
21237 		is_async = FALSE;
21238 	} else {
21239 		is_async = TRUE;
21240 	}
21241 
21242 	mutex_enter(SD_MUTEX(un));
21243 	/* check whether cache flush should be suppressed */
21244 	if (un->un_f_suppress_cache_flush == TRUE) {
21245 		mutex_exit(SD_MUTEX(un));
21246 		/*
21247 		 * suppress the cache flush if the device is told to do
21248 		 * so by sd.conf or disk table
21249 		 */
21250 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
21251 		    skip the cache flush since suppress_cache_flush is %d!\n",
21252 		    un->un_f_suppress_cache_flush);
21253 
21254 		if (is_async == TRUE) {
21255 			/* invoke callback for asynchronous flush */
21256 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
21257 		}
21258 		return (rval);
21259 	}
21260 	mutex_exit(SD_MUTEX(un));
21261 
21262 	/*
21263 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
21264 	 * set properly
21265 	 */
21266 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
21267 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
21268 
21269 	mutex_enter(SD_MUTEX(un));
21270 	if (dkc != NULL && un->un_f_sync_nv_supported &&
21271 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
21272 		/*
21273 		 * if the device supports SYNC_NV bit, turn on
21274 		 * the SYNC_NV bit to only flush volatile cache
21275 		 */
21276 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
21277 	}
21278 	mutex_exit(SD_MUTEX(un));
21279 
21280 	/*
21281 	 * First get some memory for the uscsi_cmd struct and cdb
21282 	 * and initialize for SYNCHRONIZE_CACHE cmd.
21283 	 */
21284 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
21285 	uscmd->uscsi_cdblen = CDB_GROUP1;
21286 	uscmd->uscsi_cdb = (caddr_t)cdb;
21287 	uscmd->uscsi_bufaddr = NULL;
21288 	uscmd->uscsi_buflen = 0;
21289 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
21290 	uscmd->uscsi_rqlen = SENSE_LENGTH;
21291 	uscmd->uscsi_rqresid = SENSE_LENGTH;
21292 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
21293 	uscmd->uscsi_timeout = sd_io_time;
21294 
21295 	/*
21296 	 * Allocate an sd_uscsi_info struct and fill it with the info
21297 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
21298 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
21299 	 * since we allocate the buf here in this function, we do not
21300 	 * need to preserve the prior contents of b_private.
21301 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
21302 	 */
21303 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
21304 	uip->ui_flags = SD_PATH_DIRECT;
21305 	uip->ui_cmdp  = uscmd;
21306 
21307 	bp = getrbuf(KM_SLEEP);
21308 	bp->b_private = uip;
21309 
21310 	/*
21311 	 * Setup buffer to carry uscsi request.
21312 	 */
21313 	bp->b_flags  = B_BUSY;
21314 	bp->b_bcount = 0;
21315 	bp->b_blkno  = 0;
21316 
21317 	if (is_async == TRUE) {
21318 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
21319 		uip->ui_dkc = *dkc;
21320 	}
21321 
21322 	bp->b_edev = SD_GET_DEV(un);
21323 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
21324 
21325 	/*
21326 	 * Unset un_f_sync_cache_required flag
21327 	 */
21328 	mutex_enter(SD_MUTEX(un));
21329 	un->un_f_sync_cache_required = FALSE;
21330 	mutex_exit(SD_MUTEX(un));
21331 
21332 	(void) sd_uscsi_strategy(bp);
21333 
21334 	/*
21335 	 * If synchronous request, wait for completion
21336 	 * If async just return and let b_iodone callback
21337 	 * cleanup.
21338 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
21339 	 * but it was also incremented in sd_uscsi_strategy(), so
21340 	 * we should be ok.
21341 	 */
21342 	if (is_async == FALSE) {
21343 		(void) biowait(bp);
21344 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
21345 	}
21346 
21347 	return (rval);
21348 }
21349 
21350 
21351 static int
21352 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
21353 {
21354 	struct sd_uscsi_info *uip;
21355 	struct uscsi_cmd *uscmd;
21356 	uint8_t *sense_buf;
21357 	struct sd_lun *un;
21358 	int status;
21359 	union scsi_cdb *cdb;
21360 
21361 	uip = (struct sd_uscsi_info *)(bp->b_private);
21362 	ASSERT(uip != NULL);
21363 
21364 	uscmd = uip->ui_cmdp;
21365 	ASSERT(uscmd != NULL);
21366 
21367 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
21368 	ASSERT(sense_buf != NULL);
21369 
21370 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
21371 	ASSERT(un != NULL);
21372 
21373 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
21374 
21375 	status = geterror(bp);
21376 	switch (status) {
21377 	case 0:
21378 		break;	/* Success! */
21379 	case EIO:
21380 		switch (uscmd->uscsi_status) {
21381 		case STATUS_RESERVATION_CONFLICT:
21382 			/* Ignore reservation conflict */
21383 			status = 0;
21384 			goto done;
21385 
21386 		case STATUS_CHECK:
21387 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
21388 			    (scsi_sense_key(sense_buf) ==
21389 			    KEY_ILLEGAL_REQUEST)) {
21390 				/* Ignore Illegal Request error */
21391 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
21392 					mutex_enter(SD_MUTEX(un));
21393 					un->un_f_sync_nv_supported = FALSE;
21394 					mutex_exit(SD_MUTEX(un));
21395 					status = 0;
21396 					SD_TRACE(SD_LOG_IO, un,
21397 					    "un_f_sync_nv_supported \
21398 					    is set to false.\n");
21399 					goto done;
21400 				}
21401 
21402 				mutex_enter(SD_MUTEX(un));
21403 				un->un_f_sync_cache_supported = FALSE;
21404 				mutex_exit(SD_MUTEX(un));
21405 				SD_TRACE(SD_LOG_IO, un,
21406 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
21407 				    un_f_sync_cache_supported set to false \
21408 				    with asc = %x, ascq = %x\n",
21409 				    scsi_sense_asc(sense_buf),
21410 				    scsi_sense_ascq(sense_buf));
21411 				status = ENOTSUP;
21412 				goto done;
21413 			}
21414 			break;
21415 		default:
21416 			break;
21417 		}
21418 		/* FALLTHRU */
21419 	default:
21420 		/*
21421 		 * Turn on the un_f_sync_cache_required flag
21422 		 * since the SYNC CACHE command failed
21423 		 */
21424 		mutex_enter(SD_MUTEX(un));
21425 		un->un_f_sync_cache_required = TRUE;
21426 		mutex_exit(SD_MUTEX(un));
21427 
21428 		/*
21429 		 * Don't log an error message if this device
21430 		 * has removable media.
21431 		 */
21432 		if (!un->un_f_has_removable_media) {
21433 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
21434 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
21435 		}
21436 		break;
21437 	}
21438 
21439 done:
21440 	if (uip->ui_dkc.dkc_callback != NULL) {
21441 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
21442 	}
21443 
21444 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
21445 	freerbuf(bp);
21446 	kmem_free(uip, sizeof (struct sd_uscsi_info));
21447 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
21448 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
21449 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
21450 
21451 	return (status);
21452 }
21453 
21454 /*
21455  * Issues a single SCSI UNMAP command with a prepared UNMAP parameter list.
21456  * Returns zero on success, or the non-zero command error code on failure.
21457  */
21458 static int
21459 sd_send_scsi_UNMAP_issue_one(sd_ssc_t *ssc, unmap_param_hdr_t *uph,
21460     uint64_t num_descr, uint64_t bytes)
21461 {
21462 	struct sd_lun		*un = ssc->ssc_un;
21463 	struct scsi_extended_sense	sense_buf;
21464 	union scsi_cdb		cdb;
21465 	struct uscsi_cmd	ucmd_buf;
21466 	int			status;
21467 	const uint64_t		param_size = sizeof (unmap_param_hdr_t) +
21468 	    num_descr * sizeof (unmap_blk_descr_t);
21469 
21470 	ASSERT3U(param_size - 2, <=, UINT16_MAX);
21471 	uph->uph_data_len = BE_16(param_size - 2);
21472 	uph->uph_descr_data_len = BE_16(param_size - 8);
21473 
21474 	bzero(&cdb, sizeof (cdb));
21475 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21476 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21477 
21478 	cdb.scc_cmd = SCMD_UNMAP;
21479 	FORMG1COUNT(&cdb, param_size);
21480 
21481 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21482 	ucmd_buf.uscsi_cdblen	= (uchar_t)CDB_GROUP1;
21483 	ucmd_buf.uscsi_bufaddr	= (caddr_t)uph;
21484 	ucmd_buf.uscsi_buflen	= param_size;
21485 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21486 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21487 	ucmd_buf.uscsi_flags	= USCSI_WRITE | USCSI_RQENABLE | USCSI_SILENT;
21488 	ucmd_buf.uscsi_timeout	= un->un_cmd_timeout;
21489 
21490 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL, UIO_SYSSPACE,
21491 	    SD_PATH_STANDARD);
21492 
21493 	switch (status) {
21494 	case 0:
21495 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21496 
21497 		if (un->un_unmapstats) {
21498 			atomic_inc_64(&un->un_unmapstats->us_cmds.value.ui64);
21499 			atomic_add_64(&un->un_unmapstats->us_extents.value.ui64,
21500 			    num_descr);
21501 			atomic_add_64(&un->un_unmapstats->us_bytes.value.ui64,
21502 			    bytes);
21503 		}
21504 		break;	/* Success! */
21505 	case EIO:
21506 		if (un->un_unmapstats)
21507 			atomic_inc_64(&un->un_unmapstats->us_errs.value.ui64);
21508 		switch (ucmd_buf.uscsi_status) {
21509 		case STATUS_RESERVATION_CONFLICT:
21510 			status = EACCES;
21511 			break;
21512 		default:
21513 			break;
21514 		}
21515 		break;
21516 	default:
21517 		if (un->un_unmapstats)
21518 			atomic_inc_64(&un->un_unmapstats->us_errs.value.ui64);
21519 		break;
21520 	}
21521 
21522 	return (status);
21523 }
21524 
21525 /*
21526  * Returns a pointer to the i'th block descriptor inside an UNMAP param list.
21527  */
21528 static inline unmap_blk_descr_t *
21529 UNMAP_blk_descr_i(void *buf, size_t i)
21530 {
21531 	return ((unmap_blk_descr_t *)((uintptr_t)buf +
21532 	    sizeof (unmap_param_hdr_t) + (i * sizeof (unmap_blk_descr_t))));
21533 }
21534 
21535 /*
21536  * Takes the list of extents from sd_send_scsi_UNMAP, chops it up, prepares
21537  * UNMAP block descriptors and issues individual SCSI UNMAP commands. While
21538  * doing so we consult the block limits to determine at most how many
21539  * extents and LBAs we can UNMAP in one command.
21540  * If a command fails for whatever, reason, extent list processing is aborted
21541  * and the failed command's status is returned. Otherwise returns 0 on
21542  * success.
21543  */
21544 static int
21545 sd_send_scsi_UNMAP_issue(dev_t dev, sd_ssc_t *ssc, const dkioc_free_list_t *dfl)
21546 {
21547 	struct sd_lun		*un = ssc->ssc_un;
21548 	unmap_param_hdr_t	*uph;
21549 	sd_blk_limits_t		*lim = &un->un_blk_lim;
21550 	int			rval = 0;
21551 	int			partition;
21552 	/* partition offset & length in system blocks */
21553 	diskaddr_t		part_off_sysblks = 0, part_len_sysblks = 0;
21554 	uint64_t		part_off, part_len;
21555 	uint64_t		descr_cnt_lim, byte_cnt_lim;
21556 	uint64_t		descr_issued = 0, bytes_issued = 0;
21557 
21558 	uph = kmem_zalloc(SD_UNMAP_PARAM_LIST_MAXSZ, KM_SLEEP);
21559 
21560 	partition = SDPART(dev);
21561 	rval = cmlb_partinfo(un->un_cmlbhandle, partition, &part_len_sysblks,
21562 	    &part_off_sysblks, NULL, NULL, (void *)SD_PATH_DIRECT);
21563 	if (rval != 0)
21564 		goto out;
21565 	part_off = SD_SYSBLOCKS2BYTES(part_off_sysblks);
21566 	part_len = SD_SYSBLOCKS2BYTES(part_len_sysblks);
21567 
21568 	ASSERT(un->un_blk_lim.lim_max_unmap_lba_cnt != 0);
21569 	ASSERT(un->un_blk_lim.lim_max_unmap_descr_cnt != 0);
21570 	/* Spec says 0xffffffff are special values, so compute maximums. */
21571 	byte_cnt_lim = lim->lim_max_unmap_lba_cnt < UINT32_MAX ?
21572 	    (uint64_t)lim->lim_max_unmap_lba_cnt * un->un_tgt_blocksize :
21573 	    UINT64_MAX;
21574 	descr_cnt_lim = MIN(lim->lim_max_unmap_descr_cnt, SD_UNMAP_MAX_DESCR);
21575 
21576 	if (dfl->dfl_offset >= part_len) {
21577 		rval = SET_ERROR(EINVAL);
21578 		goto out;
21579 	}
21580 
21581 	for (size_t i = 0; i < dfl->dfl_num_exts; i++) {
21582 		const dkioc_free_list_ext_t *ext = &dfl->dfl_exts[i];
21583 		uint64_t ext_start = ext->dfle_start;
21584 		uint64_t ext_length = ext->dfle_length;
21585 
21586 		while (ext_length > 0) {
21587 			unmap_blk_descr_t *ubd;
21588 			/* Respect device limit on LBA count per command */
21589 			uint64_t len = MIN(MIN(ext_length, byte_cnt_lim -
21590 			    bytes_issued), SD_TGTBLOCKS2BYTES(un, UINT32_MAX));
21591 
21592 			/* check partition limits */
21593 			if (ext_start >= part_len ||
21594 			    ext_start + len < ext_start ||
21595 			    dfl->dfl_offset + ext_start + len <
21596 			    dfl->dfl_offset ||
21597 			    dfl->dfl_offset + ext_start + len > part_len) {
21598 				rval = SET_ERROR(EINVAL);
21599 				goto out;
21600 			}
21601 
21602 			ASSERT3U(descr_issued, <, descr_cnt_lim);
21603 			ASSERT3U(bytes_issued, <, byte_cnt_lim);
21604 			ubd = UNMAP_blk_descr_i(uph, descr_issued);
21605 
21606 			/* adjust in-partition addresses to be device-global */
21607 			ubd->ubd_lba = BE_64(SD_BYTES2TGTBLOCKS(un,
21608 			    dfl->dfl_offset + ext_start + part_off));
21609 			ubd->ubd_lba_cnt = BE_32(SD_BYTES2TGTBLOCKS(un, len));
21610 
21611 			descr_issued++;
21612 			bytes_issued += len;
21613 
21614 			/* Issue command when device limits reached */
21615 			if (descr_issued == descr_cnt_lim ||
21616 			    bytes_issued == byte_cnt_lim) {
21617 				rval = sd_send_scsi_UNMAP_issue_one(ssc, uph,
21618 				    descr_issued, bytes_issued);
21619 				if (rval != 0)
21620 					goto out;
21621 				descr_issued = 0;
21622 				bytes_issued = 0;
21623 			}
21624 
21625 			ext_start += len;
21626 			ext_length -= len;
21627 		}
21628 	}
21629 
21630 	if (descr_issued > 0) {
21631 		/* issue last command */
21632 		rval = sd_send_scsi_UNMAP_issue_one(ssc, uph, descr_issued,
21633 		    bytes_issued);
21634 	}
21635 
21636 out:
21637 	kmem_free(uph, SD_UNMAP_PARAM_LIST_MAXSZ);
21638 	return (rval);
21639 }
21640 
21641 /*
21642  * Issues one or several UNMAP commands based on a list of extents to be
21643  * unmapped. The internal multi-command processing is hidden, as the exact
21644  * number of commands and extents per command is limited by both SCSI
21645  * command syntax and device limits (as expressed in the SCSI Block Limits
21646  * VPD page and un_blk_lim in struct sd_lun).
21647  * Returns zero on success, or the error code of the first failed SCSI UNMAP
21648  * command.
21649  */
21650 static int
21651 sd_send_scsi_UNMAP(dev_t dev, sd_ssc_t *ssc, dkioc_free_list_t *dfl, int flag)
21652 {
21653 	struct sd_lun		*un = ssc->ssc_un;
21654 	int			rval = 0;
21655 
21656 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21657 	ASSERT(dfl != NULL);
21658 
21659 	/* Per spec, any of these conditions signals lack of UNMAP support. */
21660 	if (!(un->un_thin_flags & SD_THIN_PROV_ENABLED) ||
21661 	    un->un_blk_lim.lim_max_unmap_descr_cnt == 0 ||
21662 	    un->un_blk_lim.lim_max_unmap_lba_cnt == 0) {
21663 		return (SET_ERROR(ENOTSUP));
21664 	}
21665 
21666 	/* For userspace calls we must copy in. */
21667 	if (!(flag & FKIOCTL)) {
21668 		int err = dfl_copyin(dfl, &dfl, flag, KM_SLEEP);
21669 		if (err != 0)
21670 			return (err);
21671 	} else if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
21672 		ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
21673 		return (SET_ERROR(EINVAL));
21674 	}
21675 
21676 	rval = sd_send_scsi_UNMAP_issue(dev, ssc, dfl);
21677 
21678 	if (!(flag & FKIOCTL)) {
21679 		dfl_free(dfl);
21680 		dfl = NULL;
21681 	}
21682 
21683 	return (rval);
21684 }
21685 
21686 /*
21687  *    Function: sd_send_scsi_GET_CONFIGURATION
21688  *
21689  * Description: Issues the get configuration command to the device.
21690  *		Called from sd_check_for_writable_cd & sd_get_media_info
21691  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
21692  *   Arguments: ssc
21693  *		ucmdbuf
21694  *		rqbuf
21695  *		rqbuflen
21696  *		bufaddr
21697  *		buflen
21698  *		path_flag
21699  *
21700  * Return Code: 0   - Success
21701  *		errno return code from sd_ssc_send()
21702  *
21703  *     Context: Can sleep. Does not return until command is completed.
21704  *
21705  */
21706 
21707 static int
21708 sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21709     uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21710     int path_flag)
21711 {
21712 	char	cdb[CDB_GROUP1];
21713 	int	status;
21714 	struct sd_lun	*un;
21715 
21716 	ASSERT(ssc != NULL);
21717 	un = ssc->ssc_un;
21718 	ASSERT(un != NULL);
21719 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21720 	ASSERT(bufaddr != NULL);
21721 	ASSERT(ucmdbuf != NULL);
21722 	ASSERT(rqbuf != NULL);
21723 
21724 	SD_TRACE(SD_LOG_IO, un,
21725 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
21726 
21727 	bzero(cdb, sizeof (cdb));
21728 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21729 	bzero(rqbuf, rqbuflen);
21730 	bzero(bufaddr, buflen);
21731 
21732 	/*
21733 	 * Set up cdb field for the get configuration command.
21734 	 */
21735 	cdb[0] = SCMD_GET_CONFIGURATION;
21736 	cdb[1] = 0x02;  /* Requested Type */
21737 	cdb[8] = SD_PROFILE_HEADER_LEN;
21738 	ucmdbuf->uscsi_cdb = cdb;
21739 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21740 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21741 	ucmdbuf->uscsi_buflen = buflen;
21742 	ucmdbuf->uscsi_timeout = sd_io_time;
21743 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21744 	ucmdbuf->uscsi_rqlen = rqbuflen;
21745 	ucmdbuf->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT | USCSI_READ;
21746 
21747 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21748 	    UIO_SYSSPACE, path_flag);
21749 
21750 	switch (status) {
21751 	case 0:
21752 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21753 		break;  /* Success! */
21754 	case EIO:
21755 		switch (ucmdbuf->uscsi_status) {
21756 		case STATUS_RESERVATION_CONFLICT:
21757 			status = EACCES;
21758 			break;
21759 		default:
21760 			break;
21761 		}
21762 		break;
21763 	default:
21764 		break;
21765 	}
21766 
21767 	if (status == 0) {
21768 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21769 		    "sd_send_scsi_GET_CONFIGURATION: data",
21770 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21771 	}
21772 
21773 	SD_TRACE(SD_LOG_IO, un,
21774 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
21775 
21776 	return (status);
21777 }
21778 
21779 /*
21780  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
21781  *
21782  * Description: Issues the get configuration command to the device to
21783  *              retrieve a specific feature. Called from
21784  *		sd_check_for_writable_cd & sd_set_mmc_caps.
21785  *   Arguments: ssc
21786  *              ucmdbuf
21787  *              rqbuf
21788  *              rqbuflen
21789  *              bufaddr
21790  *              buflen
21791  *		feature
21792  *
21793  * Return Code: 0   - Success
21794  *              errno return code from sd_ssc_send()
21795  *
21796  *     Context: Can sleep. Does not return until command is completed.
21797  *
21798  */
21799 static int
21800 sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21801     uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21802     char feature, int path_flag)
21803 {
21804 	char    cdb[CDB_GROUP1];
21805 	int	status;
21806 	struct sd_lun	*un;
21807 
21808 	ASSERT(ssc != NULL);
21809 	un = ssc->ssc_un;
21810 	ASSERT(un != NULL);
21811 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21812 	ASSERT(bufaddr != NULL);
21813 	ASSERT(ucmdbuf != NULL);
21814 	ASSERT(rqbuf != NULL);
21815 
21816 	SD_TRACE(SD_LOG_IO, un,
21817 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
21818 
21819 	bzero(cdb, sizeof (cdb));
21820 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21821 	bzero(rqbuf, rqbuflen);
21822 	bzero(bufaddr, buflen);
21823 
21824 	/*
21825 	 * Set up cdb field for the get configuration command.
21826 	 */
21827 	cdb[0] = SCMD_GET_CONFIGURATION;
21828 	cdb[1] = 0x02;  /* Requested Type */
21829 	cdb[3] = feature;
21830 	cdb[8] = buflen;
21831 	ucmdbuf->uscsi_cdb = cdb;
21832 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21833 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21834 	ucmdbuf->uscsi_buflen = buflen;
21835 	ucmdbuf->uscsi_timeout = sd_io_time;
21836 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21837 	ucmdbuf->uscsi_rqlen = rqbuflen;
21838 	ucmdbuf->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT | USCSI_READ;
21839 
21840 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21841 	    UIO_SYSSPACE, path_flag);
21842 
21843 	switch (status) {
21844 	case 0:
21845 
21846 		break;  /* Success! */
21847 	case EIO:
21848 		switch (ucmdbuf->uscsi_status) {
21849 		case STATUS_RESERVATION_CONFLICT:
21850 			status = EACCES;
21851 			break;
21852 		default:
21853 			break;
21854 		}
21855 		break;
21856 	default:
21857 		break;
21858 	}
21859 
21860 	if (status == 0) {
21861 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21862 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
21863 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21864 	}
21865 
21866 	SD_TRACE(SD_LOG_IO, un,
21867 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
21868 
21869 	return (status);
21870 }
21871 
21872 
21873 /*
21874  *    Function: sd_send_scsi_MODE_SENSE
21875  *
21876  * Description: Utility function for issuing a scsi MODE SENSE command.
21877  *		Note: This routine uses a consistent implementation for Group0,
21878  *		Group1, and Group2 commands across all platforms. ATAPI devices
21879  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21880  *
21881  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21882  *                      structure for this target.
21883  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21884  *			  CDB_GROUP[1|2] (10 byte).
21885  *		bufaddr - buffer for page data retrieved from the target.
21886  *		buflen - size of page to be retrieved.
21887  *		page_code - page code of data to be retrieved from the target.
21888  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21889  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21890  *			to use the USCSI "direct" chain and bypass the normal
21891  *			command waitq.
21892  *
21893  * Return Code: 0   - Success
21894  *		errno return code from sd_ssc_send()
21895  *
21896  *     Context: Can sleep. Does not return until command is completed.
21897  */
21898 
21899 static int
21900 sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21901     size_t buflen,  uchar_t page_code, int path_flag)
21902 {
21903 	struct	scsi_extended_sense	sense_buf;
21904 	union scsi_cdb		cdb;
21905 	struct uscsi_cmd	ucmd_buf;
21906 	int			status;
21907 	int			headlen;
21908 	struct sd_lun		*un;
21909 
21910 	ASSERT(ssc != NULL);
21911 	un = ssc->ssc_un;
21912 	ASSERT(un != NULL);
21913 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21914 	ASSERT(bufaddr != NULL);
21915 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21916 	    (cdbsize == CDB_GROUP2));
21917 
21918 	SD_TRACE(SD_LOG_IO, un,
21919 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
21920 
21921 	bzero(&cdb, sizeof (cdb));
21922 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21923 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21924 	bzero(bufaddr, buflen);
21925 
21926 	if (cdbsize == CDB_GROUP0) {
21927 		cdb.scc_cmd = SCMD_MODE_SENSE;
21928 		cdb.cdb_opaque[2] = page_code;
21929 		FORMG0COUNT(&cdb, buflen);
21930 		headlen = MODE_HEADER_LENGTH;
21931 	} else {
21932 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
21933 		cdb.cdb_opaque[2] = page_code;
21934 		FORMG1COUNT(&cdb, buflen);
21935 		headlen = MODE_HEADER_LENGTH_GRP2;
21936 	}
21937 
21938 	ASSERT(headlen <= buflen);
21939 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21940 
21941 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21942 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21943 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21944 	ucmd_buf.uscsi_buflen	= buflen;
21945 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21946 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21947 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21948 	ucmd_buf.uscsi_timeout	= 60;
21949 
21950 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21951 	    UIO_SYSSPACE, path_flag);
21952 
21953 	switch (status) {
21954 	case 0:
21955 		/*
21956 		 * sr_check_wp() uses 0x3f page code and check the header of
21957 		 * mode page to determine if target device is write-protected.
21958 		 * But some USB devices return 0 bytes for 0x3f page code. For
21959 		 * this case, make sure that mode page header is returned at
21960 		 * least.
21961 		 */
21962 		if (buflen - ucmd_buf.uscsi_resid <  headlen) {
21963 			status = EIO;
21964 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
21965 			    "mode page header is not returned");
21966 		}
21967 		break;	/* Success! */
21968 	case EIO:
21969 		switch (ucmd_buf.uscsi_status) {
21970 		case STATUS_RESERVATION_CONFLICT:
21971 			status = EACCES;
21972 			break;
21973 		default:
21974 			break;
21975 		}
21976 		break;
21977 	default:
21978 		break;
21979 	}
21980 
21981 	if (status == 0) {
21982 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
21983 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21984 	}
21985 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
21986 
21987 	return (status);
21988 }
21989 
21990 
21991 /*
21992  *    Function: sd_send_scsi_MODE_SELECT
21993  *
21994  * Description: Utility function for issuing a scsi MODE SELECT command.
21995  *		Note: This routine uses a consistent implementation for Group0,
21996  *		Group1, and Group2 commands across all platforms. ATAPI devices
21997  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21998  *
21999  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22000  *                      structure for this target.
22001  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
22002  *			  CDB_GROUP[1|2] (10 byte).
22003  *		bufaddr - buffer for page data retrieved from the target.
22004  *		buflen - size of page to be retrieved.
22005  *		save_page - boolean to determin if SP bit should be set.
22006  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
22007  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
22008  *			to use the USCSI "direct" chain and bypass the normal
22009  *			command waitq.
22010  *
22011  * Return Code: 0   - Success
22012  *		errno return code from sd_ssc_send()
22013  *
22014  *     Context: Can sleep. Does not return until command is completed.
22015  */
22016 
22017 static int
22018 sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
22019     size_t buflen,  uchar_t save_page, int path_flag)
22020 {
22021 	struct	scsi_extended_sense	sense_buf;
22022 	union scsi_cdb		cdb;
22023 	struct uscsi_cmd	ucmd_buf;
22024 	int			status;
22025 	struct sd_lun		*un;
22026 
22027 	ASSERT(ssc != NULL);
22028 	un = ssc->ssc_un;
22029 	ASSERT(un != NULL);
22030 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22031 	ASSERT(bufaddr != NULL);
22032 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
22033 	    (cdbsize == CDB_GROUP2));
22034 
22035 	SD_TRACE(SD_LOG_IO, un,
22036 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
22037 
22038 	bzero(&cdb, sizeof (cdb));
22039 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22040 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
22041 
22042 	/* Set the PF bit for many third party drives */
22043 	cdb.cdb_opaque[1] = 0x10;
22044 
22045 	/* Set the savepage(SP) bit if given */
22046 	if (save_page == SD_SAVE_PAGE) {
22047 		cdb.cdb_opaque[1] |= 0x01;
22048 	}
22049 
22050 	if (cdbsize == CDB_GROUP0) {
22051 		cdb.scc_cmd = SCMD_MODE_SELECT;
22052 		FORMG0COUNT(&cdb, buflen);
22053 	} else {
22054 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
22055 		FORMG1COUNT(&cdb, buflen);
22056 	}
22057 
22058 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
22059 
22060 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22061 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
22062 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22063 	ucmd_buf.uscsi_buflen	= buflen;
22064 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
22065 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
22066 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
22067 	ucmd_buf.uscsi_timeout	= 60;
22068 
22069 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22070 	    UIO_SYSSPACE, path_flag);
22071 
22072 	switch (status) {
22073 	case 0:
22074 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22075 		break;	/* Success! */
22076 	case EIO:
22077 		switch (ucmd_buf.uscsi_status) {
22078 		case STATUS_RESERVATION_CONFLICT:
22079 			status = EACCES;
22080 			break;
22081 		default:
22082 			break;
22083 		}
22084 		break;
22085 	default:
22086 		break;
22087 	}
22088 
22089 	if (status == 0) {
22090 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
22091 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22092 	}
22093 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
22094 
22095 	return (status);
22096 }
22097 
22098 
22099 /*
22100  *    Function: sd_send_scsi_RDWR
22101  *
22102  * Description: Issue a scsi READ or WRITE command with the given parameters.
22103  *
22104  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22105  *                      structure for this target.
22106  *		cmd:	 SCMD_READ or SCMD_WRITE
22107  *		bufaddr: Address of caller's buffer to receive the RDWR data
22108  *		buflen:  Length of caller's buffer receive the RDWR data.
22109  *		start_block: Block number for the start of the RDWR operation.
22110  *			 (Assumes target-native block size.)
22111  *		residp:  Pointer to variable to receive the redisual of the
22112  *			 RDWR operation (may be NULL of no residual requested).
22113  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
22114  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
22115  *			to use the USCSI "direct" chain and bypass the normal
22116  *			command waitq.
22117  *
22118  * Return Code: 0   - Success
22119  *		errno return code from sd_ssc_send()
22120  *
22121  *     Context: Can sleep. Does not return until command is completed.
22122  */
22123 
22124 static int
22125 sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
22126     size_t buflen, daddr_t start_block, int path_flag)
22127 {
22128 	struct	scsi_extended_sense	sense_buf;
22129 	union scsi_cdb		cdb;
22130 	struct uscsi_cmd	ucmd_buf;
22131 	uint32_t		block_count;
22132 	int			status;
22133 	int			cdbsize;
22134 	uchar_t			flag;
22135 	struct sd_lun		*un;
22136 
22137 	ASSERT(ssc != NULL);
22138 	un = ssc->ssc_un;
22139 	ASSERT(un != NULL);
22140 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22141 	ASSERT(bufaddr != NULL);
22142 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
22143 
22144 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
22145 
22146 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
22147 		return (EINVAL);
22148 	}
22149 
22150 	mutex_enter(SD_MUTEX(un));
22151 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
22152 	mutex_exit(SD_MUTEX(un));
22153 
22154 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
22155 
22156 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
22157 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
22158 	    bufaddr, buflen, start_block, block_count);
22159 
22160 	bzero(&cdb, sizeof (cdb));
22161 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22162 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
22163 
22164 	/* Compute CDB size to use */
22165 	if (start_block > 0xffffffff)
22166 		cdbsize = CDB_GROUP4;
22167 	else if ((start_block & 0xFFE00000) ||
22168 	    (un->un_f_cfg_is_atapi == TRUE))
22169 		cdbsize = CDB_GROUP1;
22170 	else
22171 		cdbsize = CDB_GROUP0;
22172 
22173 	switch (cdbsize) {
22174 	case CDB_GROUP0:	/* 6-byte CDBs */
22175 		cdb.scc_cmd = cmd;
22176 		FORMG0ADDR(&cdb, start_block);
22177 		FORMG0COUNT(&cdb, block_count);
22178 		break;
22179 	case CDB_GROUP1:	/* 10-byte CDBs */
22180 		cdb.scc_cmd = cmd | SCMD_GROUP1;
22181 		FORMG1ADDR(&cdb, start_block);
22182 		FORMG1COUNT(&cdb, block_count);
22183 		break;
22184 	case CDB_GROUP4:	/* 16-byte CDBs */
22185 		cdb.scc_cmd = cmd | SCMD_GROUP4;
22186 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
22187 		FORMG4COUNT(&cdb, block_count);
22188 		break;
22189 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
22190 	default:
22191 		/* All others reserved */
22192 		return (EINVAL);
22193 	}
22194 
22195 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
22196 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
22197 
22198 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22199 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
22200 	ucmd_buf.uscsi_bufaddr	= bufaddr;
22201 	ucmd_buf.uscsi_buflen	= buflen;
22202 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
22203 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
22204 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
22205 	ucmd_buf.uscsi_timeout	= 60;
22206 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22207 	    UIO_SYSSPACE, path_flag);
22208 
22209 	switch (status) {
22210 	case 0:
22211 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22212 		break;	/* Success! */
22213 	case EIO:
22214 		switch (ucmd_buf.uscsi_status) {
22215 		case STATUS_RESERVATION_CONFLICT:
22216 			status = EACCES;
22217 			break;
22218 		default:
22219 			break;
22220 		}
22221 		break;
22222 	default:
22223 		break;
22224 	}
22225 
22226 	if (status == 0) {
22227 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
22228 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22229 	}
22230 
22231 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
22232 
22233 	return (status);
22234 }
22235 
22236 
22237 /*
22238  *    Function: sd_send_scsi_LOG_SENSE
22239  *
22240  * Description: Issue a scsi LOG_SENSE command with the given parameters.
22241  *
22242  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22243  *                      structure for this target.
22244  *
22245  * Return Code: 0   - Success
22246  *		errno return code from sd_ssc_send()
22247  *
22248  *     Context: Can sleep. Does not return until command is completed.
22249  */
22250 
22251 static int
22252 sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr, uint16_t buflen,
22253     uchar_t page_code, uchar_t page_control, uint16_t param_ptr, int path_flag)
22254 {
22255 	struct scsi_extended_sense	sense_buf;
22256 	union scsi_cdb		cdb;
22257 	struct uscsi_cmd	ucmd_buf;
22258 	int			status;
22259 	struct sd_lun		*un;
22260 
22261 	ASSERT(ssc != NULL);
22262 	un = ssc->ssc_un;
22263 	ASSERT(un != NULL);
22264 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22265 
22266 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
22267 
22268 	bzero(&cdb, sizeof (cdb));
22269 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22270 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
22271 
22272 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
22273 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
22274 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
22275 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
22276 	FORMG1COUNT(&cdb, buflen);
22277 
22278 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22279 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22280 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22281 	ucmd_buf.uscsi_buflen	= buflen;
22282 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
22283 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
22284 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
22285 	ucmd_buf.uscsi_timeout	= 60;
22286 
22287 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22288 	    UIO_SYSSPACE, path_flag);
22289 
22290 	switch (status) {
22291 	case 0:
22292 		break;
22293 	case EIO:
22294 		switch (ucmd_buf.uscsi_status) {
22295 		case STATUS_RESERVATION_CONFLICT:
22296 			status = EACCES;
22297 			break;
22298 		case STATUS_CHECK:
22299 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
22300 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
22301 			    KEY_ILLEGAL_REQUEST) &&
22302 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
22303 				/*
22304 				 * ASC 0x24: INVALID FIELD IN CDB
22305 				 */
22306 				switch (page_code) {
22307 				case START_STOP_CYCLE_PAGE:
22308 					/*
22309 					 * The start stop cycle counter is
22310 					 * implemented as page 0x31 in earlier
22311 					 * generation disks. In new generation
22312 					 * disks the start stop cycle counter is
22313 					 * implemented as page 0xE. To properly
22314 					 * handle this case if an attempt for
22315 					 * log page 0xE is made and fails we
22316 					 * will try again using page 0x31.
22317 					 *
22318 					 * Network storage BU committed to
22319 					 * maintain the page 0x31 for this
22320 					 * purpose and will not have any other
22321 					 * page implemented with page code 0x31
22322 					 * until all disks transition to the
22323 					 * standard page.
22324 					 */
22325 					mutex_enter(SD_MUTEX(un));
22326 					un->un_start_stop_cycle_page =
22327 					    START_STOP_CYCLE_VU_PAGE;
22328 					cdb.cdb_opaque[2] =
22329 					    (char)(page_control << 6) |
22330 					    un->un_start_stop_cycle_page;
22331 					mutex_exit(SD_MUTEX(un));
22332 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22333 					status = sd_ssc_send(
22334 					    ssc, &ucmd_buf, FKIOCTL,
22335 					    UIO_SYSSPACE, path_flag);
22336 
22337 					break;
22338 				case TEMPERATURE_PAGE:
22339 					status = ENOTTY;
22340 					break;
22341 				default:
22342 					break;
22343 				}
22344 			}
22345 			break;
22346 		default:
22347 			break;
22348 		}
22349 		break;
22350 	default:
22351 		break;
22352 	}
22353 
22354 	if (status == 0) {
22355 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22356 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
22357 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22358 	}
22359 
22360 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
22361 
22362 	return (status);
22363 }
22364 
22365 
22366 /*
22367  *    Function: sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
22368  *
22369  * Description: Issue the scsi GET EVENT STATUS NOTIFICATION command.
22370  *
22371  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22372  *                      structure for this target.
22373  *		bufaddr
22374  *		buflen
22375  *		class_req
22376  *
22377  * Return Code: 0   - Success
22378  *		errno return code from sd_ssc_send()
22379  *
22380  *     Context: Can sleep. Does not return until command is completed.
22381  */
22382 
22383 static int
22384 sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc, uchar_t *bufaddr,
22385     size_t buflen, uchar_t class_req)
22386 {
22387 	union scsi_cdb		cdb;
22388 	struct uscsi_cmd	ucmd_buf;
22389 	int			status;
22390 	struct sd_lun		*un;
22391 
22392 	ASSERT(ssc != NULL);
22393 	un = ssc->ssc_un;
22394 	ASSERT(un != NULL);
22395 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22396 	ASSERT(bufaddr != NULL);
22397 
22398 	SD_TRACE(SD_LOG_IO, un,
22399 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: entry: un:0x%p\n", un);
22400 
22401 	bzero(&cdb, sizeof (cdb));
22402 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22403 	bzero(bufaddr, buflen);
22404 
22405 	cdb.scc_cmd = SCMD_GET_EVENT_STATUS_NOTIFICATION;
22406 	cdb.cdb_opaque[1] = 1; /* polled */
22407 	cdb.cdb_opaque[4] = class_req;
22408 	FORMG1COUNT(&cdb, buflen);
22409 
22410 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22411 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22412 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22413 	ucmd_buf.uscsi_buflen	= buflen;
22414 	ucmd_buf.uscsi_rqbuf	= NULL;
22415 	ucmd_buf.uscsi_rqlen	= 0;
22416 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
22417 	ucmd_buf.uscsi_timeout	= 60;
22418 
22419 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22420 	    UIO_SYSSPACE, SD_PATH_DIRECT);
22421 
22422 	/*
22423 	 * Only handle status == 0, the upper-level caller
22424 	 * will put different assessment based on the context.
22425 	 */
22426 	if (status == 0) {
22427 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22428 
22429 		if (ucmd_buf.uscsi_resid != 0) {
22430 			status = EIO;
22431 		}
22432 	}
22433 
22434 	SD_TRACE(SD_LOG_IO, un,
22435 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: exit\n");
22436 
22437 	return (status);
22438 }
22439 
22440 
22441 static boolean_t
22442 sd_gesn_media_data_valid(uchar_t *data)
22443 {
22444 	uint16_t			len;
22445 
22446 	len = (data[1] << 8) | data[0];
22447 	return ((len >= 6) &&
22448 	    ((data[2] & SD_GESN_HEADER_NEA) == 0) &&
22449 	    ((data[2] & SD_GESN_HEADER_CLASS) == SD_GESN_MEDIA_CLASS) &&
22450 	    ((data[3] & (1 << SD_GESN_MEDIA_CLASS)) != 0));
22451 }
22452 
22453 
22454 /*
22455  *    Function: sdioctl
22456  *
22457  * Description: Driver's ioctl(9e) entry point function.
22458  *
22459  *   Arguments: dev     - device number
22460  *		cmd     - ioctl operation to be performed
22461  *		arg     - user argument, contains data to be set or reference
22462  *			  parameter for get
22463  *		flag    - bit flag, indicating open settings, 32/64 bit type
22464  *		cred_p  - user credential pointer
22465  *		rval_p  - calling process return value (OPT)
22466  *
22467  * Return Code: EINVAL
22468  *		ENOTTY
22469  *		ENXIO
22470  *		EIO
22471  *		EFAULT
22472  *		ENOTSUP
22473  *		EPERM
22474  *
22475  *     Context: Called from the device switch at normal priority.
22476  */
22477 
22478 static int
22479 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
22480 {
22481 	struct sd_lun	*un = NULL;
22482 	int		err = 0;
22483 	int		i = 0;
22484 	cred_t		*cr;
22485 	int		tmprval = EINVAL;
22486 	boolean_t	is_valid;
22487 	sd_ssc_t	*ssc;
22488 
22489 	/*
22490 	 * All device accesses go thru sdstrategy where we check on suspend
22491 	 * status
22492 	 */
22493 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22494 		return (ENXIO);
22495 	}
22496 
22497 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22498 
22499 	/* Initialize sd_ssc_t for internal uscsi commands */
22500 	ssc = sd_ssc_init(un);
22501 
22502 	is_valid = SD_IS_VALID_LABEL(un);
22503 
22504 	/*
22505 	 * Moved this wait from sd_uscsi_strategy to here for
22506 	 * reasons of deadlock prevention. Internal driver commands,
22507 	 * specifically those to change a devices power level, result
22508 	 * in a call to sd_uscsi_strategy.
22509 	 */
22510 	mutex_enter(SD_MUTEX(un));
22511 	while ((un->un_state == SD_STATE_SUSPENDED) ||
22512 	    (un->un_state == SD_STATE_PM_CHANGING)) {
22513 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
22514 	}
22515 	/*
22516 	 * Twiddling the counter here protects commands from now
22517 	 * through to the top of sd_uscsi_strategy. Without the
22518 	 * counter inc. a power down, for example, could get in
22519 	 * after the above check for state is made and before
22520 	 * execution gets to the top of sd_uscsi_strategy.
22521 	 * That would cause problems.
22522 	 */
22523 	un->un_ncmds_in_driver++;
22524 
22525 	if (!is_valid &&
22526 	    (flag & (FNDELAY | FNONBLOCK))) {
22527 		switch (cmd) {
22528 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
22529 		case DKIOCGVTOC:
22530 		case DKIOCGEXTVTOC:
22531 		case DKIOCGAPART:
22532 		case DKIOCPARTINFO:
22533 		case DKIOCEXTPARTINFO:
22534 		case DKIOCSGEOM:
22535 		case DKIOCSAPART:
22536 		case DKIOCGETEFI:
22537 		case DKIOCPARTITION:
22538 		case DKIOCSVTOC:
22539 		case DKIOCSEXTVTOC:
22540 		case DKIOCSETEFI:
22541 		case DKIOCGMBOOT:
22542 		case DKIOCSMBOOT:
22543 		case DKIOCG_PHYGEOM:
22544 		case DKIOCG_VIRTGEOM:
22545 #if defined(__x86)
22546 		case DKIOCSETEXTPART:
22547 #endif
22548 			/* let cmlb handle it */
22549 			goto skip_ready_valid;
22550 
22551 		case CDROMPAUSE:
22552 		case CDROMRESUME:
22553 		case CDROMPLAYMSF:
22554 		case CDROMPLAYTRKIND:
22555 		case CDROMREADTOCHDR:
22556 		case CDROMREADTOCENTRY:
22557 		case CDROMSTOP:
22558 		case CDROMSTART:
22559 		case CDROMVOLCTRL:
22560 		case CDROMSUBCHNL:
22561 		case CDROMREADMODE2:
22562 		case CDROMREADMODE1:
22563 		case CDROMREADOFFSET:
22564 		case CDROMSBLKMODE:
22565 		case CDROMGBLKMODE:
22566 		case CDROMGDRVSPEED:
22567 		case CDROMSDRVSPEED:
22568 		case CDROMCDDA:
22569 		case CDROMCDXA:
22570 		case CDROMSUBCODE:
22571 			if (!ISCD(un)) {
22572 				un->un_ncmds_in_driver--;
22573 				ASSERT(un->un_ncmds_in_driver >= 0);
22574 				mutex_exit(SD_MUTEX(un));
22575 				err = ENOTTY;
22576 				goto done_without_assess;
22577 			}
22578 			break;
22579 		case FDEJECT:
22580 		case DKIOCEJECT:
22581 		case CDROMEJECT:
22582 			if (!un->un_f_eject_media_supported) {
22583 				un->un_ncmds_in_driver--;
22584 				ASSERT(un->un_ncmds_in_driver >= 0);
22585 				mutex_exit(SD_MUTEX(un));
22586 				err = ENOTTY;
22587 				goto done_without_assess;
22588 			}
22589 			break;
22590 		case DKIOCFLUSHWRITECACHE:
22591 			mutex_exit(SD_MUTEX(un));
22592 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22593 			if (err != 0) {
22594 				mutex_enter(SD_MUTEX(un));
22595 				un->un_ncmds_in_driver--;
22596 				ASSERT(un->un_ncmds_in_driver >= 0);
22597 				mutex_exit(SD_MUTEX(un));
22598 				err = EIO;
22599 				goto done_quick_assess;
22600 			}
22601 			mutex_enter(SD_MUTEX(un));
22602 			/* FALLTHROUGH */
22603 		case DKIOCREMOVABLE:
22604 		case DKIOCHOTPLUGGABLE:
22605 		case DKIOCINFO:
22606 		case DKIOCGMEDIAINFO:
22607 		case DKIOCGMEDIAINFOEXT:
22608 		case DKIOCSOLIDSTATE:
22609 		case DKIOC_CANFREE:
22610 		case MHIOCENFAILFAST:
22611 		case MHIOCSTATUS:
22612 		case MHIOCTKOWN:
22613 		case MHIOCRELEASE:
22614 		case MHIOCGRP_INKEYS:
22615 		case MHIOCGRP_INRESV:
22616 		case MHIOCGRP_REGISTER:
22617 		case MHIOCGRP_CLEAR:
22618 		case MHIOCGRP_RESERVE:
22619 		case MHIOCGRP_PREEMPTANDABORT:
22620 		case MHIOCGRP_REGISTERANDIGNOREKEY:
22621 		case CDROMCLOSETRAY:
22622 		case USCSICMD:
22623 		case USCSIMAXXFER:
22624 			goto skip_ready_valid;
22625 		default:
22626 			break;
22627 		}
22628 
22629 		mutex_exit(SD_MUTEX(un));
22630 		err = sd_ready_and_valid(ssc, SDPART(dev));
22631 		mutex_enter(SD_MUTEX(un));
22632 
22633 		if (err != SD_READY_VALID) {
22634 			switch (cmd) {
22635 			case DKIOCSTATE:
22636 			case CDROMGDRVSPEED:
22637 			case CDROMSDRVSPEED:
22638 			case FDEJECT:	/* for eject command */
22639 			case DKIOCEJECT:
22640 			case CDROMEJECT:
22641 			case DKIOCREMOVABLE:
22642 			case DKIOCHOTPLUGGABLE:
22643 				break;
22644 			default:
22645 				if (un->un_f_has_removable_media) {
22646 					err = ENXIO;
22647 				} else {
22648 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
22649 					if (err == SD_RESERVED_BY_OTHERS) {
22650 						err = EACCES;
22651 					} else {
22652 						err = EIO;
22653 					}
22654 				}
22655 				un->un_ncmds_in_driver--;
22656 				ASSERT(un->un_ncmds_in_driver >= 0);
22657 				mutex_exit(SD_MUTEX(un));
22658 
22659 				goto done_without_assess;
22660 			}
22661 		}
22662 	}
22663 
22664 skip_ready_valid:
22665 	mutex_exit(SD_MUTEX(un));
22666 
22667 	switch (cmd) {
22668 	case DKIOCINFO:
22669 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
22670 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
22671 		break;
22672 
22673 	case DKIOCGMEDIAINFO:
22674 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
22675 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
22676 		break;
22677 
22678 	case DKIOCGMEDIAINFOEXT:
22679 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFOEXT\n");
22680 		err = sd_get_media_info_ext(dev, (caddr_t)arg, flag);
22681 		break;
22682 
22683 	case DKIOCGGEOM:
22684 	case DKIOCGVTOC:
22685 	case DKIOCGEXTVTOC:
22686 	case DKIOCGAPART:
22687 	case DKIOCPARTINFO:
22688 	case DKIOCEXTPARTINFO:
22689 	case DKIOCSGEOM:
22690 	case DKIOCSAPART:
22691 	case DKIOCGETEFI:
22692 	case DKIOCPARTITION:
22693 	case DKIOCSVTOC:
22694 	case DKIOCSEXTVTOC:
22695 	case DKIOCSETEFI:
22696 	case DKIOCGMBOOT:
22697 	case DKIOCSMBOOT:
22698 	case DKIOCG_PHYGEOM:
22699 	case DKIOCG_VIRTGEOM:
22700 #if defined(__x86)
22701 	case DKIOCSETEXTPART:
22702 #endif
22703 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
22704 
22705 		/* TUR should spin up */
22706 
22707 		if (un->un_f_has_removable_media)
22708 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
22709 			    SD_CHECK_FOR_MEDIA);
22710 
22711 		else
22712 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22713 
22714 		if (err != 0)
22715 			goto done_with_assess;
22716 
22717 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
22718 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
22719 
22720 		if ((err == 0) &&
22721 		    ((cmd == DKIOCSETEFI) ||
22722 		    ((un->un_f_pkstats_enabled) &&
22723 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
22724 		    cmd == DKIOCSEXTVTOC)))) {
22725 
22726 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
22727 			    (void *)SD_PATH_DIRECT);
22728 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
22729 				sd_set_pstats(un);
22730 				SD_TRACE(SD_LOG_IO_PARTITION, un,
22731 				    "sd_ioctl: un:0x%p pstats created and "
22732 				    "set\n", un);
22733 			}
22734 		}
22735 
22736 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
22737 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
22738 
22739 			mutex_enter(SD_MUTEX(un));
22740 			if (un->un_f_devid_supported &&
22741 			    (un->un_f_opt_fab_devid == TRUE)) {
22742 				if (un->un_devid == NULL) {
22743 					sd_register_devid(ssc, SD_DEVINFO(un),
22744 					    SD_TARGET_IS_UNRESERVED);
22745 				} else {
22746 					/*
22747 					 * The device id for this disk
22748 					 * has been fabricated. The
22749 					 * device id must be preserved
22750 					 * by writing it back out to
22751 					 * disk.
22752 					 */
22753 					if (sd_write_deviceid(ssc) != 0) {
22754 						ddi_devid_free(un->un_devid);
22755 						un->un_devid = NULL;
22756 					}
22757 				}
22758 			}
22759 			mutex_exit(SD_MUTEX(un));
22760 		}
22761 
22762 		break;
22763 
22764 	case DKIOCLOCK:
22765 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
22766 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22767 		    SD_PATH_STANDARD);
22768 		goto done_with_assess;
22769 
22770 	case DKIOCUNLOCK:
22771 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
22772 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
22773 		    SD_PATH_STANDARD);
22774 		goto done_with_assess;
22775 
22776 	case DKIOCSTATE: {
22777 		enum dkio_state		state;
22778 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
22779 
22780 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
22781 			err = EFAULT;
22782 		} else {
22783 			err = sd_check_media(dev, state);
22784 			if (err == 0) {
22785 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
22786 				    sizeof (int), flag) != 0)
22787 					err = EFAULT;
22788 			}
22789 		}
22790 		break;
22791 	}
22792 
22793 	case DKIOCREMOVABLE:
22794 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
22795 		i = un->un_f_has_removable_media ? 1 : 0;
22796 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22797 			err = EFAULT;
22798 		} else {
22799 			err = 0;
22800 		}
22801 		break;
22802 
22803 	case DKIOCSOLIDSTATE:
22804 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSOLIDSTATE\n");
22805 		i = un->un_f_is_solid_state ? 1 : 0;
22806 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22807 			err = EFAULT;
22808 		} else {
22809 			err = 0;
22810 		}
22811 		break;
22812 
22813 	case DKIOCHOTPLUGGABLE:
22814 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
22815 		i = un->un_f_is_hotpluggable ? 1 : 0;
22816 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22817 			err = EFAULT;
22818 		} else {
22819 			err = 0;
22820 		}
22821 		break;
22822 
22823 	case DKIOCREADONLY:
22824 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREADONLY\n");
22825 		i = 0;
22826 		if ((ISCD(un) && !un->un_f_mmc_writable_media) ||
22827 		    (sr_check_wp(dev) != 0)) {
22828 			i = 1;
22829 		}
22830 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22831 			err = EFAULT;
22832 		} else {
22833 			err = 0;
22834 		}
22835 		break;
22836 
22837 	case DKIOCGTEMPERATURE:
22838 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
22839 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
22840 		break;
22841 
22842 	case MHIOCENFAILFAST:
22843 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
22844 		if ((err = drv_priv(cred_p)) == 0) {
22845 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
22846 		}
22847 		break;
22848 
22849 	case MHIOCTKOWN:
22850 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
22851 		if ((err = drv_priv(cred_p)) == 0) {
22852 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
22853 		}
22854 		break;
22855 
22856 	case MHIOCRELEASE:
22857 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
22858 		if ((err = drv_priv(cred_p)) == 0) {
22859 			err = sd_mhdioc_release(dev);
22860 		}
22861 		break;
22862 
22863 	case MHIOCSTATUS:
22864 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
22865 		if ((err = drv_priv(cred_p)) == 0) {
22866 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
22867 			case 0:
22868 				err = 0;
22869 				break;
22870 			case EACCES:
22871 				*rval_p = 1;
22872 				err = 0;
22873 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22874 				break;
22875 			default:
22876 				err = EIO;
22877 				goto done_with_assess;
22878 			}
22879 		}
22880 		break;
22881 
22882 	case MHIOCQRESERVE:
22883 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
22884 		if ((err = drv_priv(cred_p)) == 0) {
22885 			err = sd_reserve_release(dev, SD_RESERVE);
22886 		}
22887 		break;
22888 
22889 	case MHIOCREREGISTERDEVID:
22890 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
22891 		if (drv_priv(cred_p) == EPERM) {
22892 			err = EPERM;
22893 		} else if (!un->un_f_devid_supported) {
22894 			err = ENOTTY;
22895 		} else {
22896 			err = sd_mhdioc_register_devid(dev);
22897 		}
22898 		break;
22899 
22900 	case MHIOCGRP_INKEYS:
22901 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
22902 		if (((err = drv_priv(cred_p)) != EPERM) &&
22903 		    arg != (intptr_t)NULL) {
22904 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22905 				err = ENOTSUP;
22906 			} else {
22907 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
22908 				    flag);
22909 			}
22910 		}
22911 		break;
22912 
22913 	case MHIOCGRP_INRESV:
22914 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
22915 		if (((err = drv_priv(cred_p)) != EPERM) &&
22916 		    arg != (intptr_t)NULL) {
22917 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22918 				err = ENOTSUP;
22919 			} else {
22920 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
22921 			}
22922 		}
22923 		break;
22924 
22925 	case MHIOCGRP_REGISTER:
22926 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
22927 		if ((err = drv_priv(cred_p)) != EPERM) {
22928 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22929 				err = ENOTSUP;
22930 			} else if (arg != (intptr_t)NULL) {
22931 				mhioc_register_t reg;
22932 				if (ddi_copyin((void *)arg, &reg,
22933 				    sizeof (mhioc_register_t), flag) != 0) {
22934 					err = EFAULT;
22935 				} else {
22936 					err =
22937 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22938 					    ssc, SD_SCSI3_REGISTER,
22939 					    (uchar_t *)&reg);
22940 					if (err != 0)
22941 						goto done_with_assess;
22942 				}
22943 			}
22944 		}
22945 		break;
22946 
22947 	case MHIOCGRP_CLEAR:
22948 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_CLEAR\n");
22949 		if ((err = drv_priv(cred_p)) != EPERM) {
22950 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22951 				err = ENOTSUP;
22952 			} else if (arg != (intptr_t)NULL) {
22953 				mhioc_register_t reg;
22954 				if (ddi_copyin((void *)arg, &reg,
22955 				    sizeof (mhioc_register_t), flag) != 0) {
22956 					err = EFAULT;
22957 				} else {
22958 					err =
22959 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22960 					    ssc, SD_SCSI3_CLEAR,
22961 					    (uchar_t *)&reg);
22962 					if (err != 0)
22963 						goto done_with_assess;
22964 				}
22965 			}
22966 		}
22967 		break;
22968 
22969 	case MHIOCGRP_RESERVE:
22970 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
22971 		if ((err = drv_priv(cred_p)) != EPERM) {
22972 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22973 				err = ENOTSUP;
22974 			} else if (arg != (intptr_t)NULL) {
22975 				mhioc_resv_desc_t resv_desc;
22976 				if (ddi_copyin((void *)arg, &resv_desc,
22977 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
22978 					err = EFAULT;
22979 				} else {
22980 					err =
22981 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22982 					    ssc, SD_SCSI3_RESERVE,
22983 					    (uchar_t *)&resv_desc);
22984 					if (err != 0)
22985 						goto done_with_assess;
22986 				}
22987 			}
22988 		}
22989 		break;
22990 
22991 	case MHIOCGRP_PREEMPTANDABORT:
22992 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
22993 		if ((err = drv_priv(cred_p)) != EPERM) {
22994 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22995 				err = ENOTSUP;
22996 			} else if (arg != (intptr_t)NULL) {
22997 				mhioc_preemptandabort_t preempt_abort;
22998 				if (ddi_copyin((void *)arg, &preempt_abort,
22999 				    sizeof (mhioc_preemptandabort_t),
23000 				    flag) != 0) {
23001 					err = EFAULT;
23002 				} else {
23003 					err =
23004 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
23005 					    ssc, SD_SCSI3_PREEMPTANDABORT,
23006 					    (uchar_t *)&preempt_abort);
23007 					if (err != 0)
23008 						goto done_with_assess;
23009 				}
23010 			}
23011 		}
23012 		break;
23013 
23014 	case MHIOCGRP_REGISTERANDIGNOREKEY:
23015 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
23016 		if ((err = drv_priv(cred_p)) != EPERM) {
23017 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
23018 				err = ENOTSUP;
23019 			} else if (arg != (intptr_t)NULL) {
23020 				mhioc_registerandignorekey_t r_and_i;
23021 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
23022 				    sizeof (mhioc_registerandignorekey_t),
23023 				    flag) != 0) {
23024 					err = EFAULT;
23025 				} else {
23026 					err =
23027 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
23028 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
23029 					    (uchar_t *)&r_and_i);
23030 					if (err != 0)
23031 						goto done_with_assess;
23032 				}
23033 			}
23034 		}
23035 		break;
23036 
23037 	case USCSICMD:
23038 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
23039 		cr = ddi_get_cred();
23040 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
23041 			err = EPERM;
23042 		} else {
23043 			enum uio_seg	uioseg;
23044 
23045 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
23046 			    UIO_USERSPACE;
23047 			if (un->un_f_format_in_progress == TRUE) {
23048 				err = EAGAIN;
23049 				break;
23050 			}
23051 
23052 			err = sd_ssc_send(ssc,
23053 			    (struct uscsi_cmd *)arg,
23054 			    flag, uioseg, SD_PATH_STANDARD);
23055 			if (err != 0)
23056 				goto done_with_assess;
23057 			else
23058 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
23059 		}
23060 		break;
23061 
23062 	case USCSIMAXXFER:
23063 		SD_TRACE(SD_LOG_IOCTL, un, "USCSIMAXXFER\n");
23064 		cr = ddi_get_cred();
23065 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
23066 			err = EPERM;
23067 		} else {
23068 			const uscsi_xfer_t xfer = un->un_max_xfer_size;
23069 
23070 			if (ddi_copyout(&xfer, (void *)arg, sizeof (xfer),
23071 			    flag) != 0) {
23072 				err = EFAULT;
23073 			} else {
23074 				err = 0;
23075 			}
23076 		}
23077 		break;
23078 
23079 	case CDROMPAUSE:
23080 	case CDROMRESUME:
23081 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
23082 		if (!ISCD(un)) {
23083 			err = ENOTTY;
23084 		} else {
23085 			err = sr_pause_resume(dev, cmd);
23086 		}
23087 		break;
23088 
23089 	case CDROMPLAYMSF:
23090 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
23091 		if (!ISCD(un)) {
23092 			err = ENOTTY;
23093 		} else {
23094 			err = sr_play_msf(dev, (caddr_t)arg, flag);
23095 		}
23096 		break;
23097 
23098 	case CDROMPLAYTRKIND:
23099 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
23100 #if defined(__x86)
23101 		/*
23102 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
23103 		 */
23104 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
23105 #else
23106 		if (!ISCD(un)) {
23107 #endif
23108 			err = ENOTTY;
23109 		} else {
23110 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
23111 		}
23112 		break;
23113 
23114 	case CDROMREADTOCHDR:
23115 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
23116 		if (!ISCD(un)) {
23117 			err = ENOTTY;
23118 		} else {
23119 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
23120 		}
23121 		break;
23122 
23123 	case CDROMREADTOCENTRY:
23124 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
23125 		if (!ISCD(un)) {
23126 			err = ENOTTY;
23127 		} else {
23128 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
23129 		}
23130 		break;
23131 
23132 	case CDROMSTOP:
23133 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
23134 		if (!ISCD(un)) {
23135 			err = ENOTTY;
23136 		} else {
23137 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
23138 			    SD_TARGET_STOP, SD_PATH_STANDARD);
23139 			goto done_with_assess;
23140 		}
23141 		break;
23142 
23143 	case CDROMSTART:
23144 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
23145 		if (!ISCD(un)) {
23146 			err = ENOTTY;
23147 		} else {
23148 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
23149 			    SD_TARGET_START, SD_PATH_STANDARD);
23150 			goto done_with_assess;
23151 		}
23152 		break;
23153 
23154 	case CDROMCLOSETRAY:
23155 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
23156 		if (!ISCD(un)) {
23157 			err = ENOTTY;
23158 		} else {
23159 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
23160 			    SD_TARGET_CLOSE, SD_PATH_STANDARD);
23161 			goto done_with_assess;
23162 		}
23163 		break;
23164 
23165 	case FDEJECT:	/* for eject command */
23166 	case DKIOCEJECT:
23167 	case CDROMEJECT:
23168 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
23169 		if (!un->un_f_eject_media_supported) {
23170 			err = ENOTTY;
23171 		} else {
23172 			err = sr_eject(dev);
23173 		}
23174 		break;
23175 
23176 	case CDROMVOLCTRL:
23177 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
23178 		if (!ISCD(un)) {
23179 			err = ENOTTY;
23180 		} else {
23181 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
23182 		}
23183 		break;
23184 
23185 	case CDROMSUBCHNL:
23186 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
23187 		if (!ISCD(un)) {
23188 			err = ENOTTY;
23189 		} else {
23190 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
23191 		}
23192 		break;
23193 
23194 	case CDROMREADMODE2:
23195 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
23196 		if (!ISCD(un)) {
23197 			err = ENOTTY;
23198 		} else if (un->un_f_cfg_is_atapi == TRUE) {
23199 			/*
23200 			 * If the drive supports READ CD, use that instead of
23201 			 * switching the LBA size via a MODE SELECT
23202 			 * Block Descriptor
23203 			 */
23204 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
23205 		} else {
23206 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
23207 		}
23208 		break;
23209 
23210 	case CDROMREADMODE1:
23211 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
23212 		if (!ISCD(un)) {
23213 			err = ENOTTY;
23214 		} else {
23215 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
23216 		}
23217 		break;
23218 
23219 	case CDROMREADOFFSET:
23220 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
23221 		if (!ISCD(un)) {
23222 			err = ENOTTY;
23223 		} else {
23224 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
23225 			    flag);
23226 		}
23227 		break;
23228 
23229 	case CDROMSBLKMODE:
23230 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
23231 		/*
23232 		 * There is no means of changing block size in case of atapi
23233 		 * drives, thus return ENOTTY if drive type is atapi
23234 		 */
23235 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
23236 			err = ENOTTY;
23237 		} else if (un->un_f_mmc_cap == TRUE) {
23238 
23239 			/*
23240 			 * MMC Devices do not support changing the
23241 			 * logical block size
23242 			 *
23243 			 * Note: EINVAL is being returned instead of ENOTTY to
23244 			 * maintain consistancy with the original mmc
23245 			 * driver update.
23246 			 */
23247 			err = EINVAL;
23248 		} else {
23249 			mutex_enter(SD_MUTEX(un));
23250 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
23251 			    (un->un_ncmds_in_transport > 0)) {
23252 				mutex_exit(SD_MUTEX(un));
23253 				err = EINVAL;
23254 			} else {
23255 				mutex_exit(SD_MUTEX(un));
23256 				err = sr_change_blkmode(dev, cmd, arg, flag);
23257 			}
23258 		}
23259 		break;
23260 
23261 	case CDROMGBLKMODE:
23262 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
23263 		if (!ISCD(un)) {
23264 			err = ENOTTY;
23265 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
23266 		    (un->un_f_blockcount_is_valid != FALSE)) {
23267 			/*
23268 			 * Drive is an ATAPI drive so return target block
23269 			 * size for ATAPI drives since we cannot change the
23270 			 * blocksize on ATAPI drives. Used primarily to detect
23271 			 * if an ATAPI cdrom is present.
23272 			 */
23273 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
23274 			    sizeof (int), flag) != 0) {
23275 				err = EFAULT;
23276 			} else {
23277 				err = 0;
23278 			}
23279 
23280 		} else {
23281 			/*
23282 			 * Drive supports changing block sizes via a Mode
23283 			 * Select.
23284 			 */
23285 			err = sr_change_blkmode(dev, cmd, arg, flag);
23286 		}
23287 		break;
23288 
23289 	case CDROMGDRVSPEED:
23290 	case CDROMSDRVSPEED:
23291 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
23292 		if (!ISCD(un)) {
23293 			err = ENOTTY;
23294 		} else if (un->un_f_mmc_cap == TRUE) {
23295 			/*
23296 			 * Note: In the future the driver implementation
23297 			 * for getting and
23298 			 * setting cd speed should entail:
23299 			 * 1) If non-mmc try the Toshiba mode page
23300 			 *    (sr_change_speed)
23301 			 * 2) If mmc but no support for Real Time Streaming try
23302 			 *    the SET CD SPEED (0xBB) command
23303 			 *   (sr_atapi_change_speed)
23304 			 * 3) If mmc and support for Real Time Streaming
23305 			 *    try the GET PERFORMANCE and SET STREAMING
23306 			 *    commands (not yet implemented, 4380808)
23307 			 */
23308 			/*
23309 			 * As per recent MMC spec, CD-ROM speed is variable
23310 			 * and changes with LBA. Since there is no such
23311 			 * things as drive speed now, fail this ioctl.
23312 			 *
23313 			 * Note: EINVAL is returned for consistancy of original
23314 			 * implementation which included support for getting
23315 			 * the drive speed of mmc devices but not setting
23316 			 * the drive speed. Thus EINVAL would be returned
23317 			 * if a set request was made for an mmc device.
23318 			 * We no longer support get or set speed for
23319 			 * mmc but need to remain consistent with regard
23320 			 * to the error code returned.
23321 			 */
23322 			err = EINVAL;
23323 		} else if (un->un_f_cfg_is_atapi == TRUE) {
23324 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
23325 		} else {
23326 			err = sr_change_speed(dev, cmd, arg, flag);
23327 		}
23328 		break;
23329 
23330 	case CDROMCDDA:
23331 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
23332 		if (!ISCD(un)) {
23333 			err = ENOTTY;
23334 		} else {
23335 			err = sr_read_cdda(dev, (void *)arg, flag);
23336 		}
23337 		break;
23338 
23339 	case CDROMCDXA:
23340 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
23341 		if (!ISCD(un)) {
23342 			err = ENOTTY;
23343 		} else {
23344 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
23345 		}
23346 		break;
23347 
23348 	case CDROMSUBCODE:
23349 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
23350 		if (!ISCD(un)) {
23351 			err = ENOTTY;
23352 		} else {
23353 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
23354 		}
23355 		break;
23356 
23357 
23358 #ifdef SDDEBUG
23359 /* RESET/ABORTS testing ioctls */
23360 	case DKIOCRESET: {
23361 		int	reset_level;
23362 
23363 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
23364 			err = EFAULT;
23365 		} else {
23366 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
23367 			    "reset_level = 0x%lx\n", reset_level);
23368 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
23369 				err = 0;
23370 			} else {
23371 				err = EIO;
23372 			}
23373 		}
23374 		break;
23375 	}
23376 
23377 	case DKIOCABORT:
23378 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
23379 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
23380 			err = 0;
23381 		} else {
23382 			err = EIO;
23383 		}
23384 		break;
23385 #endif
23386 
23387 #ifdef SD_FAULT_INJECTION
23388 /* SDIOC FaultInjection testing ioctls */
23389 	case SDIOCSTART:
23390 	case SDIOCSTOP:
23391 	case SDIOCINSERTPKT:
23392 	case SDIOCINSERTXB:
23393 	case SDIOCINSERTUN:
23394 	case SDIOCINSERTARQ:
23395 	case SDIOCPUSH:
23396 	case SDIOCRETRIEVE:
23397 	case SDIOCRUN:
23398 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
23399 		    "SDIOC detected cmd:0x%X:\n", cmd);
23400 		/* call error generator */
23401 		sd_faultinjection_ioctl(cmd, arg, un);
23402 		err = 0;
23403 		break;
23404 
23405 #endif /* SD_FAULT_INJECTION */
23406 
23407 	case DKIOCFLUSHWRITECACHE:
23408 		{
23409 			struct dk_callback *dkc = (struct dk_callback *)arg;
23410 
23411 			mutex_enter(SD_MUTEX(un));
23412 			if (!un->un_f_sync_cache_supported ||
23413 			    !un->un_f_write_cache_enabled) {
23414 				err = un->un_f_sync_cache_supported ?
23415 				    0 : ENOTSUP;
23416 				mutex_exit(SD_MUTEX(un));
23417 				if ((flag & FKIOCTL) && dkc != NULL &&
23418 				    dkc->dkc_callback != NULL) {
23419 					(*dkc->dkc_callback)(dkc->dkc_cookie,
23420 					    err);
23421 					/*
23422 					 * Did callback and reported error.
23423 					 * Since we did a callback, ioctl
23424 					 * should return 0.
23425 					 */
23426 					err = 0;
23427 				}
23428 				break;
23429 			}
23430 			mutex_exit(SD_MUTEX(un));
23431 
23432 			if ((flag & FKIOCTL) && dkc != NULL &&
23433 			    dkc->dkc_callback != NULL) {
23434 				/* async SYNC CACHE request */
23435 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
23436 			} else {
23437 				/* synchronous SYNC CACHE request */
23438 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
23439 			}
23440 		}
23441 		break;
23442 
23443 	case DKIOCFREE:
23444 		{
23445 			dkioc_free_list_t *dfl = (dkioc_free_list_t *)arg;
23446 
23447 			/* bad ioctls shouldn't panic */
23448 			if (dfl == NULL) {
23449 				/* check kernel callers strictly in debug */
23450 				ASSERT0(flag & FKIOCTL);
23451 				err = SET_ERROR(EINVAL);
23452 				break;
23453 			}
23454 			/* synchronous UNMAP request */
23455 			err = sd_send_scsi_UNMAP(dev, ssc, dfl, flag);
23456 		}
23457 		break;
23458 
23459 	case DKIOC_CANFREE:
23460 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC_CANFREE\n");
23461 		i = (un->un_thin_flags & SD_THIN_PROV_ENABLED) ? 1 : 0;
23462 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
23463 			err = EFAULT;
23464 		} else {
23465 			err = 0;
23466 		}
23467 		break;
23468 
23469 	case DKIOCGETWCE: {
23470 
23471 		int wce;
23472 
23473 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
23474 			break;
23475 		}
23476 
23477 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
23478 			err = EFAULT;
23479 		}
23480 		break;
23481 	}
23482 
23483 	case DKIOCSETWCE: {
23484 
23485 		int wce, sync_supported;
23486 		int cur_wce = 0;
23487 
23488 		if (!un->un_f_cache_mode_changeable) {
23489 			err = EINVAL;
23490 			break;
23491 		}
23492 
23493 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
23494 			err = EFAULT;
23495 			break;
23496 		}
23497 
23498 		/*
23499 		 * Synchronize multiple threads trying to enable
23500 		 * or disable the cache via the un_f_wcc_cv
23501 		 * condition variable.
23502 		 */
23503 		mutex_enter(SD_MUTEX(un));
23504 
23505 		/*
23506 		 * Don't allow the cache to be enabled if the
23507 		 * config file has it disabled.
23508 		 */
23509 		if (un->un_f_opt_disable_cache && wce) {
23510 			mutex_exit(SD_MUTEX(un));
23511 			err = EINVAL;
23512 			break;
23513 		}
23514 
23515 		/*
23516 		 * Wait for write cache change in progress
23517 		 * bit to be clear before proceeding.
23518 		 */
23519 		while (un->un_f_wcc_inprog)
23520 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
23521 
23522 		un->un_f_wcc_inprog = 1;
23523 
23524 		mutex_exit(SD_MUTEX(un));
23525 
23526 		/*
23527 		 * Get the current write cache state
23528 		 */
23529 		if ((err = sd_get_write_cache_enabled(ssc, &cur_wce)) != 0) {
23530 			mutex_enter(SD_MUTEX(un));
23531 			un->un_f_wcc_inprog = 0;
23532 			cv_broadcast(&un->un_wcc_cv);
23533 			mutex_exit(SD_MUTEX(un));
23534 			break;
23535 		}
23536 
23537 		mutex_enter(SD_MUTEX(un));
23538 		un->un_f_write_cache_enabled = (cur_wce != 0);
23539 
23540 		if (un->un_f_write_cache_enabled && wce == 0) {
23541 			/*
23542 			 * Disable the write cache.  Don't clear
23543 			 * un_f_write_cache_enabled until after
23544 			 * the mode select and flush are complete.
23545 			 */
23546 			sync_supported = un->un_f_sync_cache_supported;
23547 
23548 			/*
23549 			 * If cache flush is suppressed, we assume that the
23550 			 * controller firmware will take care of managing the
23551 			 * write cache for us: no need to explicitly
23552 			 * disable it.
23553 			 */
23554 			if (!un->un_f_suppress_cache_flush) {
23555 				mutex_exit(SD_MUTEX(un));
23556 				if ((err = sd_cache_control(ssc,
23557 				    SD_CACHE_NOCHANGE,
23558 				    SD_CACHE_DISABLE)) == 0 &&
23559 				    sync_supported) {
23560 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
23561 					    NULL);
23562 				}
23563 			} else {
23564 				mutex_exit(SD_MUTEX(un));
23565 			}
23566 
23567 			mutex_enter(SD_MUTEX(un));
23568 			if (err == 0) {
23569 				un->un_f_write_cache_enabled = 0;
23570 			}
23571 
23572 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
23573 			/*
23574 			 * Set un_f_write_cache_enabled first, so there is
23575 			 * no window where the cache is enabled, but the
23576 			 * bit says it isn't.
23577 			 */
23578 			un->un_f_write_cache_enabled = 1;
23579 
23580 			/*
23581 			 * If cache flush is suppressed, we assume that the
23582 			 * controller firmware will take care of managing the
23583 			 * write cache for us: no need to explicitly
23584 			 * enable it.
23585 			 */
23586 			if (!un->un_f_suppress_cache_flush) {
23587 				mutex_exit(SD_MUTEX(un));
23588 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
23589 				    SD_CACHE_ENABLE);
23590 			} else {
23591 				mutex_exit(SD_MUTEX(un));
23592 			}
23593 
23594 			mutex_enter(SD_MUTEX(un));
23595 
23596 			if (err) {
23597 				un->un_f_write_cache_enabled = 0;
23598 			}
23599 		}
23600 
23601 		un->un_f_wcc_inprog = 0;
23602 		cv_broadcast(&un->un_wcc_cv);
23603 		mutex_exit(SD_MUTEX(un));
23604 		break;
23605 	}
23606 
23607 	default:
23608 		err = ENOTTY;
23609 		break;
23610 	}
23611 	mutex_enter(SD_MUTEX(un));
23612 	un->un_ncmds_in_driver--;
23613 	ASSERT(un->un_ncmds_in_driver >= 0);
23614 	mutex_exit(SD_MUTEX(un));
23615 
23616 
23617 done_without_assess:
23618 	sd_ssc_fini(ssc);
23619 
23620 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23621 	return (err);
23622 
23623 done_with_assess:
23624 	mutex_enter(SD_MUTEX(un));
23625 	un->un_ncmds_in_driver--;
23626 	ASSERT(un->un_ncmds_in_driver >= 0);
23627 	mutex_exit(SD_MUTEX(un));
23628 
23629 done_quick_assess:
23630 	if (err != 0)
23631 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23632 	/* Uninitialize sd_ssc_t pointer */
23633 	sd_ssc_fini(ssc);
23634 
23635 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23636 	return (err);
23637 }
23638 
23639 
23640 /*
23641  *    Function: sd_dkio_ctrl_info
23642  *
23643  * Description: This routine is the driver entry point for handling controller
23644  *		information ioctl requests (DKIOCINFO).
23645  *
23646  *   Arguments: dev  - the device number
23647  *		arg  - pointer to user provided dk_cinfo structure
23648  *		       specifying the controller type and attributes.
23649  *		flag - this argument is a pass through to ddi_copyxxx()
23650  *		       directly from the mode argument of ioctl().
23651  *
23652  * Return Code: 0
23653  *		EFAULT
23654  *		ENXIO
23655  */
23656 
23657 static int
23658 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
23659 {
23660 	struct sd_lun	*un = NULL;
23661 	struct dk_cinfo	*info;
23662 	dev_info_t	*pdip;
23663 	int		lun, tgt;
23664 
23665 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23666 		return (ENXIO);
23667 	}
23668 
23669 	info = (struct dk_cinfo *)
23670 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
23671 
23672 	switch (un->un_ctype) {
23673 	case CTYPE_CDROM:
23674 		info->dki_ctype = DKC_CDROM;
23675 		break;
23676 	default:
23677 		info->dki_ctype = DKC_SCSI_CCS;
23678 		break;
23679 	}
23680 	pdip = ddi_get_parent(SD_DEVINFO(un));
23681 	info->dki_cnum = ddi_get_instance(pdip);
23682 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
23683 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
23684 	} else {
23685 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
23686 		    DK_DEVLEN - 1);
23687 	}
23688 
23689 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23690 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
23691 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23692 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
23693 
23694 	/* Unit Information */
23695 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
23696 	info->dki_slave = ((tgt << 3) | lun);
23697 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
23698 	    DK_DEVLEN - 1);
23699 	info->dki_flags = DKI_FMTVOL;
23700 	info->dki_partition = SDPART(dev);
23701 
23702 	/* Max Transfer size of this device in blocks */
23703 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
23704 	info->dki_addr = 0;
23705 	info->dki_space = 0;
23706 	info->dki_prio = 0;
23707 	info->dki_vec = 0;
23708 
23709 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
23710 		kmem_free(info, sizeof (struct dk_cinfo));
23711 		return (EFAULT);
23712 	} else {
23713 		kmem_free(info, sizeof (struct dk_cinfo));
23714 		return (0);
23715 	}
23716 }
23717 
23718 /*
23719  *    Function: sd_get_media_info_com
23720  *
23721  * Description: This routine returns the information required to populate
23722  *		the fields for the dk_minfo/dk_minfo_ext structures.
23723  *
23724  *   Arguments: dev		- the device number
23725  *		dki_media_type	- media_type
23726  *		dki_lbsize	- logical block size
23727  *		dki_capacity	- capacity in blocks
23728  *		dki_pbsize	- physical block size (if requested)
23729  *
23730  * Return Code: 0
23731  *		EACCESS
23732  *		EFAULT
23733  *		ENXIO
23734  *		EIO
23735  */
23736 static int
23737 sd_get_media_info_com(dev_t dev, uint_t *dki_media_type, uint_t *dki_lbsize,
23738     diskaddr_t *dki_capacity, uint_t *dki_pbsize)
23739 {
23740 	struct sd_lun		*un = NULL;
23741 	struct uscsi_cmd	com;
23742 	struct scsi_inquiry	*sinq;
23743 	u_longlong_t		media_capacity;
23744 	uint64_t		capacity;
23745 	uint_t			lbasize;
23746 	uint_t			pbsize;
23747 	uchar_t			*out_data;
23748 	uchar_t			*rqbuf;
23749 	int			rval = 0;
23750 	int			rtn;
23751 	sd_ssc_t		*ssc;
23752 
23753 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
23754 	    (un->un_state == SD_STATE_OFFLINE)) {
23755 		return (ENXIO);
23756 	}
23757 
23758 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info_com: entry\n");
23759 
23760 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
23761 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
23762 	ssc = sd_ssc_init(un);
23763 
23764 	/* Issue a TUR to determine if the drive is ready with media present */
23765 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
23766 	if (rval == ENXIO) {
23767 		goto done;
23768 	} else if (rval != 0) {
23769 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23770 	}
23771 
23772 	/* Now get configuration data */
23773 	if (ISCD(un)) {
23774 		*dki_media_type = DK_CDROM;
23775 
23776 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
23777 		if (un->un_f_mmc_cap == TRUE) {
23778 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
23779 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
23780 			    SD_PATH_STANDARD);
23781 
23782 			if (rtn) {
23783 				/*
23784 				 * We ignore all failures for CD and need to
23785 				 * put the assessment before processing code
23786 				 * to avoid missing assessment for FMA.
23787 				 */
23788 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23789 				/*
23790 				 * Failed for other than an illegal request
23791 				 * or command not supported
23792 				 */
23793 				if ((com.uscsi_status == STATUS_CHECK) &&
23794 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
23795 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
23796 					    (rqbuf[12] != 0x20)) {
23797 						rval = EIO;
23798 						goto no_assessment;
23799 					}
23800 				}
23801 			} else {
23802 				/*
23803 				 * The GET CONFIGURATION command succeeded
23804 				 * so set the media type according to the
23805 				 * returned data
23806 				 */
23807 				*dki_media_type = out_data[6];
23808 				*dki_media_type <<= 8;
23809 				*dki_media_type |= out_data[7];
23810 			}
23811 		}
23812 	} else {
23813 		/*
23814 		 * The profile list is not available, so we attempt to identify
23815 		 * the media type based on the inquiry data
23816 		 */
23817 		sinq = un->un_sd->sd_inq;
23818 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
23819 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
23820 			/* This is a direct access device  or optical disk */
23821 			*dki_media_type = DK_FIXED_DISK;
23822 
23823 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
23824 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
23825 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
23826 					*dki_media_type = DK_ZIP;
23827 				} else if (
23828 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
23829 					*dki_media_type = DK_JAZ;
23830 				}
23831 			}
23832 		} else {
23833 			/*
23834 			 * Not a CD, direct access or optical disk so return
23835 			 * unknown media
23836 			 */
23837 			*dki_media_type = DK_UNKNOWN;
23838 		}
23839 	}
23840 
23841 	/*
23842 	 * Now read the capacity so we can provide the lbasize,
23843 	 * pbsize and capacity.
23844 	 */
23845 	if (dki_pbsize && un->un_f_descr_format_supported) {
23846 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
23847 		    &pbsize, SD_PATH_DIRECT);
23848 
23849 		/*
23850 		 * Override the physical blocksize if the instance already
23851 		 * has a larger value.
23852 		 */
23853 		pbsize = MAX(pbsize, un->un_phy_blocksize);
23854 	}
23855 
23856 	if (dki_pbsize == NULL || rval != 0 ||
23857 	    !un->un_f_descr_format_supported) {
23858 		rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
23859 		    SD_PATH_DIRECT);
23860 
23861 		switch (rval) {
23862 		case 0:
23863 			if (un->un_f_enable_rmw &&
23864 			    un->un_phy_blocksize != 0) {
23865 				pbsize = un->un_phy_blocksize;
23866 			} else {
23867 				pbsize = lbasize;
23868 			}
23869 			media_capacity = capacity;
23870 
23871 			/*
23872 			 * sd_send_scsi_READ_CAPACITY() reports capacity in
23873 			 * un->un_sys_blocksize chunks. So we need to convert
23874 			 * it into cap.lbsize chunks.
23875 			 */
23876 			if (un->un_f_has_removable_media) {
23877 				media_capacity *= un->un_sys_blocksize;
23878 				media_capacity /= lbasize;
23879 			}
23880 			break;
23881 		case EACCES:
23882 			rval = EACCES;
23883 			goto done;
23884 		default:
23885 			rval = EIO;
23886 			goto done;
23887 		}
23888 	} else {
23889 		if (un->un_f_enable_rmw &&
23890 		    !ISP2(pbsize % DEV_BSIZE)) {
23891 			pbsize = SSD_SECSIZE;
23892 		} else if (!ISP2(lbasize % DEV_BSIZE) ||
23893 		    !ISP2(pbsize % DEV_BSIZE)) {
23894 			pbsize = lbasize = DEV_BSIZE;
23895 		}
23896 		media_capacity = capacity;
23897 	}
23898 
23899 	/*
23900 	 * If lun is expanded dynamically, update the un structure.
23901 	 */
23902 	mutex_enter(SD_MUTEX(un));
23903 	if ((un->un_f_blockcount_is_valid == TRUE) &&
23904 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
23905 	    (capacity > un->un_blockcount)) {
23906 		un->un_f_expnevent = B_FALSE;
23907 		sd_update_block_info(un, lbasize, capacity);
23908 	}
23909 	mutex_exit(SD_MUTEX(un));
23910 
23911 	*dki_lbsize = lbasize;
23912 	*dki_capacity = media_capacity;
23913 	if (dki_pbsize)
23914 		*dki_pbsize = pbsize;
23915 
23916 done:
23917 	if (rval != 0) {
23918 		if (rval == EIO)
23919 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23920 		else
23921 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23922 	}
23923 no_assessment:
23924 	sd_ssc_fini(ssc);
23925 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
23926 	kmem_free(rqbuf, SENSE_LENGTH);
23927 	return (rval);
23928 }
23929 
23930 /*
23931  *    Function: sd_get_media_info
23932  *
23933  * Description: This routine is the driver entry point for handling ioctl
23934  *		requests for the media type or command set profile used by the
23935  *		drive to operate on the media (DKIOCGMEDIAINFO).
23936  *
23937  *   Arguments: dev	- the device number
23938  *		arg	- pointer to user provided dk_minfo structure
23939  *			  specifying the media type, logical block size and
23940  *			  drive capacity.
23941  *		flag	- this argument is a pass through to ddi_copyxxx()
23942  *			  directly from the mode argument of ioctl().
23943  *
23944  * Return Code: returns the value from sd_get_media_info_com
23945  */
23946 static int
23947 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
23948 {
23949 	struct dk_minfo		mi;
23950 	int			rval;
23951 
23952 	rval = sd_get_media_info_com(dev, &mi.dki_media_type,
23953 	    &mi.dki_lbsize, &mi.dki_capacity, NULL);
23954 
23955 	if (rval)
23956 		return (rval);
23957 	if (ddi_copyout(&mi, arg, sizeof (struct dk_minfo), flag))
23958 		rval = EFAULT;
23959 	return (rval);
23960 }
23961 
23962 /*
23963  *    Function: sd_get_media_info_ext
23964  *
23965  * Description: This routine is the driver entry point for handling ioctl
23966  *		requests for the media type or command set profile used by the
23967  *		drive to operate on the media (DKIOCGMEDIAINFOEXT). The
23968  *		difference this ioctl and DKIOCGMEDIAINFO is the return value
23969  *		of this ioctl contains both logical block size and physical
23970  *		block size.
23971  *
23972  *
23973  *   Arguments: dev	- the device number
23974  *		arg	- pointer to user provided dk_minfo_ext structure
23975  *			  specifying the media type, logical block size,
23976  *			  physical block size and disk capacity.
23977  *		flag	- this argument is a pass through to ddi_copyxxx()
23978  *			  directly from the mode argument of ioctl().
23979  *
23980  * Return Code: returns the value from sd_get_media_info_com
23981  */
23982 static int
23983 sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag)
23984 {
23985 	struct dk_minfo_ext	mie;
23986 	int			rval = 0;
23987 	size_t			len;
23988 
23989 	rval = sd_get_media_info_com(dev, &mie.dki_media_type,
23990 	    &mie.dki_lbsize, &mie.dki_capacity, &mie.dki_pbsize);
23991 
23992 	if (rval)
23993 		return (rval);
23994 
23995 	switch (ddi_model_convert_from(flag & FMODELS)) {
23996 	case DDI_MODEL_ILP32:
23997 		len = sizeof (struct dk_minfo_ext32);
23998 		break;
23999 	default:
24000 		len = sizeof (struct dk_minfo_ext);
24001 		break;
24002 	}
24003 
24004 	if (ddi_copyout(&mie, arg, len, flag))
24005 		rval = EFAULT;
24006 	return (rval);
24007 
24008 }
24009 
24010 /*
24011  *    Function: sd_watch_request_submit
24012  *
24013  * Description: Call scsi_watch_request_submit or scsi_mmc_watch_request_submit
24014  *		depending on which is supported by device.
24015  */
24016 static opaque_t
24017 sd_watch_request_submit(struct sd_lun *un)
24018 {
24019 	dev_t			dev;
24020 
24021 	/* All submissions are unified to use same device number */
24022 	dev = sd_make_device(SD_DEVINFO(un));
24023 
24024 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
24025 		return (scsi_mmc_watch_request_submit(SD_SCSI_DEVP(un),
24026 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
24027 		    (caddr_t)dev));
24028 	} else {
24029 		return (scsi_watch_request_submit(SD_SCSI_DEVP(un),
24030 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
24031 		    (caddr_t)dev));
24032 	}
24033 }
24034 
24035 
24036 /*
24037  *    Function: sd_check_media
24038  *
24039  * Description: This utility routine implements the functionality for the
24040  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
24041  *		driver state changes from that specified by the user
24042  *		(inserted or ejected). For example, if the user specifies
24043  *		DKIO_EJECTED and the current media state is inserted this
24044  *		routine will immediately return DKIO_INSERTED. However, if the
24045  *		current media state is not inserted the user thread will be
24046  *		blocked until the drive state changes. If DKIO_NONE is specified
24047  *		the user thread will block until a drive state change occurs.
24048  *
24049  *   Arguments: dev  - the device number
24050  *		state  - user pointer to a dkio_state, updated with the current
24051  *			drive state at return.
24052  *
24053  * Return Code: ENXIO
24054  *		EIO
24055  *		EAGAIN
24056  *		EINTR
24057  */
24058 
24059 static int
24060 sd_check_media(dev_t dev, enum dkio_state state)
24061 {
24062 	struct sd_lun		*un = NULL;
24063 	enum dkio_state		prev_state;
24064 	opaque_t		token = NULL;
24065 	int			rval = 0;
24066 	sd_ssc_t		*ssc;
24067 
24068 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24069 		return (ENXIO);
24070 	}
24071 
24072 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
24073 
24074 	ssc = sd_ssc_init(un);
24075 
24076 	mutex_enter(SD_MUTEX(un));
24077 
24078 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
24079 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
24080 
24081 	prev_state = un->un_mediastate;
24082 
24083 	/* is there anything to do? */
24084 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
24085 		/*
24086 		 * submit the request to the scsi_watch service;
24087 		 * scsi_media_watch_cb() does the real work
24088 		 */
24089 		mutex_exit(SD_MUTEX(un));
24090 
24091 		/*
24092 		 * This change handles the case where a scsi watch request is
24093 		 * added to a device that is powered down. To accomplish this
24094 		 * we power up the device before adding the scsi watch request,
24095 		 * since the scsi watch sends a TUR directly to the device
24096 		 * which the device cannot handle if it is powered down.
24097 		 */
24098 		if (sd_pm_entry(un) != DDI_SUCCESS) {
24099 			mutex_enter(SD_MUTEX(un));
24100 			goto done;
24101 		}
24102 
24103 		token = sd_watch_request_submit(un);
24104 
24105 		sd_pm_exit(un);
24106 
24107 		mutex_enter(SD_MUTEX(un));
24108 		if (token == NULL) {
24109 			rval = EAGAIN;
24110 			goto done;
24111 		}
24112 
24113 		/*
24114 		 * This is a special case IOCTL that doesn't return
24115 		 * until the media state changes. Routine sdpower
24116 		 * knows about and handles this so don't count it
24117 		 * as an active cmd in the driver, which would
24118 		 * keep the device busy to the pm framework.
24119 		 * If the count isn't decremented the device can't
24120 		 * be powered down.
24121 		 */
24122 		un->un_ncmds_in_driver--;
24123 		ASSERT(un->un_ncmds_in_driver >= 0);
24124 
24125 		/*
24126 		 * if a prior request had been made, this will be the same
24127 		 * token, as scsi_watch was designed that way.
24128 		 */
24129 		un->un_swr_token = token;
24130 		un->un_specified_mediastate = state;
24131 
24132 		/*
24133 		 * now wait for media change
24134 		 * we will not be signalled unless mediastate == state but it is
24135 		 * still better to test for this condition, since there is a
24136 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
24137 		 */
24138 		SD_TRACE(SD_LOG_COMMON, un,
24139 		    "sd_check_media: waiting for media state change\n");
24140 		while (un->un_mediastate == state) {
24141 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
24142 				SD_TRACE(SD_LOG_COMMON, un,
24143 				    "sd_check_media: waiting for media state "
24144 				    "was interrupted\n");
24145 				un->un_ncmds_in_driver++;
24146 				rval = EINTR;
24147 				goto done;
24148 			}
24149 			SD_TRACE(SD_LOG_COMMON, un,
24150 			    "sd_check_media: received signal, state=%x\n",
24151 			    un->un_mediastate);
24152 		}
24153 		/*
24154 		 * Inc the counter to indicate the device once again
24155 		 * has an active outstanding cmd.
24156 		 */
24157 		un->un_ncmds_in_driver++;
24158 	}
24159 
24160 	/* invalidate geometry */
24161 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
24162 		sr_ejected(un);
24163 	}
24164 
24165 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
24166 		uint64_t	capacity;
24167 		uint_t		lbasize;
24168 
24169 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
24170 		mutex_exit(SD_MUTEX(un));
24171 		/*
24172 		 * Since the following routines use SD_PATH_DIRECT, we must
24173 		 * call PM directly before the upcoming disk accesses. This
24174 		 * may cause the disk to be power/spin up.
24175 		 */
24176 
24177 		if (sd_pm_entry(un) == DDI_SUCCESS) {
24178 			rval = sd_send_scsi_READ_CAPACITY(ssc,
24179 			    &capacity, &lbasize, SD_PATH_DIRECT);
24180 			if (rval != 0) {
24181 				sd_pm_exit(un);
24182 				if (rval == EIO)
24183 					sd_ssc_assessment(ssc,
24184 					    SD_FMT_STATUS_CHECK);
24185 				else
24186 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24187 				mutex_enter(SD_MUTEX(un));
24188 				goto done;
24189 			}
24190 		} else {
24191 			rval = EIO;
24192 			mutex_enter(SD_MUTEX(un));
24193 			goto done;
24194 		}
24195 		mutex_enter(SD_MUTEX(un));
24196 
24197 		sd_update_block_info(un, lbasize, capacity);
24198 
24199 		/*
24200 		 *  Check if the media in the device is writable or not
24201 		 */
24202 		if (ISCD(un)) {
24203 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
24204 		}
24205 
24206 		mutex_exit(SD_MUTEX(un));
24207 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
24208 		if ((cmlb_validate(un->un_cmlbhandle, 0,
24209 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
24210 			sd_set_pstats(un);
24211 			SD_TRACE(SD_LOG_IO_PARTITION, un,
24212 			    "sd_check_media: un:0x%p pstats created and "
24213 			    "set\n", un);
24214 		}
24215 
24216 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
24217 		    SD_PATH_DIRECT);
24218 
24219 		sd_pm_exit(un);
24220 
24221 		if (rval != 0) {
24222 			if (rval == EIO)
24223 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24224 			else
24225 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24226 		}
24227 
24228 		mutex_enter(SD_MUTEX(un));
24229 	}
24230 done:
24231 	sd_ssc_fini(ssc);
24232 	un->un_f_watcht_stopped = FALSE;
24233 	if (token != NULL && un->un_swr_token != NULL) {
24234 		/*
24235 		 * Use of this local token and the mutex ensures that we avoid
24236 		 * some race conditions associated with terminating the
24237 		 * scsi watch.
24238 		 */
24239 		token = un->un_swr_token;
24240 		mutex_exit(SD_MUTEX(un));
24241 		(void) scsi_watch_request_terminate(token,
24242 		    SCSI_WATCH_TERMINATE_WAIT);
24243 		if (scsi_watch_get_ref_count(token) == 0) {
24244 			mutex_enter(SD_MUTEX(un));
24245 			un->un_swr_token = (opaque_t)NULL;
24246 		} else {
24247 			mutex_enter(SD_MUTEX(un));
24248 		}
24249 	}
24250 
24251 	/*
24252 	 * Update the capacity kstat value, if no media previously
24253 	 * (capacity kstat is 0) and a media has been inserted
24254 	 * (un_f_blockcount_is_valid == TRUE)
24255 	 */
24256 	if (un->un_errstats) {
24257 		struct sd_errstats	*stp = NULL;
24258 
24259 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
24260 		if ((stp->sd_capacity.value.ui64 == 0) &&
24261 		    (un->un_f_blockcount_is_valid == TRUE)) {
24262 			stp->sd_capacity.value.ui64 =
24263 			    (uint64_t)((uint64_t)un->un_blockcount *
24264 			    un->un_sys_blocksize);
24265 		}
24266 	}
24267 	mutex_exit(SD_MUTEX(un));
24268 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
24269 	return (rval);
24270 }
24271 
24272 
24273 /*
24274  *    Function: sd_delayed_cv_broadcast
24275  *
24276  * Description: Delayed cv_broadcast to allow for target to recover from media
24277  *		insertion.
24278  *
24279  *   Arguments: arg - driver soft state (unit) structure
24280  */
24281 
24282 static void
24283 sd_delayed_cv_broadcast(void *arg)
24284 {
24285 	struct sd_lun *un = arg;
24286 
24287 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
24288 
24289 	mutex_enter(SD_MUTEX(un));
24290 	un->un_dcvb_timeid = NULL;
24291 	cv_broadcast(&un->un_state_cv);
24292 	mutex_exit(SD_MUTEX(un));
24293 }
24294 
24295 
24296 /*
24297  *    Function: sd_media_watch_cb
24298  *
24299  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
24300  *		routine processes the TUR sense data and updates the driver
24301  *		state if a transition has occurred. The user thread
24302  *		(sd_check_media) is then signalled.
24303  *
24304  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24305  *			among multiple watches that share this callback function
24306  *		resultp - scsi watch facility result packet containing scsi
24307  *			  packet, status byte and sense data
24308  *
24309  * Return Code: 0 for success, -1 for failure
24310  */
24311 
24312 static int
24313 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
24314 {
24315 	struct sd_lun			*un;
24316 	struct scsi_status		*statusp = resultp->statusp;
24317 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
24318 	enum dkio_state			state = DKIO_NONE;
24319 	dev_t				dev = (dev_t)arg;
24320 	uchar_t				actual_sense_length;
24321 	uint8_t				skey, asc, ascq;
24322 
24323 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24324 		return (-1);
24325 	}
24326 	actual_sense_length = resultp->actual_sense_length;
24327 
24328 	mutex_enter(SD_MUTEX(un));
24329 	SD_TRACE(SD_LOG_COMMON, un,
24330 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
24331 	    *((char *)statusp), (void *)sensep, actual_sense_length);
24332 
24333 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
24334 		un->un_mediastate = DKIO_DEV_GONE;
24335 		cv_broadcast(&un->un_state_cv);
24336 		mutex_exit(SD_MUTEX(un));
24337 
24338 		return (0);
24339 	}
24340 
24341 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
24342 		if (sd_gesn_media_data_valid(resultp->mmc_data)) {
24343 			if ((resultp->mmc_data[5] &
24344 			    SD_GESN_MEDIA_EVENT_STATUS_PRESENT) != 0) {
24345 				state = DKIO_INSERTED;
24346 			} else {
24347 				state = DKIO_EJECTED;
24348 			}
24349 			if ((resultp->mmc_data[4] & SD_GESN_MEDIA_EVENT_CODE) ==
24350 			    SD_GESN_MEDIA_EVENT_EJECTREQUEST) {
24351 				sd_log_eject_request_event(un, KM_NOSLEEP);
24352 			}
24353 		}
24354 	} else if (sensep != NULL) {
24355 		/*
24356 		 * If there was a check condition then sensep points to valid
24357 		 * sense data. If status was not a check condition but a
24358 		 * reservation or busy status then the new state is DKIO_NONE.
24359 		 */
24360 		skey = scsi_sense_key(sensep);
24361 		asc = scsi_sense_asc(sensep);
24362 		ascq = scsi_sense_ascq(sensep);
24363 
24364 		SD_INFO(SD_LOG_COMMON, un,
24365 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
24366 		    skey, asc, ascq);
24367 		/* This routine only uses up to 13 bytes of sense data. */
24368 		if (actual_sense_length >= 13) {
24369 			if (skey == KEY_UNIT_ATTENTION) {
24370 				if (asc == 0x28) {
24371 					state = DKIO_INSERTED;
24372 				}
24373 			} else if (skey == KEY_NOT_READY) {
24374 				/*
24375 				 * Sense data of 02/06/00 means that the
24376 				 * drive could not read the media (No
24377 				 * reference position found). In this case
24378 				 * to prevent a hang on the DKIOCSTATE IOCTL
24379 				 * we set the media state to DKIO_INSERTED.
24380 				 */
24381 				if (asc == 0x06 && ascq == 0x00)
24382 					state = DKIO_INSERTED;
24383 
24384 				/*
24385 				 * if 02/04/02  means that the host
24386 				 * should send start command. Explicitly
24387 				 * leave the media state as is
24388 				 * (inserted) as the media is inserted
24389 				 * and host has stopped device for PM
24390 				 * reasons. Upon next true read/write
24391 				 * to this media will bring the
24392 				 * device to the right state good for
24393 				 * media access.
24394 				 */
24395 				if (asc == 0x3a) {
24396 					state = DKIO_EJECTED;
24397 				} else {
24398 					/*
24399 					 * If the drive is busy with an
24400 					 * operation or long write, keep the
24401 					 * media in an inserted state.
24402 					 */
24403 
24404 					if ((asc == 0x04) &&
24405 					    ((ascq == 0x02) ||
24406 					    (ascq == 0x07) ||
24407 					    (ascq == 0x08))) {
24408 						state = DKIO_INSERTED;
24409 					}
24410 				}
24411 			} else if (skey == KEY_NO_SENSE) {
24412 				if ((asc == 0x00) && (ascq == 0x00)) {
24413 					/*
24414 					 * Sense Data 00/00/00 does not provide
24415 					 * any information about the state of
24416 					 * the media. Ignore it.
24417 					 */
24418 					mutex_exit(SD_MUTEX(un));
24419 					return (0);
24420 				}
24421 			}
24422 		}
24423 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
24424 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
24425 		state = DKIO_INSERTED;
24426 	}
24427 
24428 	SD_TRACE(SD_LOG_COMMON, un,
24429 	    "sd_media_watch_cb: state=%x, specified=%x\n",
24430 	    state, un->un_specified_mediastate);
24431 
24432 	/*
24433 	 * now signal the waiting thread if this is *not* the specified state;
24434 	 * delay the signal if the state is DKIO_INSERTED to allow the target
24435 	 * to recover
24436 	 */
24437 	if (state != un->un_specified_mediastate) {
24438 		un->un_mediastate = state;
24439 		if (state == DKIO_INSERTED) {
24440 			/*
24441 			 * delay the signal to give the drive a chance
24442 			 * to do what it apparently needs to do
24443 			 */
24444 			SD_TRACE(SD_LOG_COMMON, un,
24445 			    "sd_media_watch_cb: delayed cv_broadcast\n");
24446 			if (un->un_dcvb_timeid == NULL) {
24447 				un->un_dcvb_timeid =
24448 				    timeout(sd_delayed_cv_broadcast, un,
24449 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
24450 			}
24451 		} else {
24452 			SD_TRACE(SD_LOG_COMMON, un,
24453 			    "sd_media_watch_cb: immediate cv_broadcast\n");
24454 			cv_broadcast(&un->un_state_cv);
24455 		}
24456 	}
24457 	mutex_exit(SD_MUTEX(un));
24458 	return (0);
24459 }
24460 
24461 
24462 /*
24463  *    Function: sd_dkio_get_temp
24464  *
24465  * Description: This routine is the driver entry point for handling ioctl
24466  *		requests to get the disk temperature.
24467  *
24468  *   Arguments: dev  - the device number
24469  *		arg  - pointer to user provided dk_temperature structure.
24470  *		flag - this argument is a pass through to ddi_copyxxx()
24471  *		       directly from the mode argument of ioctl().
24472  *
24473  * Return Code: 0
24474  *		EFAULT
24475  *		ENXIO
24476  *		EAGAIN
24477  */
24478 
24479 static int
24480 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
24481 {
24482 	struct sd_lun		*un = NULL;
24483 	struct dk_temperature	*dktemp = NULL;
24484 	uchar_t			*temperature_page;
24485 	int			rval = 0;
24486 	int			path_flag = SD_PATH_STANDARD;
24487 	sd_ssc_t		*ssc;
24488 
24489 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24490 		return (ENXIO);
24491 	}
24492 
24493 	ssc = sd_ssc_init(un);
24494 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
24495 
24496 	/* copyin the disk temp argument to get the user flags */
24497 	if (ddi_copyin((void *)arg, dktemp,
24498 	    sizeof (struct dk_temperature), flag) != 0) {
24499 		rval = EFAULT;
24500 		goto done;
24501 	}
24502 
24503 	/* Initialize the temperature to invalid. */
24504 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24505 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24506 
24507 	/*
24508 	 * Note: Investigate removing the "bypass pm" semantic.
24509 	 * Can we just bypass PM always?
24510 	 */
24511 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
24512 		path_flag = SD_PATH_DIRECT;
24513 		ASSERT(!mutex_owned(&un->un_pm_mutex));
24514 		mutex_enter(&un->un_pm_mutex);
24515 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24516 			/*
24517 			 * If DKT_BYPASS_PM is set, and the drive happens to be
24518 			 * in low power mode, we can not wake it up, Need to
24519 			 * return EAGAIN.
24520 			 */
24521 			mutex_exit(&un->un_pm_mutex);
24522 			rval = EAGAIN;
24523 			goto done;
24524 		} else {
24525 			/*
24526 			 * Indicate to PM the device is busy. This is required
24527 			 * to avoid a race - i.e. the ioctl is issuing a
24528 			 * command and the pm framework brings down the device
24529 			 * to low power mode (possible power cut-off on some
24530 			 * platforms).
24531 			 */
24532 			mutex_exit(&un->un_pm_mutex);
24533 			if (sd_pm_entry(un) != DDI_SUCCESS) {
24534 				rval = EAGAIN;
24535 				goto done;
24536 			}
24537 		}
24538 	}
24539 
24540 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
24541 
24542 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
24543 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
24544 	if (rval != 0)
24545 		goto done2;
24546 
24547 	/*
24548 	 * For the current temperature verify that the parameter length is 0x02
24549 	 * and the parameter code is 0x00
24550 	 */
24551 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
24552 	    (temperature_page[5] == 0x00)) {
24553 		if (temperature_page[9] == 0xFF) {
24554 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24555 		} else {
24556 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
24557 		}
24558 	}
24559 
24560 	/*
24561 	 * For the reference temperature verify that the parameter
24562 	 * length is 0x02 and the parameter code is 0x01
24563 	 */
24564 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
24565 	    (temperature_page[11] == 0x01)) {
24566 		if (temperature_page[15] == 0xFF) {
24567 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24568 		} else {
24569 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
24570 		}
24571 	}
24572 
24573 	/* Do the copyout regardless of the temperature commands status. */
24574 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
24575 	    flag) != 0) {
24576 		rval = EFAULT;
24577 		goto done1;
24578 	}
24579 
24580 done2:
24581 	if (rval != 0) {
24582 		if (rval == EIO)
24583 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24584 		else
24585 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24586 	}
24587 done1:
24588 	if (path_flag == SD_PATH_DIRECT) {
24589 		sd_pm_exit(un);
24590 	}
24591 
24592 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
24593 done:
24594 	sd_ssc_fini(ssc);
24595 	if (dktemp != NULL) {
24596 		kmem_free(dktemp, sizeof (struct dk_temperature));
24597 	}
24598 
24599 	return (rval);
24600 }
24601 
24602 
24603 /*
24604  *    Function: sd_log_page_supported
24605  *
24606  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
24607  *		supported log pages.
24608  *
24609  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
24610  *                      structure for this target.
24611  *		log_page -
24612  *
24613  * Return Code: -1 - on error (log sense is optional and may not be supported).
24614  *		0  - log page not found.
24615  *		1  - log page found.
24616  */
24617 
24618 static int
24619 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
24620 {
24621 	uchar_t *log_page_data;
24622 	int	i;
24623 	int	match = 0;
24624 	int	log_size;
24625 	int	status = 0;
24626 	struct sd_lun	*un;
24627 
24628 	ASSERT(ssc != NULL);
24629 	un = ssc->ssc_un;
24630 	ASSERT(un != NULL);
24631 
24632 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
24633 
24634 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
24635 	    SD_PATH_DIRECT);
24636 
24637 	if (status != 0) {
24638 		if (status == EIO) {
24639 			/*
24640 			 * Some disks do not support log sense, we
24641 			 * should ignore this kind of error(sense key is
24642 			 * 0x5 - illegal request).
24643 			 */
24644 			uint8_t *sensep;
24645 			int senlen;
24646 
24647 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
24648 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
24649 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
24650 
24651 			if (senlen > 0 &&
24652 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
24653 				sd_ssc_assessment(ssc,
24654 				    SD_FMT_IGNORE_COMPROMISE);
24655 			} else {
24656 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24657 			}
24658 		} else {
24659 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24660 		}
24661 
24662 		SD_ERROR(SD_LOG_COMMON, un,
24663 		    "sd_log_page_supported: failed log page retrieval\n");
24664 		kmem_free(log_page_data, 0xFF);
24665 		return (-1);
24666 	}
24667 
24668 	log_size = log_page_data[3];
24669 
24670 	/*
24671 	 * The list of supported log pages start from the fourth byte. Check
24672 	 * until we run out of log pages or a match is found.
24673 	 */
24674 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
24675 		if (log_page_data[i] == log_page) {
24676 			match++;
24677 		}
24678 	}
24679 	kmem_free(log_page_data, 0xFF);
24680 	return (match);
24681 }
24682 
24683 
24684 /*
24685  *    Function: sd_mhdioc_failfast
24686  *
24687  * Description: This routine is the driver entry point for handling ioctl
24688  *		requests to enable/disable the multihost failfast option.
24689  *		(MHIOCENFAILFAST)
24690  *
24691  *   Arguments: dev	- the device number
24692  *		arg	- user specified probing interval.
24693  *		flag	- this argument is a pass through to ddi_copyxxx()
24694  *			  directly from the mode argument of ioctl().
24695  *
24696  * Return Code: 0
24697  *		EFAULT
24698  *		ENXIO
24699  */
24700 
24701 static int
24702 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
24703 {
24704 	struct sd_lun	*un = NULL;
24705 	int		mh_time;
24706 	int		rval = 0;
24707 
24708 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24709 		return (ENXIO);
24710 	}
24711 
24712 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
24713 		return (EFAULT);
24714 
24715 	if (mh_time) {
24716 		mutex_enter(SD_MUTEX(un));
24717 		un->un_resvd_status |= SD_FAILFAST;
24718 		mutex_exit(SD_MUTEX(un));
24719 		/*
24720 		 * If mh_time is INT_MAX, then this ioctl is being used for
24721 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
24722 		 */
24723 		if (mh_time != INT_MAX) {
24724 			rval = sd_check_mhd(dev, mh_time);
24725 		}
24726 	} else {
24727 		(void) sd_check_mhd(dev, 0);
24728 		mutex_enter(SD_MUTEX(un));
24729 		un->un_resvd_status &= ~SD_FAILFAST;
24730 		mutex_exit(SD_MUTEX(un));
24731 	}
24732 	return (rval);
24733 }
24734 
24735 
24736 /*
24737  *    Function: sd_mhdioc_takeown
24738  *
24739  * Description: This routine is the driver entry point for handling ioctl
24740  *		requests to forcefully acquire exclusive access rights to the
24741  *		multihost disk (MHIOCTKOWN).
24742  *
24743  *   Arguments: dev	- the device number
24744  *		arg	- user provided structure specifying the delay
24745  *			  parameters in milliseconds
24746  *		flag	- this argument is a pass through to ddi_copyxxx()
24747  *			  directly from the mode argument of ioctl().
24748  *
24749  * Return Code: 0
24750  *		EFAULT
24751  *		ENXIO
24752  */
24753 
24754 static int
24755 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
24756 {
24757 	struct sd_lun		*un = NULL;
24758 	struct mhioctkown	*tkown = NULL;
24759 	int			rval = 0;
24760 
24761 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24762 		return (ENXIO);
24763 	}
24764 
24765 	if (arg != NULL) {
24766 		tkown = (struct mhioctkown *)
24767 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
24768 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
24769 		if (rval != 0) {
24770 			rval = EFAULT;
24771 			goto error;
24772 		}
24773 	}
24774 
24775 	rval = sd_take_ownership(dev, tkown);
24776 	mutex_enter(SD_MUTEX(un));
24777 	if (rval == 0) {
24778 		un->un_resvd_status |= SD_RESERVE;
24779 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
24780 			sd_reinstate_resv_delay =
24781 			    tkown->reinstate_resv_delay * 1000;
24782 		} else {
24783 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
24784 		}
24785 		/*
24786 		 * Give the scsi_watch routine interval set by
24787 		 * the MHIOCENFAILFAST ioctl precedence here.
24788 		 */
24789 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
24790 			mutex_exit(SD_MUTEX(un));
24791 			(void) sd_check_mhd(dev,
24792 			    sd_reinstate_resv_delay / 1000);
24793 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
24794 			    "sd_mhdioc_takeown : %d\n",
24795 			    sd_reinstate_resv_delay);
24796 		} else {
24797 			mutex_exit(SD_MUTEX(un));
24798 		}
24799 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
24800 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24801 	} else {
24802 		un->un_resvd_status &= ~SD_RESERVE;
24803 		mutex_exit(SD_MUTEX(un));
24804 	}
24805 
24806 error:
24807 	if (tkown != NULL) {
24808 		kmem_free(tkown, sizeof (struct mhioctkown));
24809 	}
24810 	return (rval);
24811 }
24812 
24813 
24814 /*
24815  *    Function: sd_mhdioc_release
24816  *
24817  * Description: This routine is the driver entry point for handling ioctl
24818  *		requests to release exclusive access rights to the multihost
24819  *		disk (MHIOCRELEASE).
24820  *
24821  *   Arguments: dev	- the device number
24822  *
24823  * Return Code: 0
24824  *		ENXIO
24825  */
24826 
24827 static int
24828 sd_mhdioc_release(dev_t dev)
24829 {
24830 	struct sd_lun		*un = NULL;
24831 	timeout_id_t		resvd_timeid_save;
24832 	int			resvd_status_save;
24833 	int			rval = 0;
24834 
24835 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24836 		return (ENXIO);
24837 	}
24838 
24839 	mutex_enter(SD_MUTEX(un));
24840 	resvd_status_save = un->un_resvd_status;
24841 	un->un_resvd_status &=
24842 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
24843 	if (un->un_resvd_timeid) {
24844 		resvd_timeid_save = un->un_resvd_timeid;
24845 		un->un_resvd_timeid = NULL;
24846 		mutex_exit(SD_MUTEX(un));
24847 		(void) untimeout(resvd_timeid_save);
24848 	} else {
24849 		mutex_exit(SD_MUTEX(un));
24850 	}
24851 
24852 	/*
24853 	 * destroy any pending timeout thread that may be attempting to
24854 	 * reinstate reservation on this device.
24855 	 */
24856 	sd_rmv_resv_reclaim_req(dev);
24857 
24858 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
24859 		mutex_enter(SD_MUTEX(un));
24860 		if ((un->un_mhd_token) &&
24861 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
24862 			mutex_exit(SD_MUTEX(un));
24863 			(void) sd_check_mhd(dev, 0);
24864 		} else {
24865 			mutex_exit(SD_MUTEX(un));
24866 		}
24867 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
24868 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24869 	} else {
24870 		/*
24871 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
24872 		 */
24873 		mutex_enter(SD_MUTEX(un));
24874 		un->un_resvd_status = resvd_status_save;
24875 		mutex_exit(SD_MUTEX(un));
24876 	}
24877 	return (rval);
24878 }
24879 
24880 
24881 /*
24882  *    Function: sd_mhdioc_register_devid
24883  *
24884  * Description: This routine is the driver entry point for handling ioctl
24885  *		requests to register the device id (MHIOCREREGISTERDEVID).
24886  *
24887  *		Note: The implementation for this ioctl has been updated to
24888  *		be consistent with the original PSARC case (1999/357)
24889  *		(4375899, 4241671, 4220005)
24890  *
24891  *   Arguments: dev	- the device number
24892  *
24893  * Return Code: 0
24894  *		ENXIO
24895  */
24896 
24897 static int
24898 sd_mhdioc_register_devid(dev_t dev)
24899 {
24900 	struct sd_lun	*un = NULL;
24901 	int		rval = 0;
24902 	sd_ssc_t	*ssc;
24903 
24904 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24905 		return (ENXIO);
24906 	}
24907 
24908 	ASSERT(!mutex_owned(SD_MUTEX(un)));
24909 
24910 	mutex_enter(SD_MUTEX(un));
24911 
24912 	/* If a devid already exists, de-register it */
24913 	if (un->un_devid != NULL) {
24914 		ddi_devid_unregister(SD_DEVINFO(un));
24915 		/*
24916 		 * After unregister devid, needs to free devid memory
24917 		 */
24918 		ddi_devid_free(un->un_devid);
24919 		un->un_devid = NULL;
24920 	}
24921 
24922 	/* Check for reservation conflict */
24923 	mutex_exit(SD_MUTEX(un));
24924 	ssc = sd_ssc_init(un);
24925 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
24926 	mutex_enter(SD_MUTEX(un));
24927 
24928 	switch (rval) {
24929 	case 0:
24930 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
24931 		break;
24932 	case EACCES:
24933 		break;
24934 	default:
24935 		rval = EIO;
24936 	}
24937 
24938 	mutex_exit(SD_MUTEX(un));
24939 	if (rval != 0) {
24940 		if (rval == EIO)
24941 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24942 		else
24943 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24944 	}
24945 	sd_ssc_fini(ssc);
24946 	return (rval);
24947 }
24948 
24949 
24950 /*
24951  *    Function: sd_mhdioc_inkeys
24952  *
24953  * Description: This routine is the driver entry point for handling ioctl
24954  *		requests to issue the SCSI-3 Persistent In Read Keys command
24955  *		to the device (MHIOCGRP_INKEYS).
24956  *
24957  *   Arguments: dev	- the device number
24958  *		arg	- user provided in_keys structure
24959  *		flag	- this argument is a pass through to ddi_copyxxx()
24960  *			  directly from the mode argument of ioctl().
24961  *
24962  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
24963  *		ENXIO
24964  *		EFAULT
24965  */
24966 
24967 static int
24968 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
24969 {
24970 	struct sd_lun		*un;
24971 	mhioc_inkeys_t		inkeys;
24972 	int			rval = 0;
24973 
24974 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24975 		return (ENXIO);
24976 	}
24977 
24978 #ifdef _MULTI_DATAMODEL
24979 	switch (ddi_model_convert_from(flag & FMODELS)) {
24980 	case DDI_MODEL_ILP32: {
24981 		struct mhioc_inkeys32	inkeys32;
24982 
24983 		if (ddi_copyin(arg, &inkeys32,
24984 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
24985 			return (EFAULT);
24986 		}
24987 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
24988 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24989 		    &inkeys, flag)) != 0) {
24990 			return (rval);
24991 		}
24992 		inkeys32.generation = inkeys.generation;
24993 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
24994 		    flag) != 0) {
24995 			return (EFAULT);
24996 		}
24997 		break;
24998 	}
24999 	case DDI_MODEL_NONE:
25000 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
25001 		    flag) != 0) {
25002 			return (EFAULT);
25003 		}
25004 		if ((rval = sd_persistent_reservation_in_read_keys(un,
25005 		    &inkeys, flag)) != 0) {
25006 			return (rval);
25007 		}
25008 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
25009 		    flag) != 0) {
25010 			return (EFAULT);
25011 		}
25012 		break;
25013 	}
25014 
25015 #else /* ! _MULTI_DATAMODEL */
25016 
25017 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
25018 		return (EFAULT);
25019 	}
25020 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
25021 	if (rval != 0) {
25022 		return (rval);
25023 	}
25024 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
25025 		return (EFAULT);
25026 	}
25027 
25028 #endif /* _MULTI_DATAMODEL */
25029 
25030 	return (rval);
25031 }
25032 
25033 
25034 /*
25035  *    Function: sd_mhdioc_inresv
25036  *
25037  * Description: This routine is the driver entry point for handling ioctl
25038  *		requests to issue the SCSI-3 Persistent In Read Reservations
25039  *		command to the device (MHIOCGRP_INKEYS).
25040  *
25041  *   Arguments: dev	- the device number
25042  *		arg	- user provided in_resv structure
25043  *		flag	- this argument is a pass through to ddi_copyxxx()
25044  *			  directly from the mode argument of ioctl().
25045  *
25046  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
25047  *		ENXIO
25048  *		EFAULT
25049  */
25050 
25051 static int
25052 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
25053 {
25054 	struct sd_lun		*un;
25055 	mhioc_inresvs_t		inresvs;
25056 	int			rval = 0;
25057 
25058 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25059 		return (ENXIO);
25060 	}
25061 
25062 #ifdef _MULTI_DATAMODEL
25063 
25064 	switch (ddi_model_convert_from(flag & FMODELS)) {
25065 	case DDI_MODEL_ILP32: {
25066 		struct mhioc_inresvs32	inresvs32;
25067 
25068 		if (ddi_copyin(arg, &inresvs32,
25069 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
25070 			return (EFAULT);
25071 		}
25072 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
25073 		if ((rval = sd_persistent_reservation_in_read_resv(un,
25074 		    &inresvs, flag)) != 0) {
25075 			return (rval);
25076 		}
25077 		inresvs32.generation = inresvs.generation;
25078 		if (ddi_copyout(&inresvs32, arg,
25079 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
25080 			return (EFAULT);
25081 		}
25082 		break;
25083 	}
25084 	case DDI_MODEL_NONE:
25085 		if (ddi_copyin(arg, &inresvs,
25086 		    sizeof (mhioc_inresvs_t), flag) != 0) {
25087 			return (EFAULT);
25088 		}
25089 		if ((rval = sd_persistent_reservation_in_read_resv(un,
25090 		    &inresvs, flag)) != 0) {
25091 			return (rval);
25092 		}
25093 		if (ddi_copyout(&inresvs, arg,
25094 		    sizeof (mhioc_inresvs_t), flag) != 0) {
25095 			return (EFAULT);
25096 		}
25097 		break;
25098 	}
25099 
25100 #else /* ! _MULTI_DATAMODEL */
25101 
25102 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
25103 		return (EFAULT);
25104 	}
25105 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
25106 	if (rval != 0) {
25107 		return (rval);
25108 	}
25109 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
25110 		return (EFAULT);
25111 	}
25112 
25113 #endif /* ! _MULTI_DATAMODEL */
25114 
25115 	return (rval);
25116 }
25117 
25118 
25119 /*
25120  * The following routines support the clustering functionality described below
25121  * and implement lost reservation reclaim functionality.
25122  *
25123  * Clustering
25124  * ----------
25125  * The clustering code uses two different, independent forms of SCSI
25126  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
25127  * Persistent Group Reservations. For any particular disk, it will use either
25128  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
25129  *
25130  * SCSI-2
25131  * The cluster software takes ownership of a multi-hosted disk by issuing the
25132  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
25133  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
25134  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
25135  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
25136  * driver. The meaning of failfast is that if the driver (on this host) ever
25137  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
25138  * it should immediately panic the host. The motivation for this ioctl is that
25139  * if this host does encounter reservation conflict, the underlying cause is
25140  * that some other host of the cluster has decided that this host is no longer
25141  * in the cluster and has seized control of the disks for itself. Since this
25142  * host is no longer in the cluster, it ought to panic itself. The
25143  * MHIOCENFAILFAST ioctl does two things:
25144  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
25145  *      error to panic the host
25146  *      (b) it sets up a periodic timer to test whether this host still has
25147  *      "access" (in that no other host has reserved the device):  if the
25148  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
25149  *      purpose of that periodic timer is to handle scenarios where the host is
25150  *      otherwise temporarily quiescent, temporarily doing no real i/o.
25151  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
25152  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
25153  * the device itself.
25154  *
25155  * SCSI-3 PGR
25156  * A direct semantic implementation of the SCSI-3 Persistent Reservation
25157  * facility is supported through the shared multihost disk ioctls
25158  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
25159  * MHIOCGRP_PREEMPTANDABORT, MHIOCGRP_CLEAR)
25160  *
25161  * Reservation Reclaim:
25162  * --------------------
25163  * To support the lost reservation reclaim operations this driver creates a
25164  * single thread to handle reinstating reservations on all devices that have
25165  * lost reservations sd_resv_reclaim_requests are logged for all devices that
25166  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
25167  * and the reservation reclaim thread loops through the requests to regain the
25168  * lost reservations.
25169  */
25170 
25171 /*
25172  *    Function: sd_check_mhd()
25173  *
25174  * Description: This function sets up and submits a scsi watch request or
25175  *		terminates an existing watch request. This routine is used in
25176  *		support of reservation reclaim.
25177  *
25178  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
25179  *			 among multiple watches that share the callback function
25180  *		interval - the number of microseconds specifying the watch
25181  *			   interval for issuing TEST UNIT READY commands. If
25182  *			   set to 0 the watch should be terminated. If the
25183  *			   interval is set to 0 and if the device is required
25184  *			   to hold reservation while disabling failfast, the
25185  *			   watch is restarted with an interval of
25186  *			   reinstate_resv_delay.
25187  *
25188  * Return Code: 0	   - Successful submit/terminate of scsi watch request
25189  *		ENXIO      - Indicates an invalid device was specified
25190  *		EAGAIN     - Unable to submit the scsi watch request
25191  */
25192 
25193 static int
25194 sd_check_mhd(dev_t dev, int interval)
25195 {
25196 	struct sd_lun	*un;
25197 	opaque_t	token;
25198 
25199 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25200 		return (ENXIO);
25201 	}
25202 
25203 	/* is this a watch termination request? */
25204 	if (interval == 0) {
25205 		mutex_enter(SD_MUTEX(un));
25206 		/* if there is an existing watch task then terminate it */
25207 		if (un->un_mhd_token) {
25208 			token = un->un_mhd_token;
25209 			un->un_mhd_token = NULL;
25210 			mutex_exit(SD_MUTEX(un));
25211 			(void) scsi_watch_request_terminate(token,
25212 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
25213 			mutex_enter(SD_MUTEX(un));
25214 		} else {
25215 			mutex_exit(SD_MUTEX(un));
25216 			/*
25217 			 * Note: If we return here we don't check for the
25218 			 * failfast case. This is the original legacy
25219 			 * implementation but perhaps we should be checking
25220 			 * the failfast case.
25221 			 */
25222 			return (0);
25223 		}
25224 		/*
25225 		 * If the device is required to hold reservation while
25226 		 * disabling failfast, we need to restart the scsi_watch
25227 		 * routine with an interval of reinstate_resv_delay.
25228 		 */
25229 		if (un->un_resvd_status & SD_RESERVE) {
25230 			interval = sd_reinstate_resv_delay / 1000;
25231 		} else {
25232 			/* no failfast so bail */
25233 			mutex_exit(SD_MUTEX(un));
25234 			return (0);
25235 		}
25236 		mutex_exit(SD_MUTEX(un));
25237 	}
25238 
25239 	/*
25240 	 * adjust minimum time interval to 1 second,
25241 	 * and convert from msecs to usecs
25242 	 */
25243 	if (interval > 0 && interval < 1000) {
25244 		interval = 1000;
25245 	}
25246 	interval *= 1000;
25247 
25248 	/*
25249 	 * submit the request to the scsi_watch service
25250 	 */
25251 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
25252 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
25253 	if (token == NULL) {
25254 		return (EAGAIN);
25255 	}
25256 
25257 	/*
25258 	 * save token for termination later on
25259 	 */
25260 	mutex_enter(SD_MUTEX(un));
25261 	un->un_mhd_token = token;
25262 	mutex_exit(SD_MUTEX(un));
25263 	return (0);
25264 }
25265 
25266 
25267 /*
25268  *    Function: sd_mhd_watch_cb()
25269  *
25270  * Description: This function is the call back function used by the scsi watch
25271  *		facility. The scsi watch facility sends the "Test Unit Ready"
25272  *		and processes the status. If applicable (i.e. a "Unit Attention"
25273  *		status and automatic "Request Sense" not used) the scsi watch
25274  *		facility will send a "Request Sense" and retrieve the sense data
25275  *		to be passed to this callback function. In either case the
25276  *		automatic "Request Sense" or the facility submitting one, this
25277  *		callback is passed the status and sense data.
25278  *
25279  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25280  *			among multiple watches that share this callback function
25281  *		resultp - scsi watch facility result packet containing scsi
25282  *			  packet, status byte and sense data
25283  *
25284  * Return Code: 0 - continue the watch task
25285  *		non-zero - terminate the watch task
25286  */
25287 
25288 static int
25289 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
25290 {
25291 	struct sd_lun			*un;
25292 	struct scsi_status		*statusp;
25293 	uint8_t				*sensep;
25294 	struct scsi_pkt			*pkt;
25295 	uchar_t				actual_sense_length;
25296 	dev_t				dev = (dev_t)arg;
25297 
25298 	ASSERT(resultp != NULL);
25299 	statusp			= resultp->statusp;
25300 	sensep			= (uint8_t *)resultp->sensep;
25301 	pkt			= resultp->pkt;
25302 	actual_sense_length	= resultp->actual_sense_length;
25303 
25304 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25305 		return (ENXIO);
25306 	}
25307 
25308 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25309 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
25310 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
25311 
25312 	/* Begin processing of the status and/or sense data */
25313 	if (pkt->pkt_reason != CMD_CMPLT) {
25314 		/* Handle the incomplete packet */
25315 		sd_mhd_watch_incomplete(un, pkt);
25316 		return (0);
25317 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
25318 		if (*((unsigned char *)statusp)
25319 		    == STATUS_RESERVATION_CONFLICT) {
25320 			/*
25321 			 * Handle a reservation conflict by panicking if
25322 			 * configured for failfast or by logging the conflict
25323 			 * and updating the reservation status
25324 			 */
25325 			mutex_enter(SD_MUTEX(un));
25326 			if ((un->un_resvd_status & SD_FAILFAST) &&
25327 			    (sd_failfast_enable)) {
25328 				sd_panic_for_res_conflict(un);
25329 				/*NOTREACHED*/
25330 			}
25331 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25332 			    "sd_mhd_watch_cb: Reservation Conflict\n");
25333 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
25334 			mutex_exit(SD_MUTEX(un));
25335 		}
25336 	}
25337 
25338 	if (sensep != NULL) {
25339 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
25340 			mutex_enter(SD_MUTEX(un));
25341 			if ((scsi_sense_asc(sensep) ==
25342 			    SD_SCSI_RESET_SENSE_CODE) &&
25343 			    (un->un_resvd_status & SD_RESERVE)) {
25344 				/*
25345 				 * The additional sense code indicates a power
25346 				 * on or bus device reset has occurred; update
25347 				 * the reservation status.
25348 				 */
25349 				un->un_resvd_status |=
25350 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25351 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25352 				    "sd_mhd_watch_cb: Lost Reservation\n");
25353 			}
25354 		} else {
25355 			return (0);
25356 		}
25357 	} else {
25358 		mutex_enter(SD_MUTEX(un));
25359 	}
25360 
25361 	if ((un->un_resvd_status & SD_RESERVE) &&
25362 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
25363 		if (un->un_resvd_status & SD_WANT_RESERVE) {
25364 			/*
25365 			 * A reset occurred in between the last probe and this
25366 			 * one so if a timeout is pending cancel it.
25367 			 */
25368 			if (un->un_resvd_timeid) {
25369 				timeout_id_t temp_id = un->un_resvd_timeid;
25370 				un->un_resvd_timeid = NULL;
25371 				mutex_exit(SD_MUTEX(un));
25372 				(void) untimeout(temp_id);
25373 				mutex_enter(SD_MUTEX(un));
25374 			}
25375 			un->un_resvd_status &= ~SD_WANT_RESERVE;
25376 		}
25377 		if (un->un_resvd_timeid == 0) {
25378 			/* Schedule a timeout to handle the lost reservation */
25379 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
25380 			    (void *)dev,
25381 			    drv_usectohz(sd_reinstate_resv_delay));
25382 		}
25383 	}
25384 	mutex_exit(SD_MUTEX(un));
25385 	return (0);
25386 }
25387 
25388 
25389 /*
25390  *    Function: sd_mhd_watch_incomplete()
25391  *
25392  * Description: This function is used to find out why a scsi pkt sent by the
25393  *		scsi watch facility was not completed. Under some scenarios this
25394  *		routine will return. Otherwise it will send a bus reset to see
25395  *		if the drive is still online.
25396  *
25397  *   Arguments: un  - driver soft state (unit) structure
25398  *		pkt - incomplete scsi pkt
25399  */
25400 
25401 static void
25402 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
25403 {
25404 	int	be_chatty;
25405 	int	perr;
25406 
25407 	ASSERT(pkt != NULL);
25408 	ASSERT(un != NULL);
25409 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
25410 	perr		= (pkt->pkt_statistics & STAT_PERR);
25411 
25412 	mutex_enter(SD_MUTEX(un));
25413 	if (un->un_state == SD_STATE_DUMPING) {
25414 		mutex_exit(SD_MUTEX(un));
25415 		return;
25416 	}
25417 
25418 	switch (pkt->pkt_reason) {
25419 	case CMD_UNX_BUS_FREE:
25420 		/*
25421 		 * If we had a parity error that caused the target to drop BSY*,
25422 		 * don't be chatty about it.
25423 		 */
25424 		if (perr && be_chatty) {
25425 			be_chatty = 0;
25426 		}
25427 		break;
25428 	case CMD_TAG_REJECT:
25429 		/*
25430 		 * The SCSI-2 spec states that a tag reject will be sent by the
25431 		 * target if tagged queuing is not supported. A tag reject may
25432 		 * also be sent during certain initialization periods or to
25433 		 * control internal resources. For the latter case the target
25434 		 * may also return Queue Full.
25435 		 *
25436 		 * If this driver receives a tag reject from a target that is
25437 		 * going through an init period or controlling internal
25438 		 * resources tagged queuing will be disabled. This is a less
25439 		 * than optimal behavior but the driver is unable to determine
25440 		 * the target state and assumes tagged queueing is not supported
25441 		 */
25442 		pkt->pkt_flags = 0;
25443 		un->un_tagflags = 0;
25444 
25445 		if (un->un_f_opt_queueing == TRUE) {
25446 			un->un_throttle = min(un->un_throttle, 3);
25447 		} else {
25448 			un->un_throttle = 1;
25449 		}
25450 		mutex_exit(SD_MUTEX(un));
25451 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
25452 		mutex_enter(SD_MUTEX(un));
25453 		break;
25454 	case CMD_INCOMPLETE:
25455 		/*
25456 		 * The transport stopped with an abnormal state, fallthrough and
25457 		 * reset the target and/or bus unless selection did not complete
25458 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
25459 		 * go through a target/bus reset
25460 		 */
25461 		if (pkt->pkt_state == STATE_GOT_BUS) {
25462 			break;
25463 		}
25464 		/*FALLTHROUGH*/
25465 
25466 	case CMD_TIMEOUT:
25467 	default:
25468 		/*
25469 		 * The lun may still be running the command, so a lun reset
25470 		 * should be attempted. If the lun reset fails or cannot be
25471 		 * issued, than try a target reset. Lastly try a bus reset.
25472 		 */
25473 		if ((pkt->pkt_statistics &
25474 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0) {
25475 			int reset_retval = 0;
25476 			mutex_exit(SD_MUTEX(un));
25477 			if (un->un_f_allow_bus_device_reset == TRUE) {
25478 				if (un->un_f_lun_reset_enabled == TRUE) {
25479 					reset_retval =
25480 					    scsi_reset(SD_ADDRESS(un),
25481 					    RESET_LUN);
25482 				}
25483 				if (reset_retval == 0) {
25484 					reset_retval =
25485 					    scsi_reset(SD_ADDRESS(un),
25486 					    RESET_TARGET);
25487 				}
25488 			}
25489 			if (reset_retval == 0) {
25490 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
25491 			}
25492 			mutex_enter(SD_MUTEX(un));
25493 		}
25494 		break;
25495 	}
25496 
25497 	/* A device/bus reset has occurred; update the reservation status. */
25498 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
25499 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
25500 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25501 			un->un_resvd_status |=
25502 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25503 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25504 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
25505 		}
25506 	}
25507 
25508 	/*
25509 	 * The disk has been turned off; Update the device state.
25510 	 *
25511 	 * Note: Should we be offlining the disk here?
25512 	 */
25513 	if (pkt->pkt_state == STATE_GOT_BUS) {
25514 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
25515 		    "Disk not responding to selection\n");
25516 		if (un->un_state != SD_STATE_OFFLINE) {
25517 			New_state(un, SD_STATE_OFFLINE);
25518 		}
25519 	} else if (be_chatty) {
25520 		/*
25521 		 * suppress messages if they are all the same pkt reason;
25522 		 * with TQ, many (up to 256) are returned with the same
25523 		 * pkt_reason
25524 		 */
25525 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
25526 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25527 			    "sd_mhd_watch_incomplete: "
25528 			    "SCSI transport failed: reason '%s'\n",
25529 			    scsi_rname(pkt->pkt_reason));
25530 		}
25531 	}
25532 	un->un_last_pkt_reason = pkt->pkt_reason;
25533 	mutex_exit(SD_MUTEX(un));
25534 }
25535 
25536 
25537 /*
25538  *    Function: sd_sname()
25539  *
25540  * Description: This is a simple little routine to return a string containing
25541  *		a printable description of command status byte for use in
25542  *		logging.
25543  *
25544  *   Arguments: status - pointer to a status byte
25545  *
25546  * Return Code: char * - string containing status description.
25547  */
25548 
25549 static char *
25550 sd_sname(uchar_t status)
25551 {
25552 	switch (status & STATUS_MASK) {
25553 	case STATUS_GOOD:
25554 		return ("good status");
25555 	case STATUS_CHECK:
25556 		return ("check condition");
25557 	case STATUS_MET:
25558 		return ("condition met");
25559 	case STATUS_BUSY:
25560 		return ("busy");
25561 	case STATUS_INTERMEDIATE:
25562 		return ("intermediate");
25563 	case STATUS_INTERMEDIATE_MET:
25564 		return ("intermediate - condition met");
25565 	case STATUS_RESERVATION_CONFLICT:
25566 		return ("reservation_conflict");
25567 	case STATUS_TERMINATED:
25568 		return ("command terminated");
25569 	case STATUS_QFULL:
25570 		return ("queue full");
25571 	default:
25572 		return ("<unknown status>");
25573 	}
25574 }
25575 
25576 
25577 /*
25578  *    Function: sd_mhd_resvd_recover()
25579  *
25580  * Description: This function adds a reservation entry to the
25581  *		sd_resv_reclaim_request list and signals the reservation
25582  *		reclaim thread that there is work pending. If the reservation
25583  *		reclaim thread has not been previously created this function
25584  *		will kick it off.
25585  *
25586  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25587  *			among multiple watches that share this callback function
25588  *
25589  *     Context: This routine is called by timeout() and is run in interrupt
25590  *		context. It must not sleep or call other functions which may
25591  *		sleep.
25592  */
25593 
25594 static void
25595 sd_mhd_resvd_recover(void *arg)
25596 {
25597 	dev_t			dev = (dev_t)arg;
25598 	struct sd_lun		*un;
25599 	struct sd_thr_request	*sd_treq = NULL;
25600 	struct sd_thr_request	*sd_cur = NULL;
25601 	struct sd_thr_request	*sd_prev = NULL;
25602 	int			already_there = 0;
25603 
25604 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25605 		return;
25606 	}
25607 
25608 	mutex_enter(SD_MUTEX(un));
25609 	un->un_resvd_timeid = NULL;
25610 	if (un->un_resvd_status & SD_WANT_RESERVE) {
25611 		/*
25612 		 * There was a reset so don't issue the reserve, allow the
25613 		 * sd_mhd_watch_cb callback function to notice this and
25614 		 * reschedule the timeout for reservation.
25615 		 */
25616 		mutex_exit(SD_MUTEX(un));
25617 		return;
25618 	}
25619 	mutex_exit(SD_MUTEX(un));
25620 
25621 	/*
25622 	 * Add this device to the sd_resv_reclaim_request list and the
25623 	 * sd_resv_reclaim_thread should take care of the rest.
25624 	 *
25625 	 * Note: We can't sleep in this context so if the memory allocation
25626 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
25627 	 * reschedule the timeout for reservation.  (4378460)
25628 	 */
25629 	sd_treq = (struct sd_thr_request *)
25630 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
25631 	if (sd_treq == NULL) {
25632 		return;
25633 	}
25634 
25635 	sd_treq->sd_thr_req_next = NULL;
25636 	sd_treq->dev = dev;
25637 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25638 	if (sd_tr.srq_thr_req_head == NULL) {
25639 		sd_tr.srq_thr_req_head = sd_treq;
25640 	} else {
25641 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
25642 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
25643 			if (sd_cur->dev == dev) {
25644 				/*
25645 				 * already in Queue so don't log
25646 				 * another request for the device
25647 				 */
25648 				already_there = 1;
25649 				break;
25650 			}
25651 			sd_prev = sd_cur;
25652 		}
25653 		if (!already_there) {
25654 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
25655 			    "logging request for %lx\n", dev);
25656 			sd_prev->sd_thr_req_next = sd_treq;
25657 		} else {
25658 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
25659 		}
25660 	}
25661 
25662 	/*
25663 	 * Create a kernel thread to do the reservation reclaim and free up this
25664 	 * thread. We cannot block this thread while we go away to do the
25665 	 * reservation reclaim
25666 	 */
25667 	if (sd_tr.srq_resv_reclaim_thread == NULL)
25668 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
25669 		    sd_resv_reclaim_thread, NULL,
25670 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
25671 
25672 	/* Tell the reservation reclaim thread that it has work to do */
25673 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
25674 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25675 }
25676 
25677 /*
25678  *    Function: sd_resv_reclaim_thread()
25679  *
25680  * Description: This function implements the reservation reclaim operations
25681  *
25682  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
25683  *		      among multiple watches that share this callback function
25684  */
25685 
25686 static void
25687 sd_resv_reclaim_thread()
25688 {
25689 	struct sd_lun		*un;
25690 	struct sd_thr_request	*sd_mhreq;
25691 
25692 	/* Wait for work */
25693 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25694 	if (sd_tr.srq_thr_req_head == NULL) {
25695 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
25696 		    &sd_tr.srq_resv_reclaim_mutex);
25697 	}
25698 
25699 	/* Loop while we have work */
25700 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
25701 		un = ddi_get_soft_state(sd_state,
25702 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
25703 		if (un == NULL) {
25704 			/*
25705 			 * softstate structure is NULL so just
25706 			 * dequeue the request and continue
25707 			 */
25708 			sd_tr.srq_thr_req_head =
25709 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25710 			kmem_free(sd_tr.srq_thr_cur_req,
25711 			    sizeof (struct sd_thr_request));
25712 			continue;
25713 		}
25714 
25715 		/* dequeue the request */
25716 		sd_mhreq = sd_tr.srq_thr_cur_req;
25717 		sd_tr.srq_thr_req_head =
25718 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25719 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25720 
25721 		/*
25722 		 * Reclaim reservation only if SD_RESERVE is still set. There
25723 		 * may have been a call to MHIOCRELEASE before we got here.
25724 		 */
25725 		mutex_enter(SD_MUTEX(un));
25726 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25727 			/*
25728 			 * Note: The SD_LOST_RESERVE flag is cleared before
25729 			 * reclaiming the reservation. If this is done after the
25730 			 * call to sd_reserve_release a reservation loss in the
25731 			 * window between pkt completion of reserve cmd and
25732 			 * mutex_enter below may not be recognized
25733 			 */
25734 			un->un_resvd_status &= ~SD_LOST_RESERVE;
25735 			mutex_exit(SD_MUTEX(un));
25736 
25737 			if (sd_reserve_release(sd_mhreq->dev,
25738 			    SD_RESERVE) == 0) {
25739 				mutex_enter(SD_MUTEX(un));
25740 				un->un_resvd_status |= SD_RESERVE;
25741 				mutex_exit(SD_MUTEX(un));
25742 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25743 				    "sd_resv_reclaim_thread: "
25744 				    "Reservation Recovered\n");
25745 			} else {
25746 				mutex_enter(SD_MUTEX(un));
25747 				un->un_resvd_status |= SD_LOST_RESERVE;
25748 				mutex_exit(SD_MUTEX(un));
25749 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25750 				    "sd_resv_reclaim_thread: Failed "
25751 				    "Reservation Recovery\n");
25752 			}
25753 		} else {
25754 			mutex_exit(SD_MUTEX(un));
25755 		}
25756 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25757 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
25758 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25759 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
25760 		/*
25761 		 * wakeup the destroy thread if anyone is waiting on
25762 		 * us to complete.
25763 		 */
25764 		cv_signal(&sd_tr.srq_inprocess_cv);
25765 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
25766 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
25767 	}
25768 
25769 	/*
25770 	 * cleanup the sd_tr structure now that this thread will not exist
25771 	 */
25772 	ASSERT(sd_tr.srq_thr_req_head == NULL);
25773 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
25774 	sd_tr.srq_resv_reclaim_thread = NULL;
25775 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25776 	thread_exit();
25777 }
25778 
25779 
25780 /*
25781  *    Function: sd_rmv_resv_reclaim_req()
25782  *
25783  * Description: This function removes any pending reservation reclaim requests
25784  *		for the specified device.
25785  *
25786  *   Arguments: dev - the device 'dev_t'
25787  */
25788 
25789 static void
25790 sd_rmv_resv_reclaim_req(dev_t dev)
25791 {
25792 	struct sd_thr_request *sd_mhreq;
25793 	struct sd_thr_request *sd_prev;
25794 
25795 	/* Remove a reservation reclaim request from the list */
25796 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25797 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
25798 		/*
25799 		 * We are attempting to reinstate reservation for
25800 		 * this device. We wait for sd_reserve_release()
25801 		 * to return before we return.
25802 		 */
25803 		cv_wait(&sd_tr.srq_inprocess_cv,
25804 		    &sd_tr.srq_resv_reclaim_mutex);
25805 	} else {
25806 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
25807 		if (sd_mhreq && sd_mhreq->dev == dev) {
25808 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
25809 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25810 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25811 			return;
25812 		}
25813 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
25814 			if (sd_mhreq && sd_mhreq->dev == dev) {
25815 				break;
25816 			}
25817 			sd_prev = sd_mhreq;
25818 		}
25819 		if (sd_mhreq != NULL) {
25820 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
25821 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25822 		}
25823 	}
25824 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25825 }
25826 
25827 
25828 /*
25829  *    Function: sd_mhd_reset_notify_cb()
25830  *
25831  * Description: This is a call back function for scsi_reset_notify. This
25832  *		function updates the softstate reserved status and logs the
25833  *		reset. The driver scsi watch facility callback function
25834  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
25835  *		will reclaim the reservation.
25836  *
25837  *   Arguments: arg  - driver soft state (unit) structure
25838  */
25839 
25840 static void
25841 sd_mhd_reset_notify_cb(caddr_t arg)
25842 {
25843 	struct sd_lun *un = (struct sd_lun *)arg;
25844 
25845 	mutex_enter(SD_MUTEX(un));
25846 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25847 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
25848 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25849 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
25850 	}
25851 	mutex_exit(SD_MUTEX(un));
25852 }
25853 
25854 
25855 /*
25856  *    Function: sd_take_ownership()
25857  *
25858  * Description: This routine implements an algorithm to achieve a stable
25859  *		reservation on disks which don't implement priority reserve,
25860  *		and makes sure that other host lose re-reservation attempts.
25861  *		This algorithm contains of a loop that keeps issuing the RESERVE
25862  *		for some period of time (min_ownership_delay, default 6 seconds)
25863  *		During that loop, it looks to see if there has been a bus device
25864  *		reset or bus reset (both of which cause an existing reservation
25865  *		to be lost). If the reservation is lost issue RESERVE until a
25866  *		period of min_ownership_delay with no resets has gone by, or
25867  *		until max_ownership_delay has expired. This loop ensures that
25868  *		the host really did manage to reserve the device, in spite of
25869  *		resets. The looping for min_ownership_delay (default six
25870  *		seconds) is important to early generation clustering products,
25871  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
25872  *		MHIOCENFAILFAST periodic timer of two seconds. By having
25873  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
25874  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
25875  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
25876  *		have already noticed, via the MHIOCENFAILFAST polling, that it
25877  *		no longer "owns" the disk and will have panicked itself.  Thus,
25878  *		the host issuing the MHIOCTKOWN is assured (with timing
25879  *		dependencies) that by the time it actually starts to use the
25880  *		disk for real work, the old owner is no longer accessing it.
25881  *
25882  *		min_ownership_delay is the minimum amount of time for which the
25883  *		disk must be reserved continuously devoid of resets before the
25884  *		MHIOCTKOWN ioctl will return success.
25885  *
25886  *		max_ownership_delay indicates the amount of time by which the
25887  *		take ownership should succeed or timeout with an error.
25888  *
25889  *   Arguments: dev - the device 'dev_t'
25890  *		*p  - struct containing timing info.
25891  *
25892  * Return Code: 0 for success or error code
25893  */
25894 
25895 static int
25896 sd_take_ownership(dev_t dev, struct mhioctkown *p)
25897 {
25898 	struct sd_lun	*un;
25899 	int		rval;
25900 	int		err;
25901 	int		reservation_count   = 0;
25902 	int		min_ownership_delay =  6000000; /* in usec */
25903 	int		max_ownership_delay = 30000000; /* in usec */
25904 	clock_t		start_time;	/* starting time of this algorithm */
25905 	clock_t		end_time;	/* time limit for giving up */
25906 	clock_t		ownership_time;	/* time limit for stable ownership */
25907 	clock_t		current_time;
25908 	clock_t		previous_current_time;
25909 
25910 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25911 		return (ENXIO);
25912 	}
25913 
25914 	/*
25915 	 * Attempt a device reservation. A priority reservation is requested.
25916 	 */
25917 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
25918 	    != SD_SUCCESS) {
25919 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25920 		    "sd_take_ownership: return(1)=%d\n", rval);
25921 		return (rval);
25922 	}
25923 
25924 	/* Update the softstate reserved status to indicate the reservation */
25925 	mutex_enter(SD_MUTEX(un));
25926 	un->un_resvd_status |= SD_RESERVE;
25927 	un->un_resvd_status &=
25928 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
25929 	mutex_exit(SD_MUTEX(un));
25930 
25931 	if (p != NULL) {
25932 		if (p->min_ownership_delay != 0) {
25933 			min_ownership_delay = p->min_ownership_delay * 1000;
25934 		}
25935 		if (p->max_ownership_delay != 0) {
25936 			max_ownership_delay = p->max_ownership_delay * 1000;
25937 		}
25938 	}
25939 	SD_INFO(SD_LOG_IOCTL_MHD, un,
25940 	    "sd_take_ownership: min, max delays: %d, %d\n",
25941 	    min_ownership_delay, max_ownership_delay);
25942 
25943 	start_time = ddi_get_lbolt();
25944 	current_time	= start_time;
25945 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
25946 	end_time	= start_time + drv_usectohz(max_ownership_delay);
25947 
25948 	while (current_time - end_time < 0) {
25949 		delay(drv_usectohz(500000));
25950 
25951 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
25952 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
25953 				mutex_enter(SD_MUTEX(un));
25954 				rval = (un->un_resvd_status &
25955 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
25956 				mutex_exit(SD_MUTEX(un));
25957 				break;
25958 			}
25959 		}
25960 		previous_current_time = current_time;
25961 		current_time = ddi_get_lbolt();
25962 		mutex_enter(SD_MUTEX(un));
25963 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
25964 			ownership_time = ddi_get_lbolt() +
25965 			    drv_usectohz(min_ownership_delay);
25966 			reservation_count = 0;
25967 		} else {
25968 			reservation_count++;
25969 		}
25970 		un->un_resvd_status |= SD_RESERVE;
25971 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
25972 		mutex_exit(SD_MUTEX(un));
25973 
25974 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25975 		    "sd_take_ownership: ticks for loop iteration=%ld, "
25976 		    "reservation=%s\n", (current_time - previous_current_time),
25977 		    reservation_count ? "ok" : "reclaimed");
25978 
25979 		if (current_time - ownership_time >= 0 &&
25980 		    reservation_count >= 4) {
25981 			rval = 0; /* Achieved a stable ownership */
25982 			break;
25983 		}
25984 		if (current_time - end_time >= 0) {
25985 			rval = EACCES; /* No ownership in max possible time */
25986 			break;
25987 		}
25988 	}
25989 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25990 	    "sd_take_ownership: return(2)=%d\n", rval);
25991 	return (rval);
25992 }
25993 
25994 
25995 /*
25996  *    Function: sd_reserve_release()
25997  *
25998  * Description: This function builds and sends scsi RESERVE, RELEASE, and
25999  *		PRIORITY RESERVE commands based on a user specified command type
26000  *
26001  *   Arguments: dev - the device 'dev_t'
26002  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
26003  *		      SD_RESERVE, SD_RELEASE
26004  *
26005  * Return Code: 0 or Error Code
26006  */
26007 
26008 static int
26009 sd_reserve_release(dev_t dev, int cmd)
26010 {
26011 	struct uscsi_cmd	*com = NULL;
26012 	struct sd_lun		*un = NULL;
26013 	char			cdb[CDB_GROUP0];
26014 	int			rval;
26015 
26016 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
26017 	    (cmd == SD_PRIORITY_RESERVE));
26018 
26019 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26020 		return (ENXIO);
26021 	}
26022 
26023 	/* instantiate and initialize the command and cdb */
26024 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26025 	bzero(cdb, CDB_GROUP0);
26026 	com->uscsi_flags   = USCSI_SILENT;
26027 	com->uscsi_timeout = un->un_reserve_release_time;
26028 	com->uscsi_cdblen  = CDB_GROUP0;
26029 	com->uscsi_cdb	   = cdb;
26030 	if (cmd == SD_RELEASE) {
26031 		cdb[0] = SCMD_RELEASE;
26032 	} else {
26033 		cdb[0] = SCMD_RESERVE;
26034 	}
26035 
26036 	/* Send the command. */
26037 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26038 	    SD_PATH_STANDARD);
26039 
26040 	/*
26041 	 * "break" a reservation that is held by another host, by issuing a
26042 	 * reset if priority reserve is desired, and we could not get the
26043 	 * device.
26044 	 */
26045 	if ((cmd == SD_PRIORITY_RESERVE) &&
26046 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
26047 		/*
26048 		 * First try to reset the LUN. If we cannot, then try a target
26049 		 * reset, followed by a bus reset if the target reset fails.
26050 		 */
26051 		int reset_retval = 0;
26052 		if (un->un_f_lun_reset_enabled == TRUE) {
26053 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
26054 		}
26055 		if (reset_retval == 0) {
26056 			/* The LUN reset either failed or was not issued */
26057 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26058 		}
26059 		if ((reset_retval == 0) &&
26060 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
26061 			rval = EIO;
26062 			kmem_free(com, sizeof (*com));
26063 			return (rval);
26064 		}
26065 
26066 		bzero(com, sizeof (struct uscsi_cmd));
26067 		com->uscsi_flags   = USCSI_SILENT;
26068 		com->uscsi_cdb	   = cdb;
26069 		com->uscsi_cdblen  = CDB_GROUP0;
26070 		com->uscsi_timeout = 5;
26071 
26072 		/*
26073 		 * Reissue the last reserve command, this time without request
26074 		 * sense.  Assume that it is just a regular reserve command.
26075 		 */
26076 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26077 		    SD_PATH_STANDARD);
26078 	}
26079 
26080 	/* Return an error if still getting a reservation conflict. */
26081 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
26082 		rval = EACCES;
26083 	}
26084 
26085 	kmem_free(com, sizeof (*com));
26086 	return (rval);
26087 }
26088 
26089 
26090 #define	SD_NDUMP_RETRIES	12
26091 /*
26092  *	System Crash Dump routine
26093  */
26094 
26095 static int
26096 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
26097 {
26098 	int		instance;
26099 	int		partition;
26100 	int		i;
26101 	int		err;
26102 	struct sd_lun	*un;
26103 	struct scsi_pkt *wr_pktp;
26104 	struct buf	*wr_bp;
26105 	struct buf	wr_buf;
26106 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
26107 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
26108 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
26109 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
26110 	size_t		io_start_offset;
26111 	int		doing_rmw = FALSE;
26112 	int		rval;
26113 	ssize_t		dma_resid;
26114 	daddr_t		oblkno;
26115 	diskaddr_t	nblks = 0;
26116 	diskaddr_t	start_block;
26117 
26118 	instance = SDUNIT(dev);
26119 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
26120 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
26121 		return (ENXIO);
26122 	}
26123 
26124 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
26125 
26126 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
26127 
26128 	partition = SDPART(dev);
26129 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
26130 
26131 	if (!(NOT_DEVBSIZE(un))) {
26132 		int secmask = 0;
26133 		int blknomask = 0;
26134 
26135 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
26136 		secmask = un->un_tgt_blocksize - 1;
26137 
26138 		if (blkno & blknomask) {
26139 			SD_TRACE(SD_LOG_DUMP, un,
26140 			    "sddump: dump start block not modulo %d\n",
26141 			    un->un_tgt_blocksize);
26142 			return (EINVAL);
26143 		}
26144 
26145 		if ((nblk * DEV_BSIZE) & secmask) {
26146 			SD_TRACE(SD_LOG_DUMP, un,
26147 			    "sddump: dump length not modulo %d\n",
26148 			    un->un_tgt_blocksize);
26149 			return (EINVAL);
26150 		}
26151 
26152 	}
26153 
26154 	/* Validate blocks to dump at against partition size. */
26155 
26156 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
26157 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
26158 
26159 	if (NOT_DEVBSIZE(un)) {
26160 		if ((blkno + nblk) > nblks) {
26161 			SD_TRACE(SD_LOG_DUMP, un,
26162 			    "sddump: dump range larger than partition: "
26163 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
26164 			    blkno, nblk, nblks);
26165 			return (EINVAL);
26166 		}
26167 	} else {
26168 		if (((blkno / (un->un_tgt_blocksize / DEV_BSIZE)) +
26169 		    (nblk / (un->un_tgt_blocksize / DEV_BSIZE))) > nblks) {
26170 			SD_TRACE(SD_LOG_DUMP, un,
26171 			    "sddump: dump range larger than partition: "
26172 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
26173 			    blkno, nblk, nblks);
26174 			return (EINVAL);
26175 		}
26176 	}
26177 
26178 	mutex_enter(&un->un_pm_mutex);
26179 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
26180 		struct scsi_pkt *start_pktp;
26181 
26182 		mutex_exit(&un->un_pm_mutex);
26183 
26184 		/*
26185 		 * use pm framework to power on HBA 1st
26186 		 */
26187 		(void) pm_raise_power(SD_DEVINFO(un), 0,
26188 		    SD_PM_STATE_ACTIVE(un));
26189 
26190 		/*
26191 		 * Dump no long uses sdpower to power on a device, it's
26192 		 * in-line here so it can be done in polled mode.
26193 		 */
26194 
26195 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
26196 
26197 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
26198 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
26199 
26200 		if (start_pktp == NULL) {
26201 			/* We were not given a SCSI packet, fail. */
26202 			return (EIO);
26203 		}
26204 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
26205 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
26206 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
26207 		start_pktp->pkt_flags = FLAG_NOINTR;
26208 
26209 		mutex_enter(SD_MUTEX(un));
26210 		SD_FILL_SCSI1_LUN(un, start_pktp);
26211 		mutex_exit(SD_MUTEX(un));
26212 		/*
26213 		 * Scsi_poll returns 0 (success) if the command completes and
26214 		 * the status block is STATUS_GOOD.
26215 		 */
26216 		if (sd_scsi_poll(un, start_pktp) != 0) {
26217 			scsi_destroy_pkt(start_pktp);
26218 			return (EIO);
26219 		}
26220 		scsi_destroy_pkt(start_pktp);
26221 		(void) sd_pm_state_change(un, SD_PM_STATE_ACTIVE(un),
26222 		    SD_PM_STATE_CHANGE);
26223 	} else {
26224 		mutex_exit(&un->un_pm_mutex);
26225 	}
26226 
26227 	mutex_enter(SD_MUTEX(un));
26228 	un->un_throttle = 0;
26229 
26230 	/*
26231 	 * The first time through, reset the specific target device.
26232 	 * However, when cpr calls sddump we know that sd is in a
26233 	 * a good state so no bus reset is required.
26234 	 * Clear sense data via Request Sense cmd.
26235 	 * In sddump we don't care about allow_bus_device_reset anymore
26236 	 */
26237 
26238 	if ((un->un_state != SD_STATE_SUSPENDED) &&
26239 	    (un->un_state != SD_STATE_DUMPING)) {
26240 
26241 		New_state(un, SD_STATE_DUMPING);
26242 
26243 		if (un->un_f_is_fibre == FALSE) {
26244 			mutex_exit(SD_MUTEX(un));
26245 			/*
26246 			 * Attempt a bus reset for parallel scsi.
26247 			 *
26248 			 * Note: A bus reset is required because on some host
26249 			 * systems (i.e. E420R) a bus device reset is
26250 			 * insufficient to reset the state of the target.
26251 			 *
26252 			 * Note: Don't issue the reset for fibre-channel,
26253 			 * because this tends to hang the bus (loop) for
26254 			 * too long while everyone is logging out and in
26255 			 * and the deadman timer for dumping will fire
26256 			 * before the dump is complete.
26257 			 */
26258 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
26259 				mutex_enter(SD_MUTEX(un));
26260 				Restore_state(un);
26261 				mutex_exit(SD_MUTEX(un));
26262 				return (EIO);
26263 			}
26264 
26265 			/* Delay to give the device some recovery time. */
26266 			drv_usecwait(10000);
26267 
26268 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
26269 				SD_INFO(SD_LOG_DUMP, un,
26270 				    "sddump: sd_send_polled_RQS failed\n");
26271 			}
26272 			mutex_enter(SD_MUTEX(un));
26273 		}
26274 	}
26275 
26276 	/*
26277 	 * Convert the partition-relative block number to a
26278 	 * disk physical block number.
26279 	 */
26280 	if (NOT_DEVBSIZE(un)) {
26281 		blkno += start_block;
26282 	} else {
26283 		blkno = blkno / (un->un_tgt_blocksize / DEV_BSIZE);
26284 		blkno += start_block;
26285 	}
26286 
26287 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
26288 
26289 
26290 	/*
26291 	 * Check if the device has a non-512 block size.
26292 	 */
26293 	wr_bp = NULL;
26294 	if (NOT_DEVBSIZE(un)) {
26295 		tgt_byte_offset = blkno * un->un_sys_blocksize;
26296 		tgt_byte_count = nblk * un->un_sys_blocksize;
26297 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
26298 		    (tgt_byte_count % un->un_tgt_blocksize)) {
26299 			doing_rmw = TRUE;
26300 			/*
26301 			 * Calculate the block number and number of block
26302 			 * in terms of the media block size.
26303 			 */
26304 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26305 			tgt_nblk =
26306 			    ((tgt_byte_offset + tgt_byte_count +
26307 			    (un->un_tgt_blocksize - 1)) /
26308 			    un->un_tgt_blocksize) - tgt_blkno;
26309 
26310 			/*
26311 			 * Invoke the routine which is going to do read part
26312 			 * of read-modify-write.
26313 			 * Note that this routine returns a pointer to
26314 			 * a valid bp in wr_bp.
26315 			 */
26316 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
26317 			    &wr_bp);
26318 			if (err) {
26319 				mutex_exit(SD_MUTEX(un));
26320 				return (err);
26321 			}
26322 			/*
26323 			 * Offset is being calculated as -
26324 			 * (original block # * system block size) -
26325 			 * (new block # * target block size)
26326 			 */
26327 			io_start_offset =
26328 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
26329 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
26330 
26331 			ASSERT(io_start_offset < un->un_tgt_blocksize);
26332 			/*
26333 			 * Do the modify portion of read modify write.
26334 			 */
26335 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
26336 			    (size_t)nblk * un->un_sys_blocksize);
26337 		} else {
26338 			doing_rmw = FALSE;
26339 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26340 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
26341 		}
26342 
26343 		/* Convert blkno and nblk to target blocks */
26344 		blkno = tgt_blkno;
26345 		nblk = tgt_nblk;
26346 	} else {
26347 		wr_bp = &wr_buf;
26348 		bzero(wr_bp, sizeof (struct buf));
26349 		wr_bp->b_flags		= B_BUSY;
26350 		wr_bp->b_un.b_addr	= addr;
26351 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
26352 		wr_bp->b_resid		= 0;
26353 	}
26354 
26355 	mutex_exit(SD_MUTEX(un));
26356 
26357 	/*
26358 	 * Obtain a SCSI packet for the write command.
26359 	 * It should be safe to call the allocator here without
26360 	 * worrying about being locked for DVMA mapping because
26361 	 * the address we're passed is already a DVMA mapping
26362 	 *
26363 	 * We are also not going to worry about semaphore ownership
26364 	 * in the dump buffer. Dumping is single threaded at present.
26365 	 */
26366 
26367 	wr_pktp = NULL;
26368 
26369 	dma_resid = wr_bp->b_bcount;
26370 	oblkno = blkno;
26371 
26372 	if (!(NOT_DEVBSIZE(un))) {
26373 		nblk = nblk / (un->un_tgt_blocksize / DEV_BSIZE);
26374 	}
26375 
26376 	while (dma_resid != 0) {
26377 
26378 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26379 		wr_bp->b_flags &= ~B_ERROR;
26380 
26381 		if (un->un_partial_dma_supported == 1) {
26382 			blkno = oblkno +
26383 			    ((wr_bp->b_bcount - dma_resid) /
26384 			    un->un_tgt_blocksize);
26385 			nblk = dma_resid / un->un_tgt_blocksize;
26386 
26387 			if (wr_pktp) {
26388 				/*
26389 				 * Partial DMA transfers after initial transfer
26390 				 */
26391 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
26392 				    blkno, nblk);
26393 			} else {
26394 				/* Initial transfer */
26395 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26396 				    un->un_pkt_flags, NULL_FUNC, NULL,
26397 				    blkno, nblk);
26398 			}
26399 		} else {
26400 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26401 			    0, NULL_FUNC, NULL, blkno, nblk);
26402 		}
26403 
26404 		if (rval == 0) {
26405 			/* We were given a SCSI packet, continue. */
26406 			break;
26407 		}
26408 
26409 		if (i == 0) {
26410 			if (wr_bp->b_flags & B_ERROR) {
26411 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26412 				    "no resources for dumping; "
26413 				    "error code: 0x%x, retrying",
26414 				    geterror(wr_bp));
26415 			} else {
26416 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26417 				    "no resources for dumping; retrying");
26418 			}
26419 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
26420 			if (wr_bp->b_flags & B_ERROR) {
26421 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26422 				    "no resources for dumping; error code: "
26423 				    "0x%x, retrying\n", geterror(wr_bp));
26424 			}
26425 		} else {
26426 			if (wr_bp->b_flags & B_ERROR) {
26427 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26428 				    "no resources for dumping; "
26429 				    "error code: 0x%x, retries failed, "
26430 				    "giving up.\n", geterror(wr_bp));
26431 			} else {
26432 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26433 				    "no resources for dumping; "
26434 				    "retries failed, giving up.\n");
26435 			}
26436 			mutex_enter(SD_MUTEX(un));
26437 			Restore_state(un);
26438 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
26439 				mutex_exit(SD_MUTEX(un));
26440 				scsi_free_consistent_buf(wr_bp);
26441 			} else {
26442 				mutex_exit(SD_MUTEX(un));
26443 			}
26444 			return (EIO);
26445 		}
26446 		drv_usecwait(10000);
26447 	}
26448 
26449 	if (un->un_partial_dma_supported == 1) {
26450 		/*
26451 		 * save the resid from PARTIAL_DMA
26452 		 */
26453 		dma_resid = wr_pktp->pkt_resid;
26454 		if (dma_resid != 0)
26455 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
26456 		wr_pktp->pkt_resid = 0;
26457 	} else {
26458 		dma_resid = 0;
26459 	}
26460 
26461 	/* SunBug 1222170 */
26462 	wr_pktp->pkt_flags = FLAG_NOINTR;
26463 
26464 	err = EIO;
26465 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26466 
26467 		/*
26468 		 * Scsi_poll returns 0 (success) if the command completes and
26469 		 * the status block is STATUS_GOOD.  We should only check
26470 		 * errors if this condition is not true.  Even then we should
26471 		 * send our own request sense packet only if we have a check
26472 		 * condition and auto request sense has not been performed by
26473 		 * the hba.
26474 		 */
26475 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
26476 
26477 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
26478 		    (wr_pktp->pkt_resid == 0)) {
26479 			err = SD_SUCCESS;
26480 			break;
26481 		}
26482 
26483 		/*
26484 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
26485 		 */
26486 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
26487 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26488 			    "Error while dumping state...Device is gone\n");
26489 			break;
26490 		}
26491 
26492 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
26493 			SD_INFO(SD_LOG_DUMP, un,
26494 			    "sddump: write failed with CHECK, try # %d\n", i);
26495 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
26496 				(void) sd_send_polled_RQS(un);
26497 			}
26498 
26499 			continue;
26500 		}
26501 
26502 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
26503 			int reset_retval = 0;
26504 
26505 			SD_INFO(SD_LOG_DUMP, un,
26506 			    "sddump: write failed with BUSY, try # %d\n", i);
26507 
26508 			if (un->un_f_lun_reset_enabled == TRUE) {
26509 				reset_retval = scsi_reset(SD_ADDRESS(un),
26510 				    RESET_LUN);
26511 			}
26512 			if (reset_retval == 0) {
26513 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26514 			}
26515 			(void) sd_send_polled_RQS(un);
26516 
26517 		} else {
26518 			SD_INFO(SD_LOG_DUMP, un,
26519 			    "sddump: write failed with 0x%x, try # %d\n",
26520 			    SD_GET_PKT_STATUS(wr_pktp), i);
26521 			mutex_enter(SD_MUTEX(un));
26522 			sd_reset_target(un, wr_pktp);
26523 			mutex_exit(SD_MUTEX(un));
26524 		}
26525 
26526 		/*
26527 		 * If we are not getting anywhere with lun/target resets,
26528 		 * let's reset the bus.
26529 		 */
26530 		if (i == SD_NDUMP_RETRIES / 2) {
26531 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26532 			(void) sd_send_polled_RQS(un);
26533 		}
26534 	}
26535 	}
26536 
26537 	scsi_destroy_pkt(wr_pktp);
26538 	mutex_enter(SD_MUTEX(un));
26539 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
26540 		mutex_exit(SD_MUTEX(un));
26541 		scsi_free_consistent_buf(wr_bp);
26542 	} else {
26543 		mutex_exit(SD_MUTEX(un));
26544 	}
26545 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
26546 	return (err);
26547 }
26548 
26549 /*
26550  *    Function: sd_scsi_poll()
26551  *
26552  * Description: This is a wrapper for the scsi_poll call.
26553  *
26554  *   Arguments: sd_lun - The unit structure
26555  *              scsi_pkt - The scsi packet being sent to the device.
26556  *
26557  * Return Code: 0 - Command completed successfully with good status
26558  *             -1 - Command failed.  This could indicate a check condition
26559  *                  or other status value requiring recovery action.
26560  *
26561  * NOTE: This code is only called off sddump().
26562  */
26563 
26564 static int
26565 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
26566 {
26567 	int status;
26568 
26569 	ASSERT(un != NULL);
26570 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26571 	ASSERT(pktp != NULL);
26572 
26573 	status = SD_SUCCESS;
26574 
26575 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
26576 		pktp->pkt_flags |= un->un_tagflags;
26577 		pktp->pkt_flags &= ~FLAG_NODISCON;
26578 	}
26579 
26580 	status = sd_ddi_scsi_poll(pktp);
26581 	/*
26582 	 * Scsi_poll returns 0 (success) if the command completes and the
26583 	 * status block is STATUS_GOOD.  We should only check errors if this
26584 	 * condition is not true.  Even then we should send our own request
26585 	 * sense packet only if we have a check condition and auto
26586 	 * request sense has not been performed by the hba.
26587 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
26588 	 */
26589 	if ((status != SD_SUCCESS) &&
26590 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
26591 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
26592 	    (pktp->pkt_reason != CMD_DEV_GONE))
26593 		(void) sd_send_polled_RQS(un);
26594 
26595 	return (status);
26596 }
26597 
26598 /*
26599  *    Function: sd_send_polled_RQS()
26600  *
26601  * Description: This sends the request sense command to a device.
26602  *
26603  *   Arguments: sd_lun - The unit structure
26604  *
26605  * Return Code: 0 - Command completed successfully with good status
26606  *             -1 - Command failed.
26607  *
26608  */
26609 
26610 static int
26611 sd_send_polled_RQS(struct sd_lun *un)
26612 {
26613 	int	ret_val;
26614 	struct	scsi_pkt	*rqs_pktp;
26615 	struct	buf		*rqs_bp;
26616 
26617 	ASSERT(un != NULL);
26618 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26619 
26620 	ret_val = SD_SUCCESS;
26621 
26622 	rqs_pktp = un->un_rqs_pktp;
26623 	rqs_bp	 = un->un_rqs_bp;
26624 
26625 	mutex_enter(SD_MUTEX(un));
26626 
26627 	if (un->un_sense_isbusy) {
26628 		ret_val = SD_FAILURE;
26629 		mutex_exit(SD_MUTEX(un));
26630 		return (ret_val);
26631 	}
26632 
26633 	/*
26634 	 * If the request sense buffer (and packet) is not in use,
26635 	 * let's set the un_sense_isbusy and send our packet
26636 	 */
26637 	un->un_sense_isbusy = 1;
26638 	rqs_pktp->pkt_resid = 0;
26639 	rqs_pktp->pkt_reason = 0;
26640 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
26641 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
26642 
26643 	mutex_exit(SD_MUTEX(un));
26644 
26645 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
26646 	    " 0x%p\n", rqs_bp->b_un.b_addr);
26647 
26648 	/*
26649 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
26650 	 * axle - it has a call into us!
26651 	 */
26652 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
26653 		SD_INFO(SD_LOG_COMMON, un,
26654 		    "sd_send_polled_RQS: RQS failed\n");
26655 	}
26656 
26657 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
26658 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
26659 
26660 	mutex_enter(SD_MUTEX(un));
26661 	un->un_sense_isbusy = 0;
26662 	mutex_exit(SD_MUTEX(un));
26663 
26664 	return (ret_val);
26665 }
26666 
26667 /*
26668  * Defines needed for localized version of the scsi_poll routine.
26669  */
26670 #define	CSEC		10000			/* usecs */
26671 #define	SEC_TO_CSEC	(1000000 / CSEC)
26672 
26673 /*
26674  *    Function: sd_ddi_scsi_poll()
26675  *
26676  * Description: Localized version of the scsi_poll routine.  The purpose is to
26677  *		send a scsi_pkt to a device as a polled command.  This version
26678  *		is to ensure more robust handling of transport errors.
26679  *		Specifically this routine cures not ready, coming ready
26680  *		transition for power up and reset of sonoma's.  This can take
26681  *		up to 45 seconds for power-on and 20 seconds for reset of a
26682  *		sonoma lun.
26683  *
26684  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
26685  *
26686  * Return Code: 0 - Command completed successfully with good status
26687  *             -1 - Command failed.
26688  *
26689  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
26690  * be fixed (removing this code), we need to determine how to handle the
26691  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
26692  *
26693  * NOTE: This code is only called off sddump().
26694  */
26695 static int
26696 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
26697 {
26698 	int			rval = -1;
26699 	int			savef;
26700 	long			savet;
26701 	void			(*savec)();
26702 	int			timeout;
26703 	int			busy_count;
26704 	int			poll_delay;
26705 	int			rc;
26706 	uint8_t			*sensep;
26707 	struct scsi_arq_status	*arqstat;
26708 	extern int		do_polled_io;
26709 
26710 	ASSERT(pkt->pkt_scbp);
26711 
26712 	/*
26713 	 * save old flags..
26714 	 */
26715 	savef = pkt->pkt_flags;
26716 	savec = pkt->pkt_comp;
26717 	savet = pkt->pkt_time;
26718 
26719 	pkt->pkt_flags |= FLAG_NOINTR;
26720 
26721 	/*
26722 	 * XXX there is nothing in the SCSA spec that states that we should not
26723 	 * do a callback for polled cmds; however, removing this will break sd
26724 	 * and probably other target drivers
26725 	 */
26726 	pkt->pkt_comp = NULL;
26727 
26728 	/*
26729 	 * we don't like a polled command without timeout.
26730 	 * 60 seconds seems long enough.
26731 	 */
26732 	if (pkt->pkt_time == 0)
26733 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
26734 
26735 	/*
26736 	 * Send polled cmd.
26737 	 *
26738 	 * We do some error recovery for various errors.  Tran_busy,
26739 	 * queue full, and non-dispatched commands are retried every 10 msec.
26740 	 * as they are typically transient failures.  Busy status and Not
26741 	 * Ready are retried every second as this status takes a while to
26742 	 * change.
26743 	 */
26744 	timeout = pkt->pkt_time * SEC_TO_CSEC;
26745 
26746 	for (busy_count = 0; busy_count < timeout; busy_count++) {
26747 		/*
26748 		 * Initialize pkt status variables.
26749 		 */
26750 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
26751 
26752 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
26753 			if (rc != TRAN_BUSY) {
26754 				/* Transport failed - give up. */
26755 				break;
26756 			} else {
26757 				/* Transport busy - try again. */
26758 				poll_delay = 1 * CSEC;		/* 10 msec. */
26759 			}
26760 		} else {
26761 			/*
26762 			 * Transport accepted - check pkt status.
26763 			 */
26764 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
26765 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26766 			    (rc == STATUS_CHECK) &&
26767 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
26768 				arqstat =
26769 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
26770 				sensep = (uint8_t *)&arqstat->sts_sensedata;
26771 			} else {
26772 				sensep = NULL;
26773 			}
26774 
26775 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26776 			    (rc == STATUS_GOOD)) {
26777 				/* No error - we're done */
26778 				rval = 0;
26779 				break;
26780 
26781 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
26782 				/* Lost connection - give up */
26783 				break;
26784 
26785 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
26786 			    (pkt->pkt_state == 0)) {
26787 				/* Pkt not dispatched - try again. */
26788 				poll_delay = 1 * CSEC;		/* 10 msec. */
26789 
26790 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26791 			    (rc == STATUS_QFULL)) {
26792 				/* Queue full - try again. */
26793 				poll_delay = 1 * CSEC;		/* 10 msec. */
26794 
26795 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26796 			    (rc == STATUS_BUSY)) {
26797 				/* Busy - try again. */
26798 				poll_delay = 100 * CSEC;	/* 1 sec. */
26799 				busy_count += (SEC_TO_CSEC - 1);
26800 
26801 			} else if ((sensep != NULL) &&
26802 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
26803 				/*
26804 				 * Unit Attention - try again.
26805 				 * Pretend it took 1 sec.
26806 				 * NOTE: 'continue' avoids poll_delay
26807 				 */
26808 				busy_count += (SEC_TO_CSEC - 1);
26809 				continue;
26810 
26811 			} else if ((sensep != NULL) &&
26812 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
26813 			    (scsi_sense_asc(sensep) == 0x04) &&
26814 			    (scsi_sense_ascq(sensep) == 0x01)) {
26815 				/*
26816 				 * Not ready -> ready - try again.
26817 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
26818 				 * ...same as STATUS_BUSY
26819 				 */
26820 				poll_delay = 100 * CSEC;	/* 1 sec. */
26821 				busy_count += (SEC_TO_CSEC - 1);
26822 
26823 			} else {
26824 				/* BAD status - give up. */
26825 				break;
26826 			}
26827 		}
26828 
26829 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
26830 		    !do_polled_io) {
26831 			delay(drv_usectohz(poll_delay));
26832 		} else {
26833 			/* we busy wait during cpr_dump or interrupt threads */
26834 			drv_usecwait(poll_delay);
26835 		}
26836 	}
26837 
26838 	pkt->pkt_flags = savef;
26839 	pkt->pkt_comp = savec;
26840 	pkt->pkt_time = savet;
26841 
26842 	/* return on error */
26843 	if (rval)
26844 		return (rval);
26845 
26846 	/*
26847 	 * This is not a performance critical code path.
26848 	 *
26849 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
26850 	 * issues associated with looking at DMA memory prior to
26851 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
26852 	 */
26853 	scsi_sync_pkt(pkt);
26854 	return (0);
26855 }
26856 
26857 
26858 
26859 /*
26860  *    Function: sd_persistent_reservation_in_read_keys
26861  *
26862  * Description: This routine is the driver entry point for handling CD-ROM
26863  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
26864  *		by sending the SCSI-3 PRIN commands to the device.
26865  *		Processes the read keys command response by copying the
26866  *		reservation key information into the user provided buffer.
26867  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
26868  *
26869  *   Arguments: un   -  Pointer to soft state struct for the target.
26870  *		usrp -	user provided pointer to multihost Persistent In Read
26871  *			Keys structure (mhioc_inkeys_t)
26872  *		flag -	this argument is a pass through to ddi_copyxxx()
26873  *			directly from the mode argument of ioctl().
26874  *
26875  * Return Code: 0   - Success
26876  *		EACCES
26877  *		ENOTSUP
26878  *		errno return code from sd_send_scsi_cmd()
26879  *
26880  *     Context: Can sleep. Does not return until command is completed.
26881  */
26882 
26883 static int
26884 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
26885     mhioc_inkeys_t *usrp, int flag)
26886 {
26887 #ifdef _MULTI_DATAMODEL
26888 	struct mhioc_key_list32	li32;
26889 #endif
26890 	sd_prin_readkeys_t	*in;
26891 	mhioc_inkeys_t		*ptr;
26892 	mhioc_key_list_t	li;
26893 	uchar_t			*data_bufp = NULL;
26894 	int			data_len = 0;
26895 	int			rval = 0;
26896 	size_t			copysz = 0;
26897 	sd_ssc_t		*ssc;
26898 
26899 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
26900 		return (EINVAL);
26901 	}
26902 	bzero(&li, sizeof (mhioc_key_list_t));
26903 
26904 	ssc = sd_ssc_init(un);
26905 
26906 	/*
26907 	 * Get the listsize from user
26908 	 */
26909 #ifdef _MULTI_DATAMODEL
26910 	switch (ddi_model_convert_from(flag & FMODELS)) {
26911 	case DDI_MODEL_ILP32:
26912 		copysz = sizeof (struct mhioc_key_list32);
26913 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
26914 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26915 			    "sd_persistent_reservation_in_read_keys: "
26916 			    "failed ddi_copyin: mhioc_key_list32_t\n");
26917 			rval = EFAULT;
26918 			goto done;
26919 		}
26920 		li.listsize = li32.listsize;
26921 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
26922 		break;
26923 
26924 	case DDI_MODEL_NONE:
26925 		copysz = sizeof (mhioc_key_list_t);
26926 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26927 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26928 			    "sd_persistent_reservation_in_read_keys: "
26929 			    "failed ddi_copyin: mhioc_key_list_t\n");
26930 			rval = EFAULT;
26931 			goto done;
26932 		}
26933 		break;
26934 	}
26935 
26936 #else /* ! _MULTI_DATAMODEL */
26937 	copysz = sizeof (mhioc_key_list_t);
26938 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26939 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26940 		    "sd_persistent_reservation_in_read_keys: "
26941 		    "failed ddi_copyin: mhioc_key_list_t\n");
26942 		rval = EFAULT;
26943 		goto done;
26944 	}
26945 #endif
26946 
26947 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
26948 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
26949 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26950 
26951 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
26952 	    data_len, data_bufp);
26953 	if (rval != 0) {
26954 		if (rval == EIO)
26955 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26956 		else
26957 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26958 		goto done;
26959 	}
26960 	in = (sd_prin_readkeys_t *)data_bufp;
26961 	ptr->generation = BE_32(in->generation);
26962 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
26963 
26964 	/*
26965 	 * Return the min(listsize, listlen) keys
26966 	 */
26967 #ifdef _MULTI_DATAMODEL
26968 
26969 	switch (ddi_model_convert_from(flag & FMODELS)) {
26970 	case DDI_MODEL_ILP32:
26971 		li32.listlen = li.listlen;
26972 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
26973 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26974 			    "sd_persistent_reservation_in_read_keys: "
26975 			    "failed ddi_copyout: mhioc_key_list32_t\n");
26976 			rval = EFAULT;
26977 			goto done;
26978 		}
26979 		break;
26980 
26981 	case DDI_MODEL_NONE:
26982 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26983 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26984 			    "sd_persistent_reservation_in_read_keys: "
26985 			    "failed ddi_copyout: mhioc_key_list_t\n");
26986 			rval = EFAULT;
26987 			goto done;
26988 		}
26989 		break;
26990 	}
26991 
26992 #else /* ! _MULTI_DATAMODEL */
26993 
26994 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26995 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26996 		    "sd_persistent_reservation_in_read_keys: "
26997 		    "failed ddi_copyout: mhioc_key_list_t\n");
26998 		rval = EFAULT;
26999 		goto done;
27000 	}
27001 
27002 #endif /* _MULTI_DATAMODEL */
27003 
27004 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
27005 	    li.listsize * MHIOC_RESV_KEY_SIZE);
27006 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
27007 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
27008 		    "sd_persistent_reservation_in_read_keys: "
27009 		    "failed ddi_copyout: keylist\n");
27010 		rval = EFAULT;
27011 	}
27012 done:
27013 	sd_ssc_fini(ssc);
27014 	kmem_free(data_bufp, data_len);
27015 	return (rval);
27016 }
27017 
27018 
27019 /*
27020  *    Function: sd_persistent_reservation_in_read_resv
27021  *
27022  * Description: This routine is the driver entry point for handling CD-ROM
27023  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
27024  *		by sending the SCSI-3 PRIN commands to the device.
27025  *		Process the read persistent reservations command response by
27026  *		copying the reservation information into the user provided
27027  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
27028  *
27029  *   Arguments: un   -  Pointer to soft state struct for the target.
27030  *		usrp -	user provided pointer to multihost Persistent In Read
27031  *			Keys structure (mhioc_inkeys_t)
27032  *		flag -	this argument is a pass through to ddi_copyxxx()
27033  *			directly from the mode argument of ioctl().
27034  *
27035  * Return Code: 0   - Success
27036  *		EACCES
27037  *		ENOTSUP
27038  *		errno return code from sd_send_scsi_cmd()
27039  *
27040  *     Context: Can sleep. Does not return until command is completed.
27041  */
27042 
27043 static int
27044 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
27045     mhioc_inresvs_t *usrp, int flag)
27046 {
27047 #ifdef _MULTI_DATAMODEL
27048 	struct mhioc_resv_desc_list32 resvlist32;
27049 #endif
27050 	sd_prin_readresv_t	*in;
27051 	mhioc_inresvs_t		*ptr;
27052 	sd_readresv_desc_t	*readresv_ptr;
27053 	mhioc_resv_desc_list_t	resvlist;
27054 	mhioc_resv_desc_t	resvdesc;
27055 	uchar_t			*data_bufp = NULL;
27056 	int			data_len;
27057 	int			rval = 0;
27058 	int			i;
27059 	size_t			copysz = 0;
27060 	mhioc_resv_desc_t	*bufp;
27061 	sd_ssc_t		*ssc;
27062 
27063 	if ((ptr = usrp) == NULL) {
27064 		return (EINVAL);
27065 	}
27066 
27067 	ssc = sd_ssc_init(un);
27068 
27069 	/*
27070 	 * Get the listsize from user
27071 	 */
27072 #ifdef _MULTI_DATAMODEL
27073 	switch (ddi_model_convert_from(flag & FMODELS)) {
27074 	case DDI_MODEL_ILP32:
27075 		copysz = sizeof (struct mhioc_resv_desc_list32);
27076 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
27077 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
27078 			    "sd_persistent_reservation_in_read_resv: "
27079 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
27080 			rval = EFAULT;
27081 			goto done;
27082 		}
27083 		resvlist.listsize = resvlist32.listsize;
27084 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
27085 		break;
27086 
27087 	case DDI_MODEL_NONE:
27088 		copysz = sizeof (mhioc_resv_desc_list_t);
27089 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
27090 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
27091 			    "sd_persistent_reservation_in_read_resv: "
27092 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
27093 			rval = EFAULT;
27094 			goto done;
27095 		}
27096 		break;
27097 	}
27098 #else /* ! _MULTI_DATAMODEL */
27099 	copysz = sizeof (mhioc_resv_desc_list_t);
27100 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
27101 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
27102 		    "sd_persistent_reservation_in_read_resv: "
27103 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
27104 		rval = EFAULT;
27105 		goto done;
27106 	}
27107 #endif /* ! _MULTI_DATAMODEL */
27108 
27109 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
27110 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
27111 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
27112 
27113 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
27114 	    data_len, data_bufp);
27115 	if (rval != 0) {
27116 		if (rval == EIO)
27117 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
27118 		else
27119 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
27120 		goto done;
27121 	}
27122 	in = (sd_prin_readresv_t *)data_bufp;
27123 	ptr->generation = BE_32(in->generation);
27124 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
27125 
27126 	/*
27127 	 * Return the min(listsize, listlen( keys
27128 	 */
27129 #ifdef _MULTI_DATAMODEL
27130 
27131 	switch (ddi_model_convert_from(flag & FMODELS)) {
27132 	case DDI_MODEL_ILP32:
27133 		resvlist32.listlen = resvlist.listlen;
27134 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
27135 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
27136 			    "sd_persistent_reservation_in_read_resv: "
27137 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
27138 			rval = EFAULT;
27139 			goto done;
27140 		}
27141 		break;
27142 
27143 	case DDI_MODEL_NONE:
27144 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
27145 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
27146 			    "sd_persistent_reservation_in_read_resv: "
27147 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
27148 			rval = EFAULT;
27149 			goto done;
27150 		}
27151 		break;
27152 	}
27153 
27154 #else /* ! _MULTI_DATAMODEL */
27155 
27156 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
27157 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
27158 		    "sd_persistent_reservation_in_read_resv: "
27159 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
27160 		rval = EFAULT;
27161 		goto done;
27162 	}
27163 
27164 #endif /* ! _MULTI_DATAMODEL */
27165 
27166 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
27167 	bufp = resvlist.list;
27168 	copysz = sizeof (mhioc_resv_desc_t);
27169 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
27170 	    i++, readresv_ptr++, bufp++) {
27171 
27172 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
27173 		    MHIOC_RESV_KEY_SIZE);
27174 		resvdesc.type  = readresv_ptr->type;
27175 		resvdesc.scope = readresv_ptr->scope;
27176 		resvdesc.scope_specific_addr =
27177 		    BE_32(readresv_ptr->scope_specific_addr);
27178 
27179 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
27180 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
27181 			    "sd_persistent_reservation_in_read_resv: "
27182 			    "failed ddi_copyout: resvlist\n");
27183 			rval = EFAULT;
27184 			goto done;
27185 		}
27186 	}
27187 done:
27188 	sd_ssc_fini(ssc);
27189 	/* only if data_bufp is allocated, we need to free it */
27190 	if (data_bufp) {
27191 		kmem_free(data_bufp, data_len);
27192 	}
27193 	return (rval);
27194 }
27195 
27196 
27197 /*
27198  *    Function: sr_change_blkmode()
27199  *
27200  * Description: This routine is the driver entry point for handling CD-ROM
27201  *		block mode ioctl requests. Support for returning and changing
27202  *		the current block size in use by the device is implemented. The
27203  *		LBA size is changed via a MODE SELECT Block Descriptor.
27204  *
27205  *		This routine issues a mode sense with an allocation length of
27206  *		12 bytes for the mode page header and a single block descriptor.
27207  *
27208  *   Arguments: dev - the device 'dev_t'
27209  *		cmd - the request type; one of CDROMGBLKMODE (get) or
27210  *		      CDROMSBLKMODE (set)
27211  *		data - current block size or requested block size
27212  *		flag - this argument is a pass through to ddi_copyxxx() directly
27213  *		       from the mode argument of ioctl().
27214  *
27215  * Return Code: the code returned by sd_send_scsi_cmd()
27216  *		EINVAL if invalid arguments are provided
27217  *		EFAULT if ddi_copyxxx() fails
27218  *		ENXIO if fail ddi_get_soft_state
27219  *		EIO if invalid mode sense block descriptor length
27220  *
27221  */
27222 
27223 static int
27224 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
27225 {
27226 	struct sd_lun			*un = NULL;
27227 	struct mode_header		*sense_mhp, *select_mhp;
27228 	struct block_descriptor		*sense_desc, *select_desc;
27229 	int				current_bsize;
27230 	int				rval = EINVAL;
27231 	uchar_t				*sense = NULL;
27232 	uchar_t				*select = NULL;
27233 	sd_ssc_t			*ssc;
27234 
27235 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
27236 
27237 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27238 		return (ENXIO);
27239 	}
27240 
27241 	/*
27242 	 * The block length is changed via the Mode Select block descriptor, the
27243 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
27244 	 * required as part of this routine. Therefore the mode sense allocation
27245 	 * length is specified to be the length of a mode page header and a
27246 	 * block descriptor.
27247 	 */
27248 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27249 
27250 	ssc = sd_ssc_init(un);
27251 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27252 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
27253 	sd_ssc_fini(ssc);
27254 	if (rval != 0) {
27255 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27256 		    "sr_change_blkmode: Mode Sense Failed\n");
27257 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27258 		return (rval);
27259 	}
27260 
27261 	/* Check the block descriptor len to handle only 1 block descriptor */
27262 	sense_mhp = (struct mode_header *)sense;
27263 	if ((sense_mhp->bdesc_length == 0) ||
27264 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
27265 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27266 		    "sr_change_blkmode: Mode Sense returned invalid block"
27267 		    " descriptor length\n");
27268 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27269 		return (EIO);
27270 	}
27271 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
27272 	current_bsize = ((sense_desc->blksize_hi << 16) |
27273 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
27274 
27275 	/* Process command */
27276 	switch (cmd) {
27277 	case CDROMGBLKMODE:
27278 		/* Return the block size obtained during the mode sense */
27279 		if (ddi_copyout(&current_bsize, (void *)data,
27280 		    sizeof (int), flag) != 0)
27281 			rval = EFAULT;
27282 		break;
27283 	case CDROMSBLKMODE:
27284 		/* Validate the requested block size */
27285 		switch (data) {
27286 		case CDROM_BLK_512:
27287 		case CDROM_BLK_1024:
27288 		case CDROM_BLK_2048:
27289 		case CDROM_BLK_2056:
27290 		case CDROM_BLK_2336:
27291 		case CDROM_BLK_2340:
27292 		case CDROM_BLK_2352:
27293 		case CDROM_BLK_2368:
27294 		case CDROM_BLK_2448:
27295 		case CDROM_BLK_2646:
27296 		case CDROM_BLK_2647:
27297 			break;
27298 		default:
27299 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27300 			    "sr_change_blkmode: "
27301 			    "Block Size '%ld' Not Supported\n", data);
27302 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27303 			return (EINVAL);
27304 		}
27305 
27306 		/*
27307 		 * The current block size matches the requested block size so
27308 		 * there is no need to send the mode select to change the size
27309 		 */
27310 		if (current_bsize == data) {
27311 			break;
27312 		}
27313 
27314 		/* Build the select data for the requested block size */
27315 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27316 		select_mhp = (struct mode_header *)select;
27317 		select_desc =
27318 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
27319 		/*
27320 		 * The LBA size is changed via the block descriptor, so the
27321 		 * descriptor is built according to the user data
27322 		 */
27323 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
27324 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
27325 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
27326 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
27327 
27328 		/* Send the mode select for the requested block size */
27329 		ssc = sd_ssc_init(un);
27330 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
27331 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27332 		    SD_PATH_STANDARD);
27333 		sd_ssc_fini(ssc);
27334 		if (rval != 0) {
27335 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27336 			    "sr_change_blkmode: Mode Select Failed\n");
27337 			/*
27338 			 * The mode select failed for the requested block size,
27339 			 * so reset the data for the original block size and
27340 			 * send it to the target. The error is indicated by the
27341 			 * return value for the failed mode select.
27342 			 */
27343 			select_desc->blksize_hi  = sense_desc->blksize_hi;
27344 			select_desc->blksize_mid = sense_desc->blksize_mid;
27345 			select_desc->blksize_lo  = sense_desc->blksize_lo;
27346 			ssc = sd_ssc_init(un);
27347 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
27348 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27349 			    SD_PATH_STANDARD);
27350 			sd_ssc_fini(ssc);
27351 		} else {
27352 			ASSERT(!mutex_owned(SD_MUTEX(un)));
27353 			mutex_enter(SD_MUTEX(un));
27354 			sd_update_block_info(un, (uint32_t)data, 0);
27355 			mutex_exit(SD_MUTEX(un));
27356 		}
27357 		break;
27358 	default:
27359 		/* should not reach here, but check anyway */
27360 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27361 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
27362 		rval = EINVAL;
27363 		break;
27364 	}
27365 
27366 	if (select) {
27367 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
27368 	}
27369 	if (sense) {
27370 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27371 	}
27372 	return (rval);
27373 }
27374 
27375 
27376 /*
27377  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
27378  * implement driver support for getting and setting the CD speed. The command
27379  * set used will be based on the device type. If the device has not been
27380  * identified as MMC the Toshiba vendor specific mode page will be used. If
27381  * the device is MMC but does not support the Real Time Streaming feature
27382  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
27383  * be used to read the speed.
27384  */
27385 
27386 /*
27387  *    Function: sr_change_speed()
27388  *
27389  * Description: This routine is the driver entry point for handling CD-ROM
27390  *		drive speed ioctl requests for devices supporting the Toshiba
27391  *		vendor specific drive speed mode page. Support for returning
27392  *		and changing the current drive speed in use by the device is
27393  *		implemented.
27394  *
27395  *   Arguments: dev - the device 'dev_t'
27396  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
27397  *		      CDROMSDRVSPEED (set)
27398  *		data - current drive speed or requested drive speed
27399  *		flag - this argument is a pass through to ddi_copyxxx() directly
27400  *		       from the mode argument of ioctl().
27401  *
27402  * Return Code: the code returned by sd_send_scsi_cmd()
27403  *		EINVAL if invalid arguments are provided
27404  *		EFAULT if ddi_copyxxx() fails
27405  *		ENXIO if fail ddi_get_soft_state
27406  *		EIO if invalid mode sense block descriptor length
27407  */
27408 
27409 static int
27410 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27411 {
27412 	struct sd_lun			*un = NULL;
27413 	struct mode_header		*sense_mhp, *select_mhp;
27414 	struct mode_speed		*sense_page, *select_page;
27415 	int				current_speed;
27416 	int				rval = EINVAL;
27417 	int				bd_len;
27418 	uchar_t				*sense = NULL;
27419 	uchar_t				*select = NULL;
27420 	sd_ssc_t			*ssc;
27421 
27422 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27423 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27424 		return (ENXIO);
27425 	}
27426 
27427 	/*
27428 	 * Note: The drive speed is being modified here according to a Toshiba
27429 	 * vendor specific mode page (0x31).
27430 	 */
27431 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27432 
27433 	ssc = sd_ssc_init(un);
27434 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27435 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
27436 	    SD_PATH_STANDARD);
27437 	sd_ssc_fini(ssc);
27438 	if (rval != 0) {
27439 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27440 		    "sr_change_speed: Mode Sense Failed\n");
27441 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27442 		return (rval);
27443 	}
27444 	sense_mhp  = (struct mode_header *)sense;
27445 
27446 	/* Check the block descriptor len to handle only 1 block descriptor */
27447 	bd_len = sense_mhp->bdesc_length;
27448 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27449 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27450 		    "sr_change_speed: Mode Sense returned invalid block "
27451 		    "descriptor length\n");
27452 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27453 		return (EIO);
27454 	}
27455 
27456 	sense_page = (struct mode_speed *)
27457 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27458 	current_speed = sense_page->speed;
27459 
27460 	/* Process command */
27461 	switch (cmd) {
27462 	case CDROMGDRVSPEED:
27463 		/* Return the drive speed obtained during the mode sense */
27464 		if (current_speed == 0x2) {
27465 			current_speed = CDROM_TWELVE_SPEED;
27466 		}
27467 		if (ddi_copyout(&current_speed, (void *)data,
27468 		    sizeof (int), flag) != 0) {
27469 			rval = EFAULT;
27470 		}
27471 		break;
27472 	case CDROMSDRVSPEED:
27473 		/* Validate the requested drive speed */
27474 		switch ((uchar_t)data) {
27475 		case CDROM_TWELVE_SPEED:
27476 			data = 0x2;
27477 			/*FALLTHROUGH*/
27478 		case CDROM_NORMAL_SPEED:
27479 		case CDROM_DOUBLE_SPEED:
27480 		case CDROM_QUAD_SPEED:
27481 		case CDROM_MAXIMUM_SPEED:
27482 			break;
27483 		default:
27484 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27485 			    "sr_change_speed: "
27486 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
27487 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27488 			return (EINVAL);
27489 		}
27490 
27491 		/*
27492 		 * The current drive speed matches the requested drive speed so
27493 		 * there is no need to send the mode select to change the speed
27494 		 */
27495 		if (current_speed == data) {
27496 			break;
27497 		}
27498 
27499 		/* Build the select data for the requested drive speed */
27500 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27501 		select_mhp = (struct mode_header *)select;
27502 		select_mhp->bdesc_length = 0;
27503 		select_page =
27504 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27505 		select_page =
27506 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27507 		select_page->mode_page.code = CDROM_MODE_SPEED;
27508 		select_page->mode_page.length = 2;
27509 		select_page->speed = (uchar_t)data;
27510 
27511 		/* Send the mode select for the requested block size */
27512 		ssc = sd_ssc_init(un);
27513 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27514 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27515 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27516 		sd_ssc_fini(ssc);
27517 		if (rval != 0) {
27518 			/*
27519 			 * The mode select failed for the requested drive speed,
27520 			 * so reset the data for the original drive speed and
27521 			 * send it to the target. The error is indicated by the
27522 			 * return value for the failed mode select.
27523 			 */
27524 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27525 			    "sr_drive_speed: Mode Select Failed\n");
27526 			select_page->speed = sense_page->speed;
27527 			ssc = sd_ssc_init(un);
27528 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27529 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27530 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27531 			sd_ssc_fini(ssc);
27532 		}
27533 		break;
27534 	default:
27535 		/* should not reach here, but check anyway */
27536 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27537 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
27538 		rval = EINVAL;
27539 		break;
27540 	}
27541 
27542 	if (select) {
27543 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
27544 	}
27545 	if (sense) {
27546 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27547 	}
27548 
27549 	return (rval);
27550 }
27551 
27552 
27553 /*
27554  *    Function: sr_atapi_change_speed()
27555  *
27556  * Description: This routine is the driver entry point for handling CD-ROM
27557  *		drive speed ioctl requests for MMC devices that do not support
27558  *		the Real Time Streaming feature (0x107).
27559  *
27560  *		Note: This routine will use the SET SPEED command which may not
27561  *		be supported by all devices.
27562  *
27563  *   Arguments: dev- the device 'dev_t'
27564  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
27565  *		     CDROMSDRVSPEED (set)
27566  *		data- current drive speed or requested drive speed
27567  *		flag- this argument is a pass through to ddi_copyxxx() directly
27568  *		      from the mode argument of ioctl().
27569  *
27570  * Return Code: the code returned by sd_send_scsi_cmd()
27571  *		EINVAL if invalid arguments are provided
27572  *		EFAULT if ddi_copyxxx() fails
27573  *		ENXIO if fail ddi_get_soft_state
27574  *		EIO if invalid mode sense block descriptor length
27575  */
27576 
27577 static int
27578 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27579 {
27580 	struct sd_lun			*un;
27581 	struct uscsi_cmd		*com = NULL;
27582 	struct mode_header_grp2		*sense_mhp;
27583 	uchar_t				*sense_page;
27584 	uchar_t				*sense = NULL;
27585 	char				cdb[CDB_GROUP5];
27586 	int				bd_len;
27587 	int				current_speed = 0;
27588 	int				max_speed = 0;
27589 	int				rval;
27590 	sd_ssc_t			*ssc;
27591 
27592 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27593 
27594 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27595 		return (ENXIO);
27596 	}
27597 
27598 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
27599 
27600 	ssc = sd_ssc_init(un);
27601 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
27602 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
27603 	    SD_PATH_STANDARD);
27604 	sd_ssc_fini(ssc);
27605 	if (rval != 0) {
27606 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27607 		    "sr_atapi_change_speed: Mode Sense Failed\n");
27608 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27609 		return (rval);
27610 	}
27611 
27612 	/* Check the block descriptor len to handle only 1 block descriptor */
27613 	sense_mhp = (struct mode_header_grp2 *)sense;
27614 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
27615 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27616 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27617 		    "sr_atapi_change_speed: Mode Sense returned invalid "
27618 		    "block descriptor length\n");
27619 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27620 		return (EIO);
27621 	}
27622 
27623 	/* Calculate the current and maximum drive speeds */
27624 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27625 	current_speed = (sense_page[14] << 8) | sense_page[15];
27626 	max_speed = (sense_page[8] << 8) | sense_page[9];
27627 
27628 	/* Process the command */
27629 	switch (cmd) {
27630 	case CDROMGDRVSPEED:
27631 		current_speed /= SD_SPEED_1X;
27632 		if (ddi_copyout(&current_speed, (void *)data,
27633 		    sizeof (int), flag) != 0)
27634 			rval = EFAULT;
27635 		break;
27636 	case CDROMSDRVSPEED:
27637 		/* Convert the speed code to KB/sec */
27638 		switch ((uchar_t)data) {
27639 		case CDROM_NORMAL_SPEED:
27640 			current_speed = SD_SPEED_1X;
27641 			break;
27642 		case CDROM_DOUBLE_SPEED:
27643 			current_speed = 2 * SD_SPEED_1X;
27644 			break;
27645 		case CDROM_QUAD_SPEED:
27646 			current_speed = 4 * SD_SPEED_1X;
27647 			break;
27648 		case CDROM_TWELVE_SPEED:
27649 			current_speed = 12 * SD_SPEED_1X;
27650 			break;
27651 		case CDROM_MAXIMUM_SPEED:
27652 			current_speed = 0xffff;
27653 			break;
27654 		default:
27655 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27656 			    "sr_atapi_change_speed: invalid drive speed %d\n",
27657 			    (uchar_t)data);
27658 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27659 			return (EINVAL);
27660 		}
27661 
27662 		/* Check the request against the drive's max speed. */
27663 		if (current_speed != 0xffff) {
27664 			if (current_speed > max_speed) {
27665 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27666 				return (EINVAL);
27667 			}
27668 		}
27669 
27670 		/*
27671 		 * Build and send the SET SPEED command
27672 		 *
27673 		 * Note: The SET SPEED (0xBB) command used in this routine is
27674 		 * obsolete per the SCSI MMC spec but still supported in the
27675 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27676 		 * therefore the command is still implemented in this routine.
27677 		 */
27678 		bzero(cdb, sizeof (cdb));
27679 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
27680 		cdb[2] = (uchar_t)(current_speed >> 8);
27681 		cdb[3] = (uchar_t)current_speed;
27682 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27683 		com->uscsi_cdb	   = (caddr_t)cdb;
27684 		com->uscsi_cdblen  = CDB_GROUP5;
27685 		com->uscsi_bufaddr = NULL;
27686 		com->uscsi_buflen  = 0;
27687 		com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
27688 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
27689 		break;
27690 	default:
27691 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27692 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
27693 		rval = EINVAL;
27694 	}
27695 
27696 	if (sense) {
27697 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27698 	}
27699 	if (com) {
27700 		kmem_free(com, sizeof (*com));
27701 	}
27702 	return (rval);
27703 }
27704 
27705 
27706 /*
27707  *    Function: sr_pause_resume()
27708  *
27709  * Description: This routine is the driver entry point for handling CD-ROM
27710  *		pause/resume ioctl requests. This only affects the audio play
27711  *		operation.
27712  *
27713  *   Arguments: dev - the device 'dev_t'
27714  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
27715  *		      for setting the resume bit of the cdb.
27716  *
27717  * Return Code: the code returned by sd_send_scsi_cmd()
27718  *		EINVAL if invalid mode specified
27719  *
27720  */
27721 
27722 static int
27723 sr_pause_resume(dev_t dev, int cmd)
27724 {
27725 	struct sd_lun		*un;
27726 	struct uscsi_cmd	*com;
27727 	char			cdb[CDB_GROUP1];
27728 	int			rval;
27729 
27730 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27731 		return (ENXIO);
27732 	}
27733 
27734 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27735 	bzero(cdb, CDB_GROUP1);
27736 	cdb[0] = SCMD_PAUSE_RESUME;
27737 	switch (cmd) {
27738 	case CDROMRESUME:
27739 		cdb[8] = 1;
27740 		break;
27741 	case CDROMPAUSE:
27742 		cdb[8] = 0;
27743 		break;
27744 	default:
27745 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
27746 		    " Command '%x' Not Supported\n", cmd);
27747 		rval = EINVAL;
27748 		goto done;
27749 	}
27750 
27751 	com->uscsi_cdb    = cdb;
27752 	com->uscsi_cdblen = CDB_GROUP1;
27753 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27754 
27755 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27756 	    SD_PATH_STANDARD);
27757 
27758 done:
27759 	kmem_free(com, sizeof (*com));
27760 	return (rval);
27761 }
27762 
27763 
27764 /*
27765  *    Function: sr_play_msf()
27766  *
27767  * Description: This routine is the driver entry point for handling CD-ROM
27768  *		ioctl requests to output the audio signals at the specified
27769  *		starting address and continue the audio play until the specified
27770  *		ending address (CDROMPLAYMSF) The address is in Minute Second
27771  *		Frame (MSF) format.
27772  *
27773  *   Arguments: dev	- the device 'dev_t'
27774  *		data	- pointer to user provided audio msf structure,
27775  *		          specifying start/end addresses.
27776  *		flag	- this argument is a pass through to ddi_copyxxx()
27777  *		          directly from the mode argument of ioctl().
27778  *
27779  * Return Code: the code returned by sd_send_scsi_cmd()
27780  *		EFAULT if ddi_copyxxx() fails
27781  *		ENXIO if fail ddi_get_soft_state
27782  *		EINVAL if data pointer is NULL
27783  */
27784 
27785 static int
27786 sr_play_msf(dev_t dev, caddr_t data, int flag)
27787 {
27788 	struct sd_lun		*un;
27789 	struct uscsi_cmd	*com;
27790 	struct cdrom_msf	msf_struct;
27791 	struct cdrom_msf	*msf = &msf_struct;
27792 	char			cdb[CDB_GROUP1];
27793 	int			rval;
27794 
27795 	if (data == NULL) {
27796 		return (EINVAL);
27797 	}
27798 
27799 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27800 		return (ENXIO);
27801 	}
27802 
27803 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
27804 		return (EFAULT);
27805 	}
27806 
27807 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27808 	bzero(cdb, CDB_GROUP1);
27809 	cdb[0] = SCMD_PLAYAUDIO_MSF;
27810 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
27811 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
27812 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
27813 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
27814 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
27815 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
27816 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
27817 	} else {
27818 		cdb[3] = msf->cdmsf_min0;
27819 		cdb[4] = msf->cdmsf_sec0;
27820 		cdb[5] = msf->cdmsf_frame0;
27821 		cdb[6] = msf->cdmsf_min1;
27822 		cdb[7] = msf->cdmsf_sec1;
27823 		cdb[8] = msf->cdmsf_frame1;
27824 	}
27825 	com->uscsi_cdb    = cdb;
27826 	com->uscsi_cdblen = CDB_GROUP1;
27827 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27828 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27829 	    SD_PATH_STANDARD);
27830 	kmem_free(com, sizeof (*com));
27831 	return (rval);
27832 }
27833 
27834 
27835 /*
27836  *    Function: sr_play_trkind()
27837  *
27838  * Description: This routine is the driver entry point for handling CD-ROM
27839  *		ioctl requests to output the audio signals at the specified
27840  *		starting address and continue the audio play until the specified
27841  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
27842  *		format.
27843  *
27844  *   Arguments: dev	- the device 'dev_t'
27845  *		data	- pointer to user provided audio track/index structure,
27846  *		          specifying start/end addresses.
27847  *		flag	- this argument is a pass through to ddi_copyxxx()
27848  *		          directly from the mode argument of ioctl().
27849  *
27850  * Return Code: the code returned by sd_send_scsi_cmd()
27851  *		EFAULT if ddi_copyxxx() fails
27852  *		ENXIO if fail ddi_get_soft_state
27853  *		EINVAL if data pointer is NULL
27854  */
27855 
27856 static int
27857 sr_play_trkind(dev_t dev, caddr_t data, int flag)
27858 {
27859 	struct cdrom_ti		ti_struct;
27860 	struct cdrom_ti		*ti = &ti_struct;
27861 	struct uscsi_cmd	*com = NULL;
27862 	char			cdb[CDB_GROUP1];
27863 	int			rval;
27864 
27865 	if (data == NULL) {
27866 		return (EINVAL);
27867 	}
27868 
27869 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
27870 		return (EFAULT);
27871 	}
27872 
27873 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27874 	bzero(cdb, CDB_GROUP1);
27875 	cdb[0] = SCMD_PLAYAUDIO_TI;
27876 	cdb[4] = ti->cdti_trk0;
27877 	cdb[5] = ti->cdti_ind0;
27878 	cdb[7] = ti->cdti_trk1;
27879 	cdb[8] = ti->cdti_ind1;
27880 	com->uscsi_cdb    = cdb;
27881 	com->uscsi_cdblen = CDB_GROUP1;
27882 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27883 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27884 	    SD_PATH_STANDARD);
27885 	kmem_free(com, sizeof (*com));
27886 	return (rval);
27887 }
27888 
27889 
27890 /*
27891  *    Function: sr_read_all_subcodes()
27892  *
27893  * Description: This routine is the driver entry point for handling CD-ROM
27894  *		ioctl requests to return raw subcode data while the target is
27895  *		playing audio (CDROMSUBCODE).
27896  *
27897  *   Arguments: dev	- the device 'dev_t'
27898  *		data	- pointer to user provided cdrom subcode structure,
27899  *		          specifying the transfer length and address.
27900  *		flag	- this argument is a pass through to ddi_copyxxx()
27901  *		          directly from the mode argument of ioctl().
27902  *
27903  * Return Code: the code returned by sd_send_scsi_cmd()
27904  *		EFAULT if ddi_copyxxx() fails
27905  *		ENXIO if fail ddi_get_soft_state
27906  *		EINVAL if data pointer is NULL
27907  */
27908 
27909 static int
27910 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
27911 {
27912 	struct sd_lun		*un = NULL;
27913 	struct uscsi_cmd	*com = NULL;
27914 	struct cdrom_subcode	*subcode = NULL;
27915 	int			rval;
27916 	size_t			buflen;
27917 	char			cdb[CDB_GROUP5];
27918 
27919 #ifdef _MULTI_DATAMODEL
27920 	/* To support ILP32 applications in an LP64 world */
27921 	struct cdrom_subcode32		cdrom_subcode32;
27922 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
27923 #endif
27924 	if (data == NULL) {
27925 		return (EINVAL);
27926 	}
27927 
27928 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27929 		return (ENXIO);
27930 	}
27931 
27932 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
27933 
27934 #ifdef _MULTI_DATAMODEL
27935 	switch (ddi_model_convert_from(flag & FMODELS)) {
27936 	case DDI_MODEL_ILP32:
27937 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
27938 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27939 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27940 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27941 			return (EFAULT);
27942 		}
27943 		/* Convert the ILP32 uscsi data from the application to LP64 */
27944 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
27945 		break;
27946 	case DDI_MODEL_NONE:
27947 		if (ddi_copyin(data, subcode,
27948 		    sizeof (struct cdrom_subcode), flag)) {
27949 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27950 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27951 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27952 			return (EFAULT);
27953 		}
27954 		break;
27955 	}
27956 #else /* ! _MULTI_DATAMODEL */
27957 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
27958 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27959 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
27960 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27961 		return (EFAULT);
27962 	}
27963 #endif /* _MULTI_DATAMODEL */
27964 
27965 	/*
27966 	 * Since MMC-2 expects max 3 bytes for length, check if the
27967 	 * length input is greater than 3 bytes
27968 	 */
27969 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
27970 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27971 		    "sr_read_all_subcodes: "
27972 		    "cdrom transfer length too large: %d (limit %d)\n",
27973 		    subcode->cdsc_length, 0xFFFFFF);
27974 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27975 		return (EINVAL);
27976 	}
27977 
27978 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
27979 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27980 	bzero(cdb, CDB_GROUP5);
27981 
27982 	if (un->un_f_mmc_cap == TRUE) {
27983 		cdb[0] = (char)SCMD_READ_CD;
27984 		cdb[2] = (char)0xff;
27985 		cdb[3] = (char)0xff;
27986 		cdb[4] = (char)0xff;
27987 		cdb[5] = (char)0xff;
27988 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27989 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27990 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
27991 		cdb[10] = 1;
27992 	} else {
27993 		/*
27994 		 * Note: A vendor specific command (0xDF) is being used here to
27995 		 * request a read of all subcodes.
27996 		 */
27997 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
27998 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
27999 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
28000 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
28001 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
28002 	}
28003 	com->uscsi_cdb	   = cdb;
28004 	com->uscsi_cdblen  = CDB_GROUP5;
28005 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
28006 	com->uscsi_buflen  = buflen;
28007 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28008 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28009 	    SD_PATH_STANDARD);
28010 	kmem_free(subcode, sizeof (struct cdrom_subcode));
28011 	kmem_free(com, sizeof (*com));
28012 	return (rval);
28013 }
28014 
28015 
28016 /*
28017  *    Function: sr_read_subchannel()
28018  *
28019  * Description: This routine is the driver entry point for handling CD-ROM
28020  *		ioctl requests to return the Q sub-channel data of the CD
28021  *		current position block. (CDROMSUBCHNL) The data includes the
28022  *		track number, index number, absolute CD-ROM address (LBA or MSF
28023  *		format per the user) , track relative CD-ROM address (LBA or MSF
28024  *		format per the user), control data and audio status.
28025  *
28026  *   Arguments: dev	- the device 'dev_t'
28027  *		data	- pointer to user provided cdrom sub-channel structure
28028  *		flag	- this argument is a pass through to ddi_copyxxx()
28029  *		          directly from the mode argument of ioctl().
28030  *
28031  * Return Code: the code returned by sd_send_scsi_cmd()
28032  *		EFAULT if ddi_copyxxx() fails
28033  *		ENXIO if fail ddi_get_soft_state
28034  *		EINVAL if data pointer is NULL
28035  */
28036 
28037 static int
28038 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
28039 {
28040 	struct sd_lun		*un;
28041 	struct uscsi_cmd	*com;
28042 	struct cdrom_subchnl	subchanel;
28043 	struct cdrom_subchnl	*subchnl = &subchanel;
28044 	char			cdb[CDB_GROUP1];
28045 	caddr_t			buffer;
28046 	int			rval;
28047 
28048 	if (data == NULL) {
28049 		return (EINVAL);
28050 	}
28051 
28052 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28053 	    (un->un_state == SD_STATE_OFFLINE)) {
28054 		return (ENXIO);
28055 	}
28056 
28057 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
28058 		return (EFAULT);
28059 	}
28060 
28061 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
28062 	bzero(cdb, CDB_GROUP1);
28063 	cdb[0] = SCMD_READ_SUBCHANNEL;
28064 	/* Set the MSF bit based on the user requested address format */
28065 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
28066 	/*
28067 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
28068 	 * returned
28069 	 */
28070 	cdb[2] = 0x40;
28071 	/*
28072 	 * Set byte 3 to specify the return data format. A value of 0x01
28073 	 * indicates that the CD-ROM current position should be returned.
28074 	 */
28075 	cdb[3] = 0x01;
28076 	cdb[8] = 0x10;
28077 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28078 	com->uscsi_cdb	   = cdb;
28079 	com->uscsi_cdblen  = CDB_GROUP1;
28080 	com->uscsi_bufaddr = buffer;
28081 	com->uscsi_buflen  = 16;
28082 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28083 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28084 	    SD_PATH_STANDARD);
28085 	if (rval != 0) {
28086 		kmem_free(buffer, 16);
28087 		kmem_free(com, sizeof (*com));
28088 		return (rval);
28089 	}
28090 
28091 	/* Process the returned Q sub-channel data */
28092 	subchnl->cdsc_audiostatus = buffer[1];
28093 	subchnl->cdsc_adr	= (buffer[5] & 0xF0) >> 4;
28094 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
28095 	subchnl->cdsc_trk	= buffer[6];
28096 	subchnl->cdsc_ind	= buffer[7];
28097 	if (subchnl->cdsc_format & CDROM_LBA) {
28098 		subchnl->cdsc_absaddr.lba =
28099 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
28100 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
28101 		subchnl->cdsc_reladdr.lba =
28102 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
28103 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
28104 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
28105 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
28106 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
28107 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
28108 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
28109 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
28110 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
28111 	} else {
28112 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
28113 		subchnl->cdsc_absaddr.msf.second = buffer[10];
28114 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
28115 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
28116 		subchnl->cdsc_reladdr.msf.second = buffer[14];
28117 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
28118 	}
28119 	kmem_free(buffer, 16);
28120 	kmem_free(com, sizeof (*com));
28121 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
28122 	    != 0) {
28123 		return (EFAULT);
28124 	}
28125 	return (rval);
28126 }
28127 
28128 
28129 /*
28130  *    Function: sr_read_tocentry()
28131  *
28132  * Description: This routine is the driver entry point for handling CD-ROM
28133  *		ioctl requests to read from the Table of Contents (TOC)
28134  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
28135  *		fields, the starting address (LBA or MSF format per the user)
28136  *		and the data mode if the user specified track is a data track.
28137  *
28138  *		Note: The READ HEADER (0x44) command used in this routine is
28139  *		obsolete per the SCSI MMC spec but still supported in the
28140  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
28141  *		therefore the command is still implemented in this routine.
28142  *
28143  *   Arguments: dev	- the device 'dev_t'
28144  *		data	- pointer to user provided toc entry structure,
28145  *			  specifying the track # and the address format
28146  *			  (LBA or MSF).
28147  *		flag	- this argument is a pass through to ddi_copyxxx()
28148  *		          directly from the mode argument of ioctl().
28149  *
28150  * Return Code: the code returned by sd_send_scsi_cmd()
28151  *		EFAULT if ddi_copyxxx() fails
28152  *		ENXIO if fail ddi_get_soft_state
28153  *		EINVAL if data pointer is NULL
28154  */
28155 
28156 static int
28157 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
28158 {
28159 	struct sd_lun		*un = NULL;
28160 	struct uscsi_cmd	*com;
28161 	struct cdrom_tocentry	toc_entry;
28162 	struct cdrom_tocentry	*entry = &toc_entry;
28163 	caddr_t			buffer;
28164 	int			rval;
28165 	char			cdb[CDB_GROUP1];
28166 
28167 	if (data == NULL) {
28168 		return (EINVAL);
28169 	}
28170 
28171 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28172 	    (un->un_state == SD_STATE_OFFLINE)) {
28173 		return (ENXIO);
28174 	}
28175 
28176 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
28177 		return (EFAULT);
28178 	}
28179 
28180 	/* Validate the requested track and address format */
28181 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
28182 		return (EINVAL);
28183 	}
28184 
28185 	if (entry->cdte_track == 0) {
28186 		return (EINVAL);
28187 	}
28188 
28189 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
28190 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28191 	bzero(cdb, CDB_GROUP1);
28192 
28193 	cdb[0] = SCMD_READ_TOC;
28194 	/* Set the MSF bit based on the user requested address format  */
28195 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
28196 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
28197 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
28198 	} else {
28199 		cdb[6] = entry->cdte_track;
28200 	}
28201 
28202 	/*
28203 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
28204 	 * (4 byte TOC response header + 8 byte track descriptor)
28205 	 */
28206 	cdb[8] = 12;
28207 	com->uscsi_cdb	   = cdb;
28208 	com->uscsi_cdblen  = CDB_GROUP1;
28209 	com->uscsi_bufaddr = buffer;
28210 	com->uscsi_buflen  = 0x0C;
28211 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
28212 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28213 	    SD_PATH_STANDARD);
28214 	if (rval != 0) {
28215 		kmem_free(buffer, 12);
28216 		kmem_free(com, sizeof (*com));
28217 		return (rval);
28218 	}
28219 
28220 	/* Process the toc entry */
28221 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
28222 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
28223 	if (entry->cdte_format & CDROM_LBA) {
28224 		entry->cdte_addr.lba =
28225 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
28226 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
28227 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
28228 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
28229 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
28230 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
28231 		/*
28232 		 * Send a READ TOC command using the LBA address format to get
28233 		 * the LBA for the track requested so it can be used in the
28234 		 * READ HEADER request
28235 		 *
28236 		 * Note: The MSF bit of the READ HEADER command specifies the
28237 		 * output format. The block address specified in that command
28238 		 * must be in LBA format.
28239 		 */
28240 		cdb[1] = 0;
28241 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28242 		    SD_PATH_STANDARD);
28243 		if (rval != 0) {
28244 			kmem_free(buffer, 12);
28245 			kmem_free(com, sizeof (*com));
28246 			return (rval);
28247 		}
28248 	} else {
28249 		entry->cdte_addr.msf.minute	= buffer[9];
28250 		entry->cdte_addr.msf.second	= buffer[10];
28251 		entry->cdte_addr.msf.frame	= buffer[11];
28252 		/*
28253 		 * Send a READ TOC command using the LBA address format to get
28254 		 * the LBA for the track requested so it can be used in the
28255 		 * READ HEADER request
28256 		 *
28257 		 * Note: The MSF bit of the READ HEADER command specifies the
28258 		 * output format. The block address specified in that command
28259 		 * must be in LBA format.
28260 		 */
28261 		cdb[1] = 0;
28262 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28263 		    SD_PATH_STANDARD);
28264 		if (rval != 0) {
28265 			kmem_free(buffer, 12);
28266 			kmem_free(com, sizeof (*com));
28267 			return (rval);
28268 		}
28269 	}
28270 
28271 	/*
28272 	 * Build and send the READ HEADER command to determine the data mode of
28273 	 * the user specified track.
28274 	 */
28275 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
28276 	    (entry->cdte_track != CDROM_LEADOUT)) {
28277 		bzero(cdb, CDB_GROUP1);
28278 		cdb[0] = SCMD_READ_HEADER;
28279 		cdb[2] = buffer[8];
28280 		cdb[3] = buffer[9];
28281 		cdb[4] = buffer[10];
28282 		cdb[5] = buffer[11];
28283 		cdb[8] = 0x08;
28284 		com->uscsi_buflen = 0x08;
28285 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28286 		    SD_PATH_STANDARD);
28287 		if (rval == 0) {
28288 			entry->cdte_datamode = buffer[0];
28289 		} else {
28290 			/*
28291 			 * READ HEADER command failed, since this is
28292 			 * obsoleted in one spec, its better to return
28293 			 * -1 for an invlid track so that we can still
28294 			 * receive the rest of the TOC data.
28295 			 */
28296 			entry->cdte_datamode = (uchar_t)-1;
28297 		}
28298 	} else {
28299 		entry->cdte_datamode = (uchar_t)-1;
28300 	}
28301 
28302 	kmem_free(buffer, 12);
28303 	kmem_free(com, sizeof (*com));
28304 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
28305 		return (EFAULT);
28306 
28307 	return (rval);
28308 }
28309 
28310 
28311 /*
28312  *    Function: sr_read_tochdr()
28313  *
28314  * Description: This routine is the driver entry point for handling CD-ROM
28315  *		ioctl requests to read the Table of Contents (TOC) header
28316  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
28317  *		and ending track numbers
28318  *
28319  *   Arguments: dev	- the device 'dev_t'
28320  *		data	- pointer to user provided toc header structure,
28321  *			  specifying the starting and ending track numbers.
28322  *		flag	- this argument is a pass through to ddi_copyxxx()
28323  *			  directly from the mode argument of ioctl().
28324  *
28325  * Return Code: the code returned by sd_send_scsi_cmd()
28326  *		EFAULT if ddi_copyxxx() fails
28327  *		ENXIO if fail ddi_get_soft_state
28328  *		EINVAL if data pointer is NULL
28329  */
28330 
28331 static int
28332 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
28333 {
28334 	struct sd_lun		*un;
28335 	struct uscsi_cmd	*com;
28336 	struct cdrom_tochdr	toc_header;
28337 	struct cdrom_tochdr	*hdr = &toc_header;
28338 	char			cdb[CDB_GROUP1];
28339 	int			rval;
28340 	caddr_t			buffer;
28341 
28342 	if (data == NULL) {
28343 		return (EINVAL);
28344 	}
28345 
28346 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28347 	    (un->un_state == SD_STATE_OFFLINE)) {
28348 		return (ENXIO);
28349 	}
28350 
28351 	buffer = kmem_zalloc(4, KM_SLEEP);
28352 	bzero(cdb, CDB_GROUP1);
28353 	cdb[0] = SCMD_READ_TOC;
28354 	/*
28355 	 * Specifying a track number of 0x00 in the READ TOC command indicates
28356 	 * that the TOC header should be returned
28357 	 */
28358 	cdb[6] = 0x00;
28359 	/*
28360 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
28361 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
28362 	 */
28363 	cdb[8] = 0x04;
28364 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28365 	com->uscsi_cdb	   = cdb;
28366 	com->uscsi_cdblen  = CDB_GROUP1;
28367 	com->uscsi_bufaddr = buffer;
28368 	com->uscsi_buflen  = 0x04;
28369 	com->uscsi_timeout = 300;
28370 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28371 
28372 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28373 	    SD_PATH_STANDARD);
28374 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
28375 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
28376 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
28377 	} else {
28378 		hdr->cdth_trk0 = buffer[2];
28379 		hdr->cdth_trk1 = buffer[3];
28380 	}
28381 	kmem_free(buffer, 4);
28382 	kmem_free(com, sizeof (*com));
28383 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
28384 		return (EFAULT);
28385 	}
28386 	return (rval);
28387 }
28388 
28389 
28390 /*
28391  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
28392  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
28393  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
28394  * digital audio and extended architecture digital audio. These modes are
28395  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
28396  * MMC specs.
28397  *
28398  * In addition to support for the various data formats these routines also
28399  * include support for devices that implement only the direct access READ
28400  * commands (0x08, 0x28), devices that implement the READ_CD commands
28401  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
28402  * READ CDXA commands (0xD8, 0xDB)
28403  */
28404 
28405 /*
28406  *    Function: sr_read_mode1()
28407  *
28408  * Description: This routine is the driver entry point for handling CD-ROM
28409  *		ioctl read mode1 requests (CDROMREADMODE1).
28410  *
28411  *   Arguments: dev	- the device 'dev_t'
28412  *		data	- pointer to user provided cd read structure specifying
28413  *			  the lba buffer address and length.
28414  *		flag	- this argument is a pass through to ddi_copyxxx()
28415  *			  directly from the mode argument of ioctl().
28416  *
28417  * Return Code: the code returned by sd_send_scsi_cmd()
28418  *		EFAULT if ddi_copyxxx() fails
28419  *		ENXIO if fail ddi_get_soft_state
28420  *		EINVAL if data pointer is NULL
28421  */
28422 
28423 static int
28424 sr_read_mode1(dev_t dev, caddr_t data, int flag)
28425 {
28426 	struct sd_lun		*un;
28427 	struct cdrom_read	mode1_struct;
28428 	struct cdrom_read	*mode1 = &mode1_struct;
28429 	int			rval;
28430 	sd_ssc_t		*ssc;
28431 
28432 #ifdef _MULTI_DATAMODEL
28433 	/* To support ILP32 applications in an LP64 world */
28434 	struct cdrom_read32	cdrom_read32;
28435 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28436 #endif /* _MULTI_DATAMODEL */
28437 
28438 	if (data == NULL) {
28439 		return (EINVAL);
28440 	}
28441 
28442 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28443 	    (un->un_state == SD_STATE_OFFLINE)) {
28444 		return (ENXIO);
28445 	}
28446 
28447 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28448 	    "sd_read_mode1: entry: un:0x%p\n", un);
28449 
28450 #ifdef _MULTI_DATAMODEL
28451 	switch (ddi_model_convert_from(flag & FMODELS)) {
28452 	case DDI_MODEL_ILP32:
28453 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28454 			return (EFAULT);
28455 		}
28456 		/* Convert the ILP32 uscsi data from the application to LP64 */
28457 		cdrom_read32tocdrom_read(cdrd32, mode1);
28458 		break;
28459 	case DDI_MODEL_NONE:
28460 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28461 			return (EFAULT);
28462 		}
28463 	}
28464 #else /* ! _MULTI_DATAMODEL */
28465 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28466 		return (EFAULT);
28467 	}
28468 #endif /* _MULTI_DATAMODEL */
28469 
28470 	ssc = sd_ssc_init(un);
28471 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
28472 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
28473 	sd_ssc_fini(ssc);
28474 
28475 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28476 	    "sd_read_mode1: exit: un:0x%p\n", un);
28477 
28478 	return (rval);
28479 }
28480 
28481 
28482 /*
28483  *    Function: sr_read_cd_mode2()
28484  *
28485  * Description: This routine is the driver entry point for handling CD-ROM
28486  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28487  *		support the READ CD (0xBE) command or the 1st generation
28488  *		READ CD (0xD4) command.
28489  *
28490  *   Arguments: dev	- the device 'dev_t'
28491  *		data	- pointer to user provided cd read structure specifying
28492  *			  the lba buffer address and length.
28493  *		flag	- this argument is a pass through to ddi_copyxxx()
28494  *			  directly from the mode argument of ioctl().
28495  *
28496  * Return Code: the code returned by sd_send_scsi_cmd()
28497  *		EFAULT if ddi_copyxxx() fails
28498  *		ENXIO if fail ddi_get_soft_state
28499  *		EINVAL if data pointer is NULL
28500  */
28501 
28502 static int
28503 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
28504 {
28505 	struct sd_lun		*un;
28506 	struct uscsi_cmd	*com;
28507 	struct cdrom_read	mode2_struct;
28508 	struct cdrom_read	*mode2 = &mode2_struct;
28509 	uchar_t			cdb[CDB_GROUP5];
28510 	int			nblocks;
28511 	int			rval;
28512 #ifdef _MULTI_DATAMODEL
28513 	/*  To support ILP32 applications in an LP64 world */
28514 	struct cdrom_read32	cdrom_read32;
28515 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28516 #endif /* _MULTI_DATAMODEL */
28517 
28518 	if (data == NULL) {
28519 		return (EINVAL);
28520 	}
28521 
28522 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28523 	    (un->un_state == SD_STATE_OFFLINE)) {
28524 		return (ENXIO);
28525 	}
28526 
28527 #ifdef _MULTI_DATAMODEL
28528 	switch (ddi_model_convert_from(flag & FMODELS)) {
28529 	case DDI_MODEL_ILP32:
28530 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28531 			return (EFAULT);
28532 		}
28533 		/* Convert the ILP32 uscsi data from the application to LP64 */
28534 		cdrom_read32tocdrom_read(cdrd32, mode2);
28535 		break;
28536 	case DDI_MODEL_NONE:
28537 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28538 			return (EFAULT);
28539 		}
28540 		break;
28541 	}
28542 
28543 #else /* ! _MULTI_DATAMODEL */
28544 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28545 		return (EFAULT);
28546 	}
28547 #endif /* _MULTI_DATAMODEL */
28548 
28549 	bzero(cdb, sizeof (cdb));
28550 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
28551 		/* Read command supported by 1st generation atapi drives */
28552 		cdb[0] = SCMD_READ_CDD4;
28553 	} else {
28554 		/* Universal CD Access Command */
28555 		cdb[0] = SCMD_READ_CD;
28556 	}
28557 
28558 	/*
28559 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
28560 	 */
28561 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
28562 
28563 	/* set the start address */
28564 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
28565 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
28566 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28567 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
28568 
28569 	/* set the transfer length */
28570 	nblocks = mode2->cdread_buflen / 2336;
28571 	cdb[6] = (uchar_t)(nblocks >> 16);
28572 	cdb[7] = (uchar_t)(nblocks >> 8);
28573 	cdb[8] = (uchar_t)nblocks;
28574 
28575 	/* set the filter bits */
28576 	cdb[9] = CDROM_READ_CD_USERDATA;
28577 
28578 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28579 	com->uscsi_cdb = (caddr_t)cdb;
28580 	com->uscsi_cdblen = sizeof (cdb);
28581 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28582 	com->uscsi_buflen = mode2->cdread_buflen;
28583 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28584 
28585 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28586 	    SD_PATH_STANDARD);
28587 	kmem_free(com, sizeof (*com));
28588 	return (rval);
28589 }
28590 
28591 
28592 /*
28593  *    Function: sr_read_mode2()
28594  *
28595  * Description: This routine is the driver entry point for handling CD-ROM
28596  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28597  *		do not support the READ CD (0xBE) command.
28598  *
28599  *   Arguments: dev	- the device 'dev_t'
28600  *		data	- pointer to user provided cd read structure specifying
28601  *			  the lba buffer address and length.
28602  *		flag	- this argument is a pass through to ddi_copyxxx()
28603  *			  directly from the mode argument of ioctl().
28604  *
28605  * Return Code: the code returned by sd_send_scsi_cmd()
28606  *		EFAULT if ddi_copyxxx() fails
28607  *		ENXIO if fail ddi_get_soft_state
28608  *		EINVAL if data pointer is NULL
28609  *		EIO if fail to reset block size
28610  *		EAGAIN if commands are in progress in the driver
28611  */
28612 
28613 static int
28614 sr_read_mode2(dev_t dev, caddr_t data, int flag)
28615 {
28616 	struct sd_lun		*un;
28617 	struct cdrom_read	mode2_struct;
28618 	struct cdrom_read	*mode2 = &mode2_struct;
28619 	int			rval;
28620 	uint32_t		restore_blksize;
28621 	struct uscsi_cmd	*com;
28622 	uchar_t			cdb[CDB_GROUP0];
28623 	int			nblocks;
28624 
28625 #ifdef _MULTI_DATAMODEL
28626 	/* To support ILP32 applications in an LP64 world */
28627 	struct cdrom_read32	cdrom_read32;
28628 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28629 #endif /* _MULTI_DATAMODEL */
28630 
28631 	if (data == NULL) {
28632 		return (EINVAL);
28633 	}
28634 
28635 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28636 	    (un->un_state == SD_STATE_OFFLINE)) {
28637 		return (ENXIO);
28638 	}
28639 
28640 	/*
28641 	 * Because this routine will update the device and driver block size
28642 	 * being used we want to make sure there are no commands in progress.
28643 	 * If commands are in progress the user will have to try again.
28644 	 *
28645 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
28646 	 * in sdioctl to protect commands from sdioctl through to the top of
28647 	 * sd_uscsi_strategy. See sdioctl for details.
28648 	 */
28649 	mutex_enter(SD_MUTEX(un));
28650 	if (un->un_ncmds_in_driver != 1) {
28651 		mutex_exit(SD_MUTEX(un));
28652 		return (EAGAIN);
28653 	}
28654 	mutex_exit(SD_MUTEX(un));
28655 
28656 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28657 	    "sd_read_mode2: entry: un:0x%p\n", un);
28658 
28659 #ifdef _MULTI_DATAMODEL
28660 	switch (ddi_model_convert_from(flag & FMODELS)) {
28661 	case DDI_MODEL_ILP32:
28662 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28663 			return (EFAULT);
28664 		}
28665 		/* Convert the ILP32 uscsi data from the application to LP64 */
28666 		cdrom_read32tocdrom_read(cdrd32, mode2);
28667 		break;
28668 	case DDI_MODEL_NONE:
28669 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28670 			return (EFAULT);
28671 		}
28672 		break;
28673 	}
28674 #else /* ! _MULTI_DATAMODEL */
28675 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
28676 		return (EFAULT);
28677 	}
28678 #endif /* _MULTI_DATAMODEL */
28679 
28680 	/* Store the current target block size for restoration later */
28681 	restore_blksize = un->un_tgt_blocksize;
28682 
28683 	/* Change the device and soft state target block size to 2336 */
28684 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
28685 		rval = EIO;
28686 		goto done;
28687 	}
28688 
28689 
28690 	bzero(cdb, sizeof (cdb));
28691 
28692 	/* set READ operation */
28693 	cdb[0] = SCMD_READ;
28694 
28695 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
28696 	mode2->cdread_lba >>= 2;
28697 
28698 	/* set the start address */
28699 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
28700 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28701 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
28702 
28703 	/* set the transfer length */
28704 	nblocks = mode2->cdread_buflen / 2336;
28705 	cdb[4] = (uchar_t)nblocks & 0xFF;
28706 
28707 	/* build command */
28708 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28709 	com->uscsi_cdb = (caddr_t)cdb;
28710 	com->uscsi_cdblen = sizeof (cdb);
28711 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28712 	com->uscsi_buflen = mode2->cdread_buflen;
28713 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28714 
28715 	/*
28716 	 * Issue SCSI command with user space address for read buffer.
28717 	 *
28718 	 * This sends the command through main channel in the driver.
28719 	 *
28720 	 * Since this is accessed via an IOCTL call, we go through the
28721 	 * standard path, so that if the device was powered down, then
28722 	 * it would be 'awakened' to handle the command.
28723 	 */
28724 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28725 	    SD_PATH_STANDARD);
28726 
28727 	kmem_free(com, sizeof (*com));
28728 
28729 	/* Restore the device and soft state target block size */
28730 	if (sr_sector_mode(dev, restore_blksize) != 0) {
28731 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28732 		    "can't do switch back to mode 1\n");
28733 		/*
28734 		 * If sd_send_scsi_READ succeeded we still need to report
28735 		 * an error because we failed to reset the block size
28736 		 */
28737 		if (rval == 0) {
28738 			rval = EIO;
28739 		}
28740 	}
28741 
28742 done:
28743 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28744 	    "sd_read_mode2: exit: un:0x%p\n", un);
28745 
28746 	return (rval);
28747 }
28748 
28749 
28750 /*
28751  *    Function: sr_sector_mode()
28752  *
28753  * Description: This utility function is used by sr_read_mode2 to set the target
28754  *		block size based on the user specified size. This is a legacy
28755  *		implementation based upon a vendor specific mode page
28756  *
28757  *   Arguments: dev	- the device 'dev_t'
28758  *		data	- flag indicating if block size is being set to 2336 or
28759  *			  512.
28760  *
28761  * Return Code: the code returned by sd_send_scsi_cmd()
28762  *		EFAULT if ddi_copyxxx() fails
28763  *		ENXIO if fail ddi_get_soft_state
28764  *		EINVAL if data pointer is NULL
28765  */
28766 
28767 static int
28768 sr_sector_mode(dev_t dev, uint32_t blksize)
28769 {
28770 	struct sd_lun	*un;
28771 	uchar_t		*sense;
28772 	uchar_t		*select;
28773 	int		rval;
28774 	sd_ssc_t	*ssc;
28775 
28776 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28777 	    (un->un_state == SD_STATE_OFFLINE)) {
28778 		return (ENXIO);
28779 	}
28780 
28781 	sense = kmem_zalloc(20, KM_SLEEP);
28782 
28783 	/* Note: This is a vendor specific mode page (0x81) */
28784 	ssc = sd_ssc_init(un);
28785 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
28786 	    SD_PATH_STANDARD);
28787 	sd_ssc_fini(ssc);
28788 	if (rval != 0) {
28789 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28790 		    "sr_sector_mode: Mode Sense failed\n");
28791 		kmem_free(sense, 20);
28792 		return (rval);
28793 	}
28794 	select = kmem_zalloc(20, KM_SLEEP);
28795 	select[3] = 0x08;
28796 	select[10] = ((blksize >> 8) & 0xff);
28797 	select[11] = (blksize & 0xff);
28798 	select[12] = 0x01;
28799 	select[13] = 0x06;
28800 	select[14] = sense[14];
28801 	select[15] = sense[15];
28802 	if (blksize == SD_MODE2_BLKSIZE) {
28803 		select[14] |= 0x01;
28804 	}
28805 
28806 	ssc = sd_ssc_init(un);
28807 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
28808 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28809 	sd_ssc_fini(ssc);
28810 	if (rval != 0) {
28811 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28812 		    "sr_sector_mode: Mode Select failed\n");
28813 	} else {
28814 		/*
28815 		 * Only update the softstate block size if we successfully
28816 		 * changed the device block mode.
28817 		 */
28818 		mutex_enter(SD_MUTEX(un));
28819 		sd_update_block_info(un, blksize, 0);
28820 		mutex_exit(SD_MUTEX(un));
28821 	}
28822 	kmem_free(sense, 20);
28823 	kmem_free(select, 20);
28824 	return (rval);
28825 }
28826 
28827 
28828 /*
28829  *    Function: sr_read_cdda()
28830  *
28831  * Description: This routine is the driver entry point for handling CD-ROM
28832  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
28833  *		the target supports CDDA these requests are handled via a vendor
28834  *		specific command (0xD8) If the target does not support CDDA
28835  *		these requests are handled via the READ CD command (0xBE).
28836  *
28837  *   Arguments: dev	- the device 'dev_t'
28838  *		data	- pointer to user provided CD-DA structure specifying
28839  *			  the track starting address, transfer length, and
28840  *			  subcode options.
28841  *		flag	- this argument is a pass through to ddi_copyxxx()
28842  *			  directly from the mode argument of ioctl().
28843  *
28844  * Return Code: the code returned by sd_send_scsi_cmd()
28845  *		EFAULT if ddi_copyxxx() fails
28846  *		ENXIO if fail ddi_get_soft_state
28847  *		EINVAL if invalid arguments are provided
28848  *		ENOTTY
28849  */
28850 
28851 static int
28852 sr_read_cdda(dev_t dev, caddr_t data, int flag)
28853 {
28854 	struct sd_lun			*un;
28855 	struct uscsi_cmd		*com;
28856 	struct cdrom_cdda		*cdda;
28857 	int				rval;
28858 	size_t				buflen;
28859 	char				cdb[CDB_GROUP5];
28860 
28861 #ifdef _MULTI_DATAMODEL
28862 	/* To support ILP32 applications in an LP64 world */
28863 	struct cdrom_cdda32	cdrom_cdda32;
28864 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
28865 #endif /* _MULTI_DATAMODEL */
28866 
28867 	if (data == NULL) {
28868 		return (EINVAL);
28869 	}
28870 
28871 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28872 		return (ENXIO);
28873 	}
28874 
28875 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
28876 
28877 #ifdef _MULTI_DATAMODEL
28878 	switch (ddi_model_convert_from(flag & FMODELS)) {
28879 	case DDI_MODEL_ILP32:
28880 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
28881 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28882 			    "sr_read_cdda: ddi_copyin Failed\n");
28883 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28884 			return (EFAULT);
28885 		}
28886 		/* Convert the ILP32 uscsi data from the application to LP64 */
28887 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
28888 		break;
28889 	case DDI_MODEL_NONE:
28890 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28891 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28892 			    "sr_read_cdda: ddi_copyin Failed\n");
28893 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28894 			return (EFAULT);
28895 		}
28896 		break;
28897 	}
28898 #else /* ! _MULTI_DATAMODEL */
28899 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28900 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28901 		    "sr_read_cdda: ddi_copyin Failed\n");
28902 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28903 		return (EFAULT);
28904 	}
28905 #endif /* _MULTI_DATAMODEL */
28906 
28907 	/*
28908 	 * Since MMC-2 expects max 3 bytes for length, check if the
28909 	 * length input is greater than 3 bytes
28910 	 */
28911 	if ((cdda->cdda_length & 0xFF000000) != 0) {
28912 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
28913 		    "cdrom transfer length too large: %d (limit %d)\n",
28914 		    cdda->cdda_length, 0xFFFFFF);
28915 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28916 		return (EINVAL);
28917 	}
28918 
28919 	switch (cdda->cdda_subcode) {
28920 	case CDROM_DA_NO_SUBCODE:
28921 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
28922 		break;
28923 	case CDROM_DA_SUBQ:
28924 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
28925 		break;
28926 	case CDROM_DA_ALL_SUBCODE:
28927 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
28928 		break;
28929 	case CDROM_DA_SUBCODE_ONLY:
28930 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
28931 		break;
28932 	default:
28933 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28934 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
28935 		    cdda->cdda_subcode);
28936 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28937 		return (EINVAL);
28938 	}
28939 
28940 	/* Build and send the command */
28941 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28942 	bzero(cdb, CDB_GROUP5);
28943 
28944 	if (un->un_f_cfg_cdda == TRUE) {
28945 		cdb[0] = (char)SCMD_READ_CD;
28946 		cdb[1] = 0x04;
28947 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28948 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28949 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28950 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28951 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28952 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28953 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
28954 		cdb[9] = 0x10;
28955 		switch (cdda->cdda_subcode) {
28956 		case CDROM_DA_NO_SUBCODE :
28957 			cdb[10] = 0x0;
28958 			break;
28959 		case CDROM_DA_SUBQ :
28960 			cdb[10] = 0x2;
28961 			break;
28962 		case CDROM_DA_ALL_SUBCODE :
28963 			cdb[10] = 0x1;
28964 			break;
28965 		case CDROM_DA_SUBCODE_ONLY :
28966 			/* FALLTHROUGH */
28967 		default :
28968 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28969 			kmem_free(com, sizeof (*com));
28970 			return (ENOTTY);
28971 		}
28972 	} else {
28973 		cdb[0] = (char)SCMD_READ_CDDA;
28974 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28975 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28976 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28977 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28978 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
28979 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28980 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28981 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
28982 		cdb[10] = cdda->cdda_subcode;
28983 	}
28984 
28985 	com->uscsi_cdb = cdb;
28986 	com->uscsi_cdblen = CDB_GROUP5;
28987 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
28988 	com->uscsi_buflen = buflen;
28989 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28990 
28991 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28992 	    SD_PATH_STANDARD);
28993 
28994 	kmem_free(cdda, sizeof (struct cdrom_cdda));
28995 	kmem_free(com, sizeof (*com));
28996 	return (rval);
28997 }
28998 
28999 
29000 /*
29001  *    Function: sr_read_cdxa()
29002  *
29003  * Description: This routine is the driver entry point for handling CD-ROM
29004  *		ioctl requests to return CD-XA (Extended Architecture) data.
29005  *		(CDROMCDXA).
29006  *
29007  *   Arguments: dev	- the device 'dev_t'
29008  *		data	- pointer to user provided CD-XA structure specifying
29009  *			  the data starting address, transfer length, and format
29010  *		flag	- this argument is a pass through to ddi_copyxxx()
29011  *			  directly from the mode argument of ioctl().
29012  *
29013  * Return Code: the code returned by sd_send_scsi_cmd()
29014  *		EFAULT if ddi_copyxxx() fails
29015  *		ENXIO if fail ddi_get_soft_state
29016  *		EINVAL if data pointer is NULL
29017  */
29018 
29019 static int
29020 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
29021 {
29022 	struct sd_lun		*un;
29023 	struct uscsi_cmd	*com;
29024 	struct cdrom_cdxa	*cdxa;
29025 	int			rval;
29026 	size_t			buflen;
29027 	char			cdb[CDB_GROUP5];
29028 	uchar_t			read_flags;
29029 
29030 #ifdef _MULTI_DATAMODEL
29031 	/* To support ILP32 applications in an LP64 world */
29032 	struct cdrom_cdxa32		cdrom_cdxa32;
29033 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
29034 #endif /* _MULTI_DATAMODEL */
29035 
29036 	if (data == NULL) {
29037 		return (EINVAL);
29038 	}
29039 
29040 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
29041 		return (ENXIO);
29042 	}
29043 
29044 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
29045 
29046 #ifdef _MULTI_DATAMODEL
29047 	switch (ddi_model_convert_from(flag & FMODELS)) {
29048 	case DDI_MODEL_ILP32:
29049 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
29050 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
29051 			return (EFAULT);
29052 		}
29053 		/*
29054 		 * Convert the ILP32 uscsi data from the
29055 		 * application to LP64 for internal use.
29056 		 */
29057 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
29058 		break;
29059 	case DDI_MODEL_NONE:
29060 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
29061 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
29062 			return (EFAULT);
29063 		}
29064 		break;
29065 	}
29066 #else /* ! _MULTI_DATAMODEL */
29067 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
29068 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
29069 		return (EFAULT);
29070 	}
29071 #endif /* _MULTI_DATAMODEL */
29072 
29073 	/*
29074 	 * Since MMC-2 expects max 3 bytes for length, check if the
29075 	 * length input is greater than 3 bytes
29076 	 */
29077 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
29078 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
29079 		    "cdrom transfer length too large: %d (limit %d)\n",
29080 		    cdxa->cdxa_length, 0xFFFFFF);
29081 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
29082 		return (EINVAL);
29083 	}
29084 
29085 	switch (cdxa->cdxa_format) {
29086 	case CDROM_XA_DATA:
29087 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
29088 		read_flags = 0x10;
29089 		break;
29090 	case CDROM_XA_SECTOR_DATA:
29091 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
29092 		read_flags = 0xf8;
29093 		break;
29094 	case CDROM_XA_DATA_W_ERROR:
29095 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
29096 		read_flags = 0xfc;
29097 		break;
29098 	default:
29099 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29100 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
29101 		    cdxa->cdxa_format);
29102 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
29103 		return (EINVAL);
29104 	}
29105 
29106 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
29107 	bzero(cdb, CDB_GROUP5);
29108 	if (un->un_f_mmc_cap == TRUE) {
29109 		cdb[0] = (char)SCMD_READ_CD;
29110 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
29111 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
29112 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
29113 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
29114 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
29115 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
29116 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
29117 		cdb[9] = (char)read_flags;
29118 	} else {
29119 		/*
29120 		 * Note: A vendor specific command (0xDB) is being used her to
29121 		 * request a read of all subcodes.
29122 		 */
29123 		cdb[0] = (char)SCMD_READ_CDXA;
29124 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
29125 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
29126 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
29127 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
29128 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
29129 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
29130 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
29131 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
29132 		cdb[10] = cdxa->cdxa_format;
29133 	}
29134 	com->uscsi_cdb	   = cdb;
29135 	com->uscsi_cdblen  = CDB_GROUP5;
29136 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
29137 	com->uscsi_buflen  = buflen;
29138 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
29139 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
29140 	    SD_PATH_STANDARD);
29141 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
29142 	kmem_free(com, sizeof (*com));
29143 	return (rval);
29144 }
29145 
29146 
29147 /*
29148  *    Function: sr_eject()
29149  *
29150  * Description: This routine is the driver entry point for handling CD-ROM
29151  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
29152  *
29153  *   Arguments: dev	- the device 'dev_t'
29154  *
29155  * Return Code: the code returned by sd_send_scsi_cmd()
29156  */
29157 
29158 static int
29159 sr_eject(dev_t dev)
29160 {
29161 	struct sd_lun	*un;
29162 	int		rval;
29163 	sd_ssc_t	*ssc;
29164 
29165 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29166 	    (un->un_state == SD_STATE_OFFLINE)) {
29167 		return (ENXIO);
29168 	}
29169 
29170 	/*
29171 	 * To prevent race conditions with the eject
29172 	 * command, keep track of an eject command as
29173 	 * it progresses. If we are already handling
29174 	 * an eject command in the driver for the given
29175 	 * unit and another request to eject is received
29176 	 * immediately return EAGAIN so we don't lose
29177 	 * the command if the current eject command fails.
29178 	 */
29179 	mutex_enter(SD_MUTEX(un));
29180 	if (un->un_f_ejecting == TRUE) {
29181 		mutex_exit(SD_MUTEX(un));
29182 		return (EAGAIN);
29183 	}
29184 	un->un_f_ejecting = TRUE;
29185 	mutex_exit(SD_MUTEX(un));
29186 
29187 	ssc = sd_ssc_init(un);
29188 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
29189 	    SD_PATH_STANDARD);
29190 	sd_ssc_fini(ssc);
29191 
29192 	if (rval != 0) {
29193 		mutex_enter(SD_MUTEX(un));
29194 		un->un_f_ejecting = FALSE;
29195 		mutex_exit(SD_MUTEX(un));
29196 		return (rval);
29197 	}
29198 
29199 	ssc = sd_ssc_init(un);
29200 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
29201 	    SD_TARGET_EJECT, SD_PATH_STANDARD);
29202 	sd_ssc_fini(ssc);
29203 
29204 	if (rval == 0) {
29205 		mutex_enter(SD_MUTEX(un));
29206 		sr_ejected(un);
29207 		un->un_mediastate = DKIO_EJECTED;
29208 		un->un_f_ejecting = FALSE;
29209 		cv_broadcast(&un->un_state_cv);
29210 		mutex_exit(SD_MUTEX(un));
29211 	} else {
29212 		mutex_enter(SD_MUTEX(un));
29213 		un->un_f_ejecting = FALSE;
29214 		mutex_exit(SD_MUTEX(un));
29215 	}
29216 	return (rval);
29217 }
29218 
29219 
29220 /*
29221  *    Function: sr_ejected()
29222  *
29223  * Description: This routine updates the soft state structure to invalidate the
29224  *		geometry information after the media has been ejected or a
29225  *		media eject has been detected.
29226  *
29227  *   Arguments: un - driver soft state (unit) structure
29228  */
29229 
29230 static void
29231 sr_ejected(struct sd_lun *un)
29232 {
29233 	struct sd_errstats *stp;
29234 
29235 	ASSERT(un != NULL);
29236 	ASSERT(mutex_owned(SD_MUTEX(un)));
29237 
29238 	un->un_f_blockcount_is_valid	= FALSE;
29239 	un->un_f_tgt_blocksize_is_valid	= FALSE;
29240 	mutex_exit(SD_MUTEX(un));
29241 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
29242 	mutex_enter(SD_MUTEX(un));
29243 
29244 	if (un->un_errstats != NULL) {
29245 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
29246 		stp->sd_capacity.value.ui64 = 0;
29247 	}
29248 }
29249 
29250 
29251 /*
29252  *    Function: sr_check_wp()
29253  *
29254  * Description: This routine checks the write protection of a removable
29255  *      media disk and hotpluggable devices via the write protect bit of
29256  *      the Mode Page Header device specific field. Some devices choke
29257  *      on unsupported mode page. In order to workaround this issue,
29258  *      this routine has been implemented to use 0x3f mode page(request
29259  *      for all pages) for all device types.
29260  *
29261  *   Arguments: dev             - the device 'dev_t'
29262  *
29263  * Return Code: int indicating if the device is write protected (1) or not (0)
29264  *
29265  *     Context: Kernel thread.
29266  *
29267  */
29268 
29269 static int
29270 sr_check_wp(dev_t dev)
29271 {
29272 	struct sd_lun	*un;
29273 	uchar_t		device_specific;
29274 	uchar_t		*sense;
29275 	int		hdrlen;
29276 	int		rval = FALSE;
29277 	int		status;
29278 	sd_ssc_t	*ssc;
29279 
29280 	/*
29281 	 * Note: The return codes for this routine should be reworked to
29282 	 * properly handle the case of a NULL softstate.
29283 	 */
29284 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
29285 		return (FALSE);
29286 	}
29287 
29288 	if (un->un_f_cfg_is_atapi == TRUE) {
29289 		/*
29290 		 * The mode page contents are not required; set the allocation
29291 		 * length for the mode page header only
29292 		 */
29293 		hdrlen = MODE_HEADER_LENGTH_GRP2;
29294 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29295 		ssc = sd_ssc_init(un);
29296 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
29297 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
29298 		sd_ssc_fini(ssc);
29299 		if (status != 0)
29300 			goto err_exit;
29301 		device_specific =
29302 		    ((struct mode_header_grp2 *)sense)->device_specific;
29303 	} else {
29304 		hdrlen = MODE_HEADER_LENGTH;
29305 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29306 		ssc = sd_ssc_init(un);
29307 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
29308 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
29309 		sd_ssc_fini(ssc);
29310 		if (status != 0)
29311 			goto err_exit;
29312 		device_specific =
29313 		    ((struct mode_header *)sense)->device_specific;
29314 	}
29315 
29316 
29317 	/*
29318 	 * Write protect mode sense failed; not all disks
29319 	 * understand this query. Return FALSE assuming that
29320 	 * these devices are not writable.
29321 	 */
29322 	if (device_specific & WRITE_PROTECT) {
29323 		rval = TRUE;
29324 	}
29325 
29326 err_exit:
29327 	kmem_free(sense, hdrlen);
29328 	return (rval);
29329 }
29330 
29331 /*
29332  *    Function: sr_volume_ctrl()
29333  *
29334  * Description: This routine is the driver entry point for handling CD-ROM
29335  *		audio output volume ioctl requests. (CDROMVOLCTRL)
29336  *
29337  *   Arguments: dev	- the device 'dev_t'
29338  *		data	- pointer to user audio volume control structure
29339  *		flag	- this argument is a pass through to ddi_copyxxx()
29340  *			  directly from the mode argument of ioctl().
29341  *
29342  * Return Code: the code returned by sd_send_scsi_cmd()
29343  *		EFAULT if ddi_copyxxx() fails
29344  *		ENXIO if fail ddi_get_soft_state
29345  *		EINVAL if data pointer is NULL
29346  *
29347  */
29348 
29349 static int
29350 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
29351 {
29352 	struct sd_lun		*un;
29353 	struct cdrom_volctrl    volume;
29354 	struct cdrom_volctrl    *vol = &volume;
29355 	uchar_t			*sense_page;
29356 	uchar_t			*select_page;
29357 	uchar_t			*sense;
29358 	uchar_t			*select;
29359 	int			sense_buflen;
29360 	int			select_buflen;
29361 	int			rval;
29362 	sd_ssc_t		*ssc;
29363 
29364 	if (data == NULL) {
29365 		return (EINVAL);
29366 	}
29367 
29368 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29369 	    (un->un_state == SD_STATE_OFFLINE)) {
29370 		return (ENXIO);
29371 	}
29372 
29373 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
29374 		return (EFAULT);
29375 	}
29376 
29377 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29378 		struct mode_header_grp2		*sense_mhp;
29379 		struct mode_header_grp2		*select_mhp;
29380 		int				bd_len;
29381 
29382 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
29383 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
29384 		    MODEPAGE_AUDIO_CTRL_LEN;
29385 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29386 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29387 		ssc = sd_ssc_init(un);
29388 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
29389 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29390 		    SD_PATH_STANDARD);
29391 		sd_ssc_fini(ssc);
29392 
29393 		if (rval != 0) {
29394 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
29395 			    "sr_volume_ctrl: Mode Sense Failed\n");
29396 			kmem_free(sense, sense_buflen);
29397 			kmem_free(select, select_buflen);
29398 			return (rval);
29399 		}
29400 		sense_mhp = (struct mode_header_grp2 *)sense;
29401 		select_mhp = (struct mode_header_grp2 *)select;
29402 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
29403 		    sense_mhp->bdesc_length_lo;
29404 		if (bd_len > MODE_BLK_DESC_LENGTH) {
29405 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29406 			    "sr_volume_ctrl: Mode Sense returned invalid "
29407 			    "block descriptor length\n");
29408 			kmem_free(sense, sense_buflen);
29409 			kmem_free(select, select_buflen);
29410 			return (EIO);
29411 		}
29412 		sense_page = (uchar_t *)
29413 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
29414 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
29415 		select_mhp->length_msb = 0;
29416 		select_mhp->length_lsb = 0;
29417 		select_mhp->bdesc_length_hi = 0;
29418 		select_mhp->bdesc_length_lo = 0;
29419 	} else {
29420 		struct mode_header		*sense_mhp, *select_mhp;
29421 
29422 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29423 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29424 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29425 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29426 		ssc = sd_ssc_init(un);
29427 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
29428 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29429 		    SD_PATH_STANDARD);
29430 		sd_ssc_fini(ssc);
29431 
29432 		if (rval != 0) {
29433 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29434 			    "sr_volume_ctrl: Mode Sense Failed\n");
29435 			kmem_free(sense, sense_buflen);
29436 			kmem_free(select, select_buflen);
29437 			return (rval);
29438 		}
29439 		sense_mhp  = (struct mode_header *)sense;
29440 		select_mhp = (struct mode_header *)select;
29441 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
29442 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29443 			    "sr_volume_ctrl: Mode Sense returned invalid "
29444 			    "block descriptor length\n");
29445 			kmem_free(sense, sense_buflen);
29446 			kmem_free(select, select_buflen);
29447 			return (EIO);
29448 		}
29449 		sense_page = (uchar_t *)
29450 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
29451 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
29452 		select_mhp->length = 0;
29453 		select_mhp->bdesc_length = 0;
29454 	}
29455 	/*
29456 	 * Note: An audio control data structure could be created and overlayed
29457 	 * on the following in place of the array indexing method implemented.
29458 	 */
29459 
29460 	/* Build the select data for the user volume data */
29461 	select_page[0] = MODEPAGE_AUDIO_CTRL;
29462 	select_page[1] = 0xE;
29463 	/* Set the immediate bit */
29464 	select_page[2] = 0x04;
29465 	/* Zero out reserved fields */
29466 	select_page[3] = 0x00;
29467 	select_page[4] = 0x00;
29468 	/* Return sense data for fields not to be modified */
29469 	select_page[5] = sense_page[5];
29470 	select_page[6] = sense_page[6];
29471 	select_page[7] = sense_page[7];
29472 	/* Set the user specified volume levels for channel 0 and 1 */
29473 	select_page[8] = 0x01;
29474 	select_page[9] = vol->channel0;
29475 	select_page[10] = 0x02;
29476 	select_page[11] = vol->channel1;
29477 	/* Channel 2 and 3 are currently unsupported so return the sense data */
29478 	select_page[12] = sense_page[12];
29479 	select_page[13] = sense_page[13];
29480 	select_page[14] = sense_page[14];
29481 	select_page[15] = sense_page[15];
29482 
29483 	ssc = sd_ssc_init(un);
29484 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29485 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
29486 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29487 	} else {
29488 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
29489 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29490 	}
29491 	sd_ssc_fini(ssc);
29492 
29493 	kmem_free(sense, sense_buflen);
29494 	kmem_free(select, select_buflen);
29495 	return (rval);
29496 }
29497 
29498 
29499 /*
29500  *    Function: sr_read_sony_session_offset()
29501  *
29502  * Description: This routine is the driver entry point for handling CD-ROM
29503  *		ioctl requests for session offset information. (CDROMREADOFFSET)
29504  *		The address of the first track in the last session of a
29505  *		multi-session CD-ROM is returned
29506  *
29507  *		Note: This routine uses a vendor specific key value in the
29508  *		command control field without implementing any vendor check here
29509  *		or in the ioctl routine.
29510  *
29511  *   Arguments: dev	- the device 'dev_t'
29512  *		data	- pointer to an int to hold the requested address
29513  *		flag	- this argument is a pass through to ddi_copyxxx()
29514  *			  directly from the mode argument of ioctl().
29515  *
29516  * Return Code: the code returned by sd_send_scsi_cmd()
29517  *		EFAULT if ddi_copyxxx() fails
29518  *		ENXIO if fail ddi_get_soft_state
29519  *		EINVAL if data pointer is NULL
29520  */
29521 
29522 static int
29523 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
29524 {
29525 	struct sd_lun		*un;
29526 	struct uscsi_cmd	*com;
29527 	caddr_t			buffer;
29528 	char			cdb[CDB_GROUP1];
29529 	int			session_offset = 0;
29530 	int			rval;
29531 
29532 	if (data == NULL) {
29533 		return (EINVAL);
29534 	}
29535 
29536 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29537 	    (un->un_state == SD_STATE_OFFLINE)) {
29538 		return (ENXIO);
29539 	}
29540 
29541 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
29542 	bzero(cdb, CDB_GROUP1);
29543 	cdb[0] = SCMD_READ_TOC;
29544 	/*
29545 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
29546 	 * (4 byte TOC response header + 8 byte response data)
29547 	 */
29548 	cdb[8] = SONY_SESSION_OFFSET_LEN;
29549 	/* Byte 9 is the control byte. A vendor specific value is used */
29550 	cdb[9] = SONY_SESSION_OFFSET_KEY;
29551 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
29552 	com->uscsi_cdb = cdb;
29553 	com->uscsi_cdblen = CDB_GROUP1;
29554 	com->uscsi_bufaddr = buffer;
29555 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
29556 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
29557 
29558 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
29559 	    SD_PATH_STANDARD);
29560 	if (rval != 0) {
29561 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29562 		kmem_free(com, sizeof (*com));
29563 		return (rval);
29564 	}
29565 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
29566 		session_offset =
29567 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
29568 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
29569 		/*
29570 		 * Offset returned offset in current lbasize block's. Convert to
29571 		 * 2k block's to return to the user
29572 		 */
29573 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
29574 			session_offset >>= 2;
29575 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
29576 			session_offset >>= 1;
29577 		}
29578 	}
29579 
29580 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
29581 		rval = EFAULT;
29582 	}
29583 
29584 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29585 	kmem_free(com, sizeof (*com));
29586 	return (rval);
29587 }
29588 
29589 
29590 /*
29591  *    Function: sd_wm_cache_constructor()
29592  *
29593  * Description: Cache Constructor for the wmap cache for the read/modify/write
29594  *		devices.
29595  *
29596  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29597  *		un	- sd_lun structure for the device.
29598  *		flag	- the km flags passed to constructor
29599  *
29600  * Return Code: 0 on success.
29601  *		-1 on failure.
29602  */
29603 
29604 /*ARGSUSED*/
29605 static int
29606 sd_wm_cache_constructor(void *wm, void *un, int flags)
29607 {
29608 	bzero(wm, sizeof (struct sd_w_map));
29609 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
29610 	return (0);
29611 }
29612 
29613 
29614 /*
29615  *    Function: sd_wm_cache_destructor()
29616  *
29617  * Description: Cache destructor for the wmap cache for the read/modify/write
29618  *		devices.
29619  *
29620  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29621  *		un	- sd_lun structure for the device.
29622  */
29623 /*ARGSUSED*/
29624 static void
29625 sd_wm_cache_destructor(void *wm, void *un)
29626 {
29627 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
29628 }
29629 
29630 
29631 /*
29632  *    Function: sd_range_lock()
29633  *
29634  * Description: Lock the range of blocks specified as parameter to ensure
29635  *		that read, modify write is atomic and no other i/o writes
29636  *		to the same location. The range is specified in terms
29637  *		of start and end blocks. Block numbers are the actual
29638  *		media block numbers and not system.
29639  *
29640  *   Arguments: un	- sd_lun structure for the device.
29641  *		startb - The starting block number
29642  *		endb - The end block number
29643  *		typ - type of i/o - simple/read_modify_write
29644  *
29645  * Return Code: wm  - pointer to the wmap structure.
29646  *
29647  *     Context: This routine can sleep.
29648  */
29649 
29650 static struct sd_w_map *
29651 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
29652 {
29653 	struct sd_w_map *wmp = NULL;
29654 	struct sd_w_map *sl_wmp = NULL;
29655 	struct sd_w_map *tmp_wmp;
29656 	wm_state state = SD_WM_CHK_LIST;
29657 
29658 
29659 	ASSERT(un != NULL);
29660 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29661 
29662 	mutex_enter(SD_MUTEX(un));
29663 
29664 	while (state != SD_WM_DONE) {
29665 
29666 		switch (state) {
29667 		case SD_WM_CHK_LIST:
29668 			/*
29669 			 * This is the starting state. Check the wmap list
29670 			 * to see if the range is currently available.
29671 			 */
29672 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
29673 				/*
29674 				 * If this is a simple write and no rmw
29675 				 * i/o is pending then try to lock the
29676 				 * range as the range should be available.
29677 				 */
29678 				state = SD_WM_LOCK_RANGE;
29679 			} else {
29680 				tmp_wmp = sd_get_range(un, startb, endb);
29681 				if (tmp_wmp != NULL) {
29682 					if ((wmp != NULL) && ONLIST(un, wmp)) {
29683 						/*
29684 						 * Should not keep onlist wmps
29685 						 * while waiting this macro
29686 						 * will also do wmp = NULL;
29687 						 */
29688 						FREE_ONLIST_WMAP(un, wmp);
29689 					}
29690 					/*
29691 					 * sl_wmp is the wmap on which wait
29692 					 * is done, since the tmp_wmp points
29693 					 * to the inuse wmap, set sl_wmp to
29694 					 * tmp_wmp and change the state to sleep
29695 					 */
29696 					sl_wmp = tmp_wmp;
29697 					state = SD_WM_WAIT_MAP;
29698 				} else {
29699 					state = SD_WM_LOCK_RANGE;
29700 				}
29701 
29702 			}
29703 			break;
29704 
29705 		case SD_WM_LOCK_RANGE:
29706 			ASSERT(un->un_wm_cache);
29707 			/*
29708 			 * The range need to be locked, try to get a wmap.
29709 			 * First attempt it with NO_SLEEP, want to avoid a sleep
29710 			 * if possible as we will have to release the sd mutex
29711 			 * if we have to sleep.
29712 			 */
29713 			if (wmp == NULL)
29714 				wmp = kmem_cache_alloc(un->un_wm_cache,
29715 				    KM_NOSLEEP);
29716 			if (wmp == NULL) {
29717 				mutex_exit(SD_MUTEX(un));
29718 				_NOTE(DATA_READABLE_WITHOUT_LOCK
29719 				    (sd_lun::un_wm_cache))
29720 				wmp = kmem_cache_alloc(un->un_wm_cache,
29721 				    KM_SLEEP);
29722 				mutex_enter(SD_MUTEX(un));
29723 				/*
29724 				 * we released the mutex so recheck and go to
29725 				 * check list state.
29726 				 */
29727 				state = SD_WM_CHK_LIST;
29728 			} else {
29729 				/*
29730 				 * We exit out of state machine since we
29731 				 * have the wmap. Do the housekeeping first.
29732 				 * place the wmap on the wmap list if it is not
29733 				 * on it already and then set the state to done.
29734 				 */
29735 				wmp->wm_start = startb;
29736 				wmp->wm_end = endb;
29737 				wmp->wm_flags = typ | SD_WM_BUSY;
29738 				if (typ & SD_WTYPE_RMW) {
29739 					un->un_rmw_count++;
29740 				}
29741 				/*
29742 				 * If not already on the list then link
29743 				 */
29744 				if (!ONLIST(un, wmp)) {
29745 					wmp->wm_next = un->un_wm;
29746 					wmp->wm_prev = NULL;
29747 					if (wmp->wm_next)
29748 						wmp->wm_next->wm_prev = wmp;
29749 					un->un_wm = wmp;
29750 				}
29751 				state = SD_WM_DONE;
29752 			}
29753 			break;
29754 
29755 		case SD_WM_WAIT_MAP:
29756 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
29757 			/*
29758 			 * Wait is done on sl_wmp, which is set in the
29759 			 * check_list state.
29760 			 */
29761 			sl_wmp->wm_wanted_count++;
29762 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
29763 			sl_wmp->wm_wanted_count--;
29764 			/*
29765 			 * We can reuse the memory from the completed sl_wmp
29766 			 * lock range for our new lock, but only if noone is
29767 			 * waiting for it.
29768 			 */
29769 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
29770 			if (sl_wmp->wm_wanted_count == 0) {
29771 				if (wmp != NULL) {
29772 					CHK_N_FREEWMP(un, wmp);
29773 				}
29774 				wmp = sl_wmp;
29775 			}
29776 			sl_wmp = NULL;
29777 			/*
29778 			 * After waking up, need to recheck for availability of
29779 			 * range.
29780 			 */
29781 			state = SD_WM_CHK_LIST;
29782 			break;
29783 
29784 		default:
29785 			panic("sd_range_lock: "
29786 			    "Unknown state %d in sd_range_lock", state);
29787 			/*NOTREACHED*/
29788 		} /* switch(state) */
29789 
29790 	} /* while(state != SD_WM_DONE) */
29791 
29792 	mutex_exit(SD_MUTEX(un));
29793 
29794 	ASSERT(wmp != NULL);
29795 
29796 	return (wmp);
29797 }
29798 
29799 
29800 /*
29801  *    Function: sd_get_range()
29802  *
29803  * Description: Find if there any overlapping I/O to this one
29804  *		Returns the write-map of 1st such I/O, NULL otherwise.
29805  *
29806  *   Arguments: un	- sd_lun structure for the device.
29807  *		startb - The starting block number
29808  *		endb - The end block number
29809  *
29810  * Return Code: wm  - pointer to the wmap structure.
29811  */
29812 
29813 static struct sd_w_map *
29814 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
29815 {
29816 	struct sd_w_map *wmp;
29817 
29818 	ASSERT(un != NULL);
29819 
29820 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
29821 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
29822 			continue;
29823 		}
29824 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
29825 			break;
29826 		}
29827 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
29828 			break;
29829 		}
29830 	}
29831 
29832 	return (wmp);
29833 }
29834 
29835 
29836 /*
29837  *    Function: sd_free_inlist_wmap()
29838  *
29839  * Description: Unlink and free a write map struct.
29840  *
29841  *   Arguments: un      - sd_lun structure for the device.
29842  *		wmp	- sd_w_map which needs to be unlinked.
29843  */
29844 
29845 static void
29846 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
29847 {
29848 	ASSERT(un != NULL);
29849 
29850 	if (un->un_wm == wmp) {
29851 		un->un_wm = wmp->wm_next;
29852 	} else {
29853 		wmp->wm_prev->wm_next = wmp->wm_next;
29854 	}
29855 
29856 	if (wmp->wm_next) {
29857 		wmp->wm_next->wm_prev = wmp->wm_prev;
29858 	}
29859 
29860 	wmp->wm_next = wmp->wm_prev = NULL;
29861 
29862 	kmem_cache_free(un->un_wm_cache, wmp);
29863 }
29864 
29865 
29866 /*
29867  *    Function: sd_range_unlock()
29868  *
29869  * Description: Unlock the range locked by wm.
29870  *		Free write map if nobody else is waiting on it.
29871  *
29872  *   Arguments: un      - sd_lun structure for the device.
29873  *              wmp     - sd_w_map which needs to be unlinked.
29874  */
29875 
29876 static void
29877 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
29878 {
29879 	ASSERT(un != NULL);
29880 	ASSERT(wm != NULL);
29881 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29882 
29883 	mutex_enter(SD_MUTEX(un));
29884 
29885 	if (wm->wm_flags & SD_WTYPE_RMW) {
29886 		un->un_rmw_count--;
29887 	}
29888 
29889 	if (wm->wm_wanted_count) {
29890 		wm->wm_flags = 0;
29891 		/*
29892 		 * Broadcast that the wmap is available now.
29893 		 */
29894 		cv_broadcast(&wm->wm_avail);
29895 	} else {
29896 		/*
29897 		 * If no one is waiting on the map, it should be free'ed.
29898 		 */
29899 		sd_free_inlist_wmap(un, wm);
29900 	}
29901 
29902 	mutex_exit(SD_MUTEX(un));
29903 }
29904 
29905 
29906 /*
29907  *    Function: sd_read_modify_write_task
29908  *
29909  * Description: Called from a taskq thread to initiate the write phase of
29910  *		a read-modify-write request.  This is used for targets where
29911  *		un->un_sys_blocksize != un->un_tgt_blocksize.
29912  *
29913  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
29914  *
29915  *     Context: Called under taskq thread context.
29916  */
29917 
29918 static void
29919 sd_read_modify_write_task(void *arg)
29920 {
29921 	struct sd_mapblocksize_info	*bsp;
29922 	struct buf	*bp;
29923 	struct sd_xbuf	*xp;
29924 	struct sd_lun	*un;
29925 
29926 	bp = arg;	/* The bp is given in arg */
29927 	ASSERT(bp != NULL);
29928 
29929 	/* Get the pointer to the layer-private data struct */
29930 	xp = SD_GET_XBUF(bp);
29931 	ASSERT(xp != NULL);
29932 	bsp = xp->xb_private;
29933 	ASSERT(bsp != NULL);
29934 
29935 	un = SD_GET_UN(bp);
29936 	ASSERT(un != NULL);
29937 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29938 
29939 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29940 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
29941 
29942 	/*
29943 	 * This is the write phase of a read-modify-write request, called
29944 	 * under the context of a taskq thread in response to the completion
29945 	 * of the read portion of the rmw request completing under interrupt
29946 	 * context. The write request must be sent from here down the iostart
29947 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
29948 	 * we use the layer index saved in the layer-private data area.
29949 	 */
29950 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
29951 
29952 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29953 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
29954 }
29955 
29956 
29957 /*
29958  *    Function: sddump_do_read_of_rmw()
29959  *
29960  * Description: This routine will be called from sddump, If sddump is called
29961  *		with an I/O which not aligned on device blocksize boundary
29962  *		then the write has to be converted to read-modify-write.
29963  *		Do the read part here in order to keep sddump simple.
29964  *		Note - That the sd_mutex is held across the call to this
29965  *		routine.
29966  *
29967  *   Arguments: un	- sd_lun
29968  *		blkno	- block number in terms of media block size.
29969  *		nblk	- number of blocks.
29970  *		bpp	- pointer to pointer to the buf structure. On return
29971  *			from this function, *bpp points to the valid buffer
29972  *			to which the write has to be done.
29973  *
29974  * Return Code: 0 for success or errno-type return code
29975  */
29976 
29977 static int
29978 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
29979     struct buf **bpp)
29980 {
29981 	int err;
29982 	int i;
29983 	int rval;
29984 	struct buf *bp;
29985 	struct scsi_pkt *pkt = NULL;
29986 	uint32_t target_blocksize;
29987 
29988 	ASSERT(un != NULL);
29989 	ASSERT(mutex_owned(SD_MUTEX(un)));
29990 
29991 	target_blocksize = un->un_tgt_blocksize;
29992 
29993 	mutex_exit(SD_MUTEX(un));
29994 
29995 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
29996 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
29997 	if (bp == NULL) {
29998 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29999 		    "no resources for dumping; giving up");
30000 		err = ENOMEM;
30001 		goto done;
30002 	}
30003 
30004 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
30005 	    blkno, nblk);
30006 	if (rval != 0) {
30007 		scsi_free_consistent_buf(bp);
30008 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30009 		    "no resources for dumping; giving up");
30010 		err = ENOMEM;
30011 		goto done;
30012 	}
30013 
30014 	pkt->pkt_flags |= FLAG_NOINTR;
30015 
30016 	err = EIO;
30017 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
30018 
30019 		/*
30020 		 * Scsi_poll returns 0 (success) if the command completes and
30021 		 * the status block is STATUS_GOOD.  We should only check
30022 		 * errors if this condition is not true.  Even then we should
30023 		 * send our own request sense packet only if we have a check
30024 		 * condition and auto request sense has not been performed by
30025 		 * the hba.
30026 		 */
30027 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
30028 
30029 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
30030 			err = 0;
30031 			break;
30032 		}
30033 
30034 		/*
30035 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
30036 		 * no need to read RQS data.
30037 		 */
30038 		if (pkt->pkt_reason == CMD_DEV_GONE) {
30039 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30040 			    "Error while dumping state with rmw..."
30041 			    "Device is gone\n");
30042 			break;
30043 		}
30044 
30045 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
30046 			SD_INFO(SD_LOG_DUMP, un,
30047 			    "sddump: read failed with CHECK, try # %d\n", i);
30048 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
30049 				(void) sd_send_polled_RQS(un);
30050 			}
30051 
30052 			continue;
30053 		}
30054 
30055 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
30056 			int reset_retval = 0;
30057 
30058 			SD_INFO(SD_LOG_DUMP, un,
30059 			    "sddump: read failed with BUSY, try # %d\n", i);
30060 
30061 			if (un->un_f_lun_reset_enabled == TRUE) {
30062 				reset_retval = scsi_reset(SD_ADDRESS(un),
30063 				    RESET_LUN);
30064 			}
30065 			if (reset_retval == 0) {
30066 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
30067 			}
30068 			(void) sd_send_polled_RQS(un);
30069 
30070 		} else {
30071 			SD_INFO(SD_LOG_DUMP, un,
30072 			    "sddump: read failed with 0x%x, try # %d\n",
30073 			    SD_GET_PKT_STATUS(pkt), i);
30074 			mutex_enter(SD_MUTEX(un));
30075 			sd_reset_target(un, pkt);
30076 			mutex_exit(SD_MUTEX(un));
30077 		}
30078 
30079 		/*
30080 		 * If we are not getting anywhere with lun/target resets,
30081 		 * let's reset the bus.
30082 		 */
30083 		if (i > SD_NDUMP_RETRIES / 2) {
30084 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
30085 			(void) sd_send_polled_RQS(un);
30086 		}
30087 
30088 	}
30089 	scsi_destroy_pkt(pkt);
30090 
30091 	if (err != 0) {
30092 		scsi_free_consistent_buf(bp);
30093 		*bpp = NULL;
30094 	} else {
30095 		*bpp = bp;
30096 	}
30097 
30098 done:
30099 	mutex_enter(SD_MUTEX(un));
30100 	return (err);
30101 }
30102 
30103 
30104 /*
30105  *    Function: sd_failfast_flushq
30106  *
30107  * Description: Take all bp's on the wait queue that have B_FAILFAST set
30108  *		in b_flags and move them onto the failfast queue, then kick
30109  *		off a thread to return all bp's on the failfast queue to
30110  *		their owners with an error set.
30111  *
30112  *   Arguments: un - pointer to the soft state struct for the instance.
30113  *
30114  *     Context: may execute in interrupt context.
30115  */
30116 
30117 static void
30118 sd_failfast_flushq(struct sd_lun *un)
30119 {
30120 	struct buf *bp;
30121 	struct buf *next_waitq_bp;
30122 	struct buf *prev_waitq_bp = NULL;
30123 
30124 	ASSERT(un != NULL);
30125 	ASSERT(mutex_owned(SD_MUTEX(un)));
30126 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
30127 	ASSERT(un->un_failfast_bp == NULL);
30128 
30129 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
30130 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
30131 
30132 	/*
30133 	 * Check if we should flush all bufs when entering failfast state, or
30134 	 * just those with B_FAILFAST set.
30135 	 */
30136 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
30137 		/*
30138 		 * Move *all* bp's on the wait queue to the failfast flush
30139 		 * queue, including those that do NOT have B_FAILFAST set.
30140 		 */
30141 		if (un->un_failfast_headp == NULL) {
30142 			ASSERT(un->un_failfast_tailp == NULL);
30143 			un->un_failfast_headp = un->un_waitq_headp;
30144 		} else {
30145 			ASSERT(un->un_failfast_tailp != NULL);
30146 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
30147 		}
30148 
30149 		un->un_failfast_tailp = un->un_waitq_tailp;
30150 
30151 		/* update kstat for each bp moved out of the waitq */
30152 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
30153 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
30154 		}
30155 
30156 		/* empty the waitq */
30157 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
30158 
30159 	} else {
30160 		/*
30161 		 * Go thru the wait queue, pick off all entries with
30162 		 * B_FAILFAST set, and move these onto the failfast queue.
30163 		 */
30164 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
30165 			/*
30166 			 * Save the pointer to the next bp on the wait queue,
30167 			 * so we get to it on the next iteration of this loop.
30168 			 */
30169 			next_waitq_bp = bp->av_forw;
30170 
30171 			/*
30172 			 * If this bp from the wait queue does NOT have
30173 			 * B_FAILFAST set, just move on to the next element
30174 			 * in the wait queue. Note, this is the only place
30175 			 * where it is correct to set prev_waitq_bp.
30176 			 */
30177 			if ((bp->b_flags & B_FAILFAST) == 0) {
30178 				prev_waitq_bp = bp;
30179 				continue;
30180 			}
30181 
30182 			/*
30183 			 * Remove the bp from the wait queue.
30184 			 */
30185 			if (bp == un->un_waitq_headp) {
30186 				/* The bp is the first element of the waitq. */
30187 				un->un_waitq_headp = next_waitq_bp;
30188 				if (un->un_waitq_headp == NULL) {
30189 					/* The wait queue is now empty */
30190 					un->un_waitq_tailp = NULL;
30191 				}
30192 			} else {
30193 				/*
30194 				 * The bp is either somewhere in the middle
30195 				 * or at the end of the wait queue.
30196 				 */
30197 				ASSERT(un->un_waitq_headp != NULL);
30198 				ASSERT(prev_waitq_bp != NULL);
30199 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
30200 				    == 0);
30201 				if (bp == un->un_waitq_tailp) {
30202 					/* bp is the last entry on the waitq. */
30203 					ASSERT(next_waitq_bp == NULL);
30204 					un->un_waitq_tailp = prev_waitq_bp;
30205 				}
30206 				prev_waitq_bp->av_forw = next_waitq_bp;
30207 			}
30208 			bp->av_forw = NULL;
30209 
30210 			/*
30211 			 * update kstat since the bp is moved out of
30212 			 * the waitq
30213 			 */
30214 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
30215 
30216 			/*
30217 			 * Now put the bp onto the failfast queue.
30218 			 */
30219 			if (un->un_failfast_headp == NULL) {
30220 				/* failfast queue is currently empty */
30221 				ASSERT(un->un_failfast_tailp == NULL);
30222 				un->un_failfast_headp =
30223 				    un->un_failfast_tailp = bp;
30224 			} else {
30225 				/* Add the bp to the end of the failfast q */
30226 				ASSERT(un->un_failfast_tailp != NULL);
30227 				ASSERT(un->un_failfast_tailp->b_flags &
30228 				    B_FAILFAST);
30229 				un->un_failfast_tailp->av_forw = bp;
30230 				un->un_failfast_tailp = bp;
30231 			}
30232 		}
30233 	}
30234 
30235 	/*
30236 	 * Now return all bp's on the failfast queue to their owners.
30237 	 */
30238 	while ((bp = un->un_failfast_headp) != NULL) {
30239 
30240 		un->un_failfast_headp = bp->av_forw;
30241 		if (un->un_failfast_headp == NULL) {
30242 			un->un_failfast_tailp = NULL;
30243 		}
30244 
30245 		/*
30246 		 * We want to return the bp with a failure error code, but
30247 		 * we do not want a call to sd_start_cmds() to occur here,
30248 		 * so use sd_return_failed_command_no_restart() instead of
30249 		 * sd_return_failed_command().
30250 		 */
30251 		sd_return_failed_command_no_restart(un, bp, EIO);
30252 	}
30253 
30254 	/* Flush the xbuf queues if required. */
30255 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
30256 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
30257 	}
30258 
30259 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
30260 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
30261 }
30262 
30263 
30264 /*
30265  *    Function: sd_failfast_flushq_callback
30266  *
30267  * Description: Return TRUE if the given bp meets the criteria for failfast
30268  *		flushing. Used with ddi_xbuf_flushq(9F).
30269  *
30270  *   Arguments: bp - ptr to buf struct to be examined.
30271  *
30272  *     Context: Any
30273  */
30274 
30275 static int
30276 sd_failfast_flushq_callback(struct buf *bp)
30277 {
30278 	/*
30279 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
30280 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
30281 	 */
30282 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
30283 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
30284 }
30285 
30286 
30287 
30288 /*
30289  * Function: sd_setup_next_xfer
30290  *
30291  * Description: Prepare next I/O operation using DMA_PARTIAL
30292  *
30293  */
30294 
30295 static int
30296 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
30297     struct scsi_pkt *pkt, struct sd_xbuf *xp)
30298 {
30299 	ssize_t	num_blks_not_xfered;
30300 	daddr_t	strt_blk_num;
30301 	ssize_t	bytes_not_xfered;
30302 	int	rval;
30303 
30304 	ASSERT(pkt->pkt_resid == 0);
30305 
30306 	/*
30307 	 * Calculate next block number and amount to be transferred.
30308 	 *
30309 	 * How much data NOT transfered to the HBA yet.
30310 	 */
30311 	bytes_not_xfered = xp->xb_dma_resid;
30312 
30313 	/*
30314 	 * figure how many blocks NOT transfered to the HBA yet.
30315 	 */
30316 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
30317 
30318 	/*
30319 	 * set starting block number to the end of what WAS transfered.
30320 	 */
30321 	strt_blk_num = xp->xb_blkno +
30322 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
30323 
30324 	/*
30325 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
30326 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
30327 	 * the disk mutex here.
30328 	 */
30329 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
30330 	    strt_blk_num, num_blks_not_xfered);
30331 
30332 	if (rval == 0) {
30333 
30334 		/*
30335 		 * Success.
30336 		 *
30337 		 * Adjust things if there are still more blocks to be
30338 		 * transfered.
30339 		 */
30340 		xp->xb_dma_resid = pkt->pkt_resid;
30341 		pkt->pkt_resid = 0;
30342 
30343 		return (1);
30344 	}
30345 
30346 	/*
30347 	 * There's really only one possible return value from
30348 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
30349 	 * returns NULL.
30350 	 */
30351 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
30352 
30353 	bp->b_resid = bp->b_bcount;
30354 	bp->b_flags |= B_ERROR;
30355 
30356 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30357 	    "Error setting up next portion of DMA transfer\n");
30358 
30359 	return (0);
30360 }
30361 
30362 /*
30363  *    Function: sd_panic_for_res_conflict
30364  *
30365  * Description: Call panic with a string formatted with "Reservation Conflict"
30366  *		and a human readable identifier indicating the SD instance
30367  *		that experienced the reservation conflict.
30368  *
30369  *   Arguments: un - pointer to the soft state struct for the instance.
30370  *
30371  *     Context: may execute in interrupt context.
30372  */
30373 
30374 #define	SD_RESV_CONFLICT_FMT_LEN 40
30375 void
30376 sd_panic_for_res_conflict(struct sd_lun *un)
30377 {
30378 	char panic_str[SD_RESV_CONFLICT_FMT_LEN + MAXPATHLEN];
30379 	char path_str[MAXPATHLEN];
30380 
30381 	(void) snprintf(panic_str, sizeof (panic_str),
30382 	    "Reservation Conflict\nDisk: %s",
30383 	    ddi_pathname(SD_DEVINFO(un), path_str));
30384 
30385 	panic(panic_str);
30386 }
30387 
30388 /*
30389  * Note: The following sd_faultinjection_ioctl( ) routines implement
30390  * driver support for handling fault injection for error analysis
30391  * causing faults in multiple layers of the driver.
30392  *
30393  */
30394 
30395 #ifdef SD_FAULT_INJECTION
30396 static uint_t   sd_fault_injection_on = 0;
30397 
30398 /*
30399  *    Function: sd_faultinjection_ioctl()
30400  *
30401  * Description: This routine is the driver entry point for handling
30402  *              faultinjection ioctls to inject errors into the
30403  *              layer model
30404  *
30405  *   Arguments: cmd	- the ioctl cmd received
30406  *		arg	- the arguments from user and returns
30407  */
30408 
30409 static void
30410 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un)
30411 {
30412 	uint_t i = 0;
30413 	uint_t rval;
30414 
30415 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
30416 
30417 	mutex_enter(SD_MUTEX(un));
30418 
30419 	switch (cmd) {
30420 	case SDIOCRUN:
30421 		/* Allow pushed faults to be injected */
30422 		SD_INFO(SD_LOG_SDTEST, un,
30423 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
30424 
30425 		sd_fault_injection_on = 1;
30426 
30427 		SD_INFO(SD_LOG_IOERR, un,
30428 		    "sd_faultinjection_ioctl: run finished\n");
30429 		break;
30430 
30431 	case SDIOCSTART:
30432 		/* Start Injection Session */
30433 		SD_INFO(SD_LOG_SDTEST, un,
30434 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
30435 
30436 		sd_fault_injection_on = 0;
30437 		un->sd_injection_mask = 0xFFFFFFFF;
30438 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30439 			un->sd_fi_fifo_pkt[i] = NULL;
30440 			un->sd_fi_fifo_xb[i] = NULL;
30441 			un->sd_fi_fifo_un[i] = NULL;
30442 			un->sd_fi_fifo_arq[i] = NULL;
30443 		}
30444 		un->sd_fi_fifo_start = 0;
30445 		un->sd_fi_fifo_end = 0;
30446 
30447 		mutex_enter(&(un->un_fi_mutex));
30448 		un->sd_fi_log[0] = '\0';
30449 		un->sd_fi_buf_len = 0;
30450 		mutex_exit(&(un->un_fi_mutex));
30451 
30452 		SD_INFO(SD_LOG_IOERR, un,
30453 		    "sd_faultinjection_ioctl: start finished\n");
30454 		break;
30455 
30456 	case SDIOCSTOP:
30457 		/* Stop Injection Session */
30458 		SD_INFO(SD_LOG_SDTEST, un,
30459 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
30460 		sd_fault_injection_on = 0;
30461 		un->sd_injection_mask = 0x0;
30462 
30463 		/* Empty stray or unuseds structs from fifo */
30464 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30465 			if (un->sd_fi_fifo_pkt[i] != NULL) {
30466 				kmem_free(un->sd_fi_fifo_pkt[i],
30467 				    sizeof (struct sd_fi_pkt));
30468 			}
30469 			if (un->sd_fi_fifo_xb[i] != NULL) {
30470 				kmem_free(un->sd_fi_fifo_xb[i],
30471 				    sizeof (struct sd_fi_xb));
30472 			}
30473 			if (un->sd_fi_fifo_un[i] != NULL) {
30474 				kmem_free(un->sd_fi_fifo_un[i],
30475 				    sizeof (struct sd_fi_un));
30476 			}
30477 			if (un->sd_fi_fifo_arq[i] != NULL) {
30478 				kmem_free(un->sd_fi_fifo_arq[i],
30479 				    sizeof (struct sd_fi_arq));
30480 			}
30481 			un->sd_fi_fifo_pkt[i] = NULL;
30482 			un->sd_fi_fifo_un[i] = NULL;
30483 			un->sd_fi_fifo_xb[i] = NULL;
30484 			un->sd_fi_fifo_arq[i] = NULL;
30485 		}
30486 		un->sd_fi_fifo_start = 0;
30487 		un->sd_fi_fifo_end = 0;
30488 
30489 		SD_INFO(SD_LOG_IOERR, un,
30490 		    "sd_faultinjection_ioctl: stop finished\n");
30491 		break;
30492 
30493 	case SDIOCINSERTPKT:
30494 		/* Store a packet struct to be pushed onto fifo */
30495 		SD_INFO(SD_LOG_SDTEST, un,
30496 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
30497 
30498 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30499 
30500 		sd_fault_injection_on = 0;
30501 
30502 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
30503 		if (un->sd_fi_fifo_pkt[i] != NULL) {
30504 			kmem_free(un->sd_fi_fifo_pkt[i],
30505 			    sizeof (struct sd_fi_pkt));
30506 		}
30507 		if (arg != (uintptr_t)NULL) {
30508 			un->sd_fi_fifo_pkt[i] =
30509 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
30510 			if (un->sd_fi_fifo_pkt[i] == NULL) {
30511 				/* Alloc failed don't store anything */
30512 				break;
30513 			}
30514 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
30515 			    sizeof (struct sd_fi_pkt), 0);
30516 			if (rval == -1) {
30517 				kmem_free(un->sd_fi_fifo_pkt[i],
30518 				    sizeof (struct sd_fi_pkt));
30519 				un->sd_fi_fifo_pkt[i] = NULL;
30520 			}
30521 		} else {
30522 			SD_INFO(SD_LOG_IOERR, un,
30523 			    "sd_faultinjection_ioctl: pkt null\n");
30524 		}
30525 		break;
30526 
30527 	case SDIOCINSERTXB:
30528 		/* Store a xb struct to be pushed onto fifo */
30529 		SD_INFO(SD_LOG_SDTEST, un,
30530 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
30531 
30532 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30533 
30534 		sd_fault_injection_on = 0;
30535 
30536 		if (un->sd_fi_fifo_xb[i] != NULL) {
30537 			kmem_free(un->sd_fi_fifo_xb[i],
30538 			    sizeof (struct sd_fi_xb));
30539 			un->sd_fi_fifo_xb[i] = NULL;
30540 		}
30541 		if (arg != (uintptr_t)NULL) {
30542 			un->sd_fi_fifo_xb[i] =
30543 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
30544 			if (un->sd_fi_fifo_xb[i] == NULL) {
30545 				/* Alloc failed don't store anything */
30546 				break;
30547 			}
30548 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
30549 			    sizeof (struct sd_fi_xb), 0);
30550 
30551 			if (rval == -1) {
30552 				kmem_free(un->sd_fi_fifo_xb[i],
30553 				    sizeof (struct sd_fi_xb));
30554 				un->sd_fi_fifo_xb[i] = NULL;
30555 			}
30556 		} else {
30557 			SD_INFO(SD_LOG_IOERR, un,
30558 			    "sd_faultinjection_ioctl: xb null\n");
30559 		}
30560 		break;
30561 
30562 	case SDIOCINSERTUN:
30563 		/* Store a un struct to be pushed onto fifo */
30564 		SD_INFO(SD_LOG_SDTEST, un,
30565 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
30566 
30567 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30568 
30569 		sd_fault_injection_on = 0;
30570 
30571 		if (un->sd_fi_fifo_un[i] != NULL) {
30572 			kmem_free(un->sd_fi_fifo_un[i],
30573 			    sizeof (struct sd_fi_un));
30574 			un->sd_fi_fifo_un[i] = NULL;
30575 		}
30576 		if (arg != (uintptr_t)NULL) {
30577 			un->sd_fi_fifo_un[i] =
30578 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
30579 			if (un->sd_fi_fifo_un[i] == NULL) {
30580 				/* Alloc failed don't store anything */
30581 				break;
30582 			}
30583 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
30584 			    sizeof (struct sd_fi_un), 0);
30585 			if (rval == -1) {
30586 				kmem_free(un->sd_fi_fifo_un[i],
30587 				    sizeof (struct sd_fi_un));
30588 				un->sd_fi_fifo_un[i] = NULL;
30589 			}
30590 
30591 		} else {
30592 			SD_INFO(SD_LOG_IOERR, un,
30593 			    "sd_faultinjection_ioctl: un null\n");
30594 		}
30595 
30596 		break;
30597 
30598 	case SDIOCINSERTARQ:
30599 		/* Store a arq struct to be pushed onto fifo */
30600 		SD_INFO(SD_LOG_SDTEST, un,
30601 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
30602 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30603 
30604 		sd_fault_injection_on = 0;
30605 
30606 		if (un->sd_fi_fifo_arq[i] != NULL) {
30607 			kmem_free(un->sd_fi_fifo_arq[i],
30608 			    sizeof (struct sd_fi_arq));
30609 			un->sd_fi_fifo_arq[i] = NULL;
30610 		}
30611 		if (arg != (uintptr_t)NULL) {
30612 			un->sd_fi_fifo_arq[i] =
30613 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
30614 			if (un->sd_fi_fifo_arq[i] == NULL) {
30615 				/* Alloc failed don't store anything */
30616 				break;
30617 			}
30618 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
30619 			    sizeof (struct sd_fi_arq), 0);
30620 			if (rval == -1) {
30621 				kmem_free(un->sd_fi_fifo_arq[i],
30622 				    sizeof (struct sd_fi_arq));
30623 				un->sd_fi_fifo_arq[i] = NULL;
30624 			}
30625 
30626 		} else {
30627 			SD_INFO(SD_LOG_IOERR, un,
30628 			    "sd_faultinjection_ioctl: arq null\n");
30629 		}
30630 
30631 		break;
30632 
30633 	case SDIOCPUSH:
30634 		/* Push stored xb, pkt, un, and arq onto fifo */
30635 		sd_fault_injection_on = 0;
30636 
30637 		if (arg != (uintptr_t)NULL) {
30638 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
30639 			if (rval != -1 &&
30640 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30641 				un->sd_fi_fifo_end += i;
30642 			}
30643 		} else {
30644 			SD_INFO(SD_LOG_IOERR, un,
30645 			    "sd_faultinjection_ioctl: push arg null\n");
30646 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30647 				un->sd_fi_fifo_end++;
30648 			}
30649 		}
30650 		SD_INFO(SD_LOG_IOERR, un,
30651 		    "sd_faultinjection_ioctl: push to end=%d\n",
30652 		    un->sd_fi_fifo_end);
30653 		break;
30654 
30655 	case SDIOCRETRIEVE:
30656 		/* Return buffer of log from Injection session */
30657 		SD_INFO(SD_LOG_SDTEST, un,
30658 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
30659 
30660 		sd_fault_injection_on = 0;
30661 
30662 		mutex_enter(&(un->un_fi_mutex));
30663 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
30664 		    un->sd_fi_buf_len+1, 0);
30665 		mutex_exit(&(un->un_fi_mutex));
30666 
30667 		if (rval == -1) {
30668 			/*
30669 			 * arg is possibly invalid setting
30670 			 * it to NULL for return
30671 			 */
30672 			arg = (uintptr_t)NULL;
30673 		}
30674 		break;
30675 	}
30676 
30677 	mutex_exit(SD_MUTEX(un));
30678 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: exit\n");
30679 }
30680 
30681 
30682 /*
30683  *    Function: sd_injection_log()
30684  *
30685  * Description: This routine adds buff to the already existing injection log
30686  *              for retrieval via faultinjection_ioctl for use in fault
30687  *              detection and recovery
30688  *
30689  *   Arguments: buf - the string to add to the log
30690  */
30691 
30692 static void
30693 sd_injection_log(char *buf, struct sd_lun *un)
30694 {
30695 	uint_t len;
30696 
30697 	ASSERT(un != NULL);
30698 	ASSERT(buf != NULL);
30699 
30700 	mutex_enter(&(un->un_fi_mutex));
30701 
30702 	len = min(strlen(buf), 255);
30703 	/* Add logged value to Injection log to be returned later */
30704 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
30705 		uint_t	offset = strlen((char *)un->sd_fi_log);
30706 		char *destp = (char *)un->sd_fi_log + offset;
30707 		int i;
30708 		for (i = 0; i < len; i++) {
30709 			*destp++ = *buf++;
30710 		}
30711 		un->sd_fi_buf_len += len;
30712 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
30713 	}
30714 
30715 	mutex_exit(&(un->un_fi_mutex));
30716 }
30717 
30718 
30719 /*
30720  *    Function: sd_faultinjection()
30721  *
30722  * Description: This routine takes the pkt and changes its
30723  *		content based on error injection scenerio.
30724  *
30725  *   Arguments: pktp	- packet to be changed
30726  */
30727 
30728 static void
30729 sd_faultinjection(struct scsi_pkt *pktp)
30730 {
30731 	uint_t i;
30732 	struct sd_fi_pkt *fi_pkt;
30733 	struct sd_fi_xb *fi_xb;
30734 	struct sd_fi_un *fi_un;
30735 	struct sd_fi_arq *fi_arq;
30736 	struct buf *bp;
30737 	struct sd_xbuf *xb;
30738 	struct sd_lun *un;
30739 
30740 	ASSERT(pktp != NULL);
30741 
30742 	/* pull bp xb and un from pktp */
30743 	bp = (struct buf *)pktp->pkt_private;
30744 	xb = SD_GET_XBUF(bp);
30745 	un = SD_GET_UN(bp);
30746 
30747 	ASSERT(un != NULL);
30748 
30749 	mutex_enter(SD_MUTEX(un));
30750 
30751 	SD_TRACE(SD_LOG_SDTEST, un,
30752 	    "sd_faultinjection: entry Injection from sdintr\n");
30753 
30754 	/* if injection is off return */
30755 	if (sd_fault_injection_on == 0 ||
30756 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
30757 		mutex_exit(SD_MUTEX(un));
30758 		return;
30759 	}
30760 
30761 	SD_INFO(SD_LOG_SDTEST, un,
30762 	    "sd_faultinjection: is working for copying\n");
30763 
30764 	/* take next set off fifo */
30765 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
30766 
30767 	fi_pkt = un->sd_fi_fifo_pkt[i];
30768 	fi_xb = un->sd_fi_fifo_xb[i];
30769 	fi_un = un->sd_fi_fifo_un[i];
30770 	fi_arq = un->sd_fi_fifo_arq[i];
30771 
30772 
30773 	/* set variables accordingly */
30774 	/* set pkt if it was on fifo */
30775 	if (fi_pkt != NULL) {
30776 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
30777 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
30778 		if (fi_pkt->pkt_cdbp != 0xff)
30779 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
30780 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
30781 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
30782 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
30783 
30784 	}
30785 	/* set xb if it was on fifo */
30786 	if (fi_xb != NULL) {
30787 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
30788 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
30789 		if (fi_xb->xb_retry_count != 0)
30790 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
30791 		SD_CONDSET(xb, xb, xb_victim_retry_count,
30792 		    "xb_victim_retry_count");
30793 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
30794 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
30795 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
30796 
30797 		/* copy in block data from sense */
30798 		/*
30799 		 * if (fi_xb->xb_sense_data[0] != -1) {
30800 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
30801 		 *	SENSE_LENGTH);
30802 		 * }
30803 		 */
30804 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
30805 
30806 		/* copy in extended sense codes */
30807 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30808 		    xb, es_code, "es_code");
30809 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30810 		    xb, es_key, "es_key");
30811 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30812 		    xb, es_add_code, "es_add_code");
30813 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30814 		    xb, es_qual_code, "es_qual_code");
30815 		struct scsi_extended_sense *esp;
30816 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
30817 		esp->es_class = CLASS_EXTENDED_SENSE;
30818 	}
30819 
30820 	/* set un if it was on fifo */
30821 	if (fi_un != NULL) {
30822 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
30823 		SD_CONDSET(un, un, un_ctype, "un_ctype");
30824 		SD_CONDSET(un, un, un_reset_retry_count,
30825 		    "un_reset_retry_count");
30826 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
30827 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
30828 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
30829 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
30830 		    "un_f_allow_bus_device_reset");
30831 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
30832 
30833 	}
30834 
30835 	/* copy in auto request sense if it was on fifo */
30836 	if (fi_arq != NULL) {
30837 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
30838 	}
30839 
30840 	/* free structs */
30841 	if (un->sd_fi_fifo_pkt[i] != NULL) {
30842 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
30843 	}
30844 	if (un->sd_fi_fifo_xb[i] != NULL) {
30845 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
30846 	}
30847 	if (un->sd_fi_fifo_un[i] != NULL) {
30848 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
30849 	}
30850 	if (un->sd_fi_fifo_arq[i] != NULL) {
30851 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
30852 	}
30853 
30854 	/*
30855 	 * kmem_free does not gurantee to set to NULL
30856 	 * since we uses these to determine if we set
30857 	 * values or not lets confirm they are always
30858 	 * NULL after free
30859 	 */
30860 	un->sd_fi_fifo_pkt[i] = NULL;
30861 	un->sd_fi_fifo_un[i] = NULL;
30862 	un->sd_fi_fifo_xb[i] = NULL;
30863 	un->sd_fi_fifo_arq[i] = NULL;
30864 
30865 	un->sd_fi_fifo_start++;
30866 
30867 	mutex_exit(SD_MUTEX(un));
30868 
30869 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
30870 }
30871 
30872 #endif /* SD_FAULT_INJECTION */
30873 
30874 /*
30875  * This routine is invoked in sd_unit_attach(). Before calling it, the
30876  * properties in conf file should be processed already, and "hotpluggable"
30877  * property was processed also.
30878  *
30879  * The sd driver distinguishes 3 different type of devices: removable media,
30880  * non-removable media, and hotpluggable. Below the differences are defined:
30881  *
30882  * 1. Device ID
30883  *
30884  *     The device ID of a device is used to identify this device. Refer to
30885  *     ddi_devid_register(9F).
30886  *
30887  *     For a non-removable media disk device which can provide 0x80 or 0x83
30888  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
30889  *     device ID is created to identify this device. For other non-removable
30890  *     media devices, a default device ID is created only if this device has
30891  *     at least 2 alter cylinders. Otherwise, this device has no devid.
30892  *
30893  *     -------------------------------------------------------
30894  *     removable media   hotpluggable  | Can Have Device ID
30895  *     -------------------------------------------------------
30896  *         false             false     |     Yes
30897  *         false             true      |     Yes
30898  *         true                x       |     No
30899  *     ------------------------------------------------------
30900  *
30901  *
30902  * 2. SCSI group 4 commands
30903  *
30904  *     In SCSI specs, only some commands in group 4 command set can use
30905  *     8-byte addresses that can be used to access >2TB storage spaces.
30906  *     Other commands have no such capability. Without supporting group4,
30907  *     it is impossible to make full use of storage spaces of a disk with
30908  *     capacity larger than 2TB.
30909  *
30910  *     -----------------------------------------------
30911  *     removable media   hotpluggable   LP64  |  Group
30912  *     -----------------------------------------------
30913  *           false          false       false |   1
30914  *           false          false       true  |   4
30915  *           false          true        false |   1
30916  *           false          true        true  |   4
30917  *           true             x           x   |   5
30918  *     -----------------------------------------------
30919  *
30920  *
30921  * 3. Check for VTOC Label
30922  *
30923  *     If a direct-access disk has no EFI label, sd will check if it has a
30924  *     valid VTOC label. Now, sd also does that check for removable media
30925  *     and hotpluggable devices.
30926  *
30927  *     --------------------------------------------------------------
30928  *     Direct-Access   removable media    hotpluggable |  Check Label
30929  *     -------------------------------------------------------------
30930  *         false          false           false        |   No
30931  *         false          false           true         |   No
30932  *         false          true            false        |   Yes
30933  *         false          true            true         |   Yes
30934  *         true            x                x          |   Yes
30935  *     --------------------------------------------------------------
30936  *
30937  *
30938  * 4. Building default VTOC label
30939  *
30940  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
30941  *     If those devices have no valid VTOC label, sd(4D) will attempt to
30942  *     create default VTOC for them. Currently sd creates default VTOC label
30943  *     for all devices on x86 platform (VTOC_16), but only for removable
30944  *     media devices on SPARC (VTOC_8).
30945  *
30946  *     -----------------------------------------------------------
30947  *       removable media hotpluggable platform   |   Default Label
30948  *     -----------------------------------------------------------
30949  *             false          false    sparc     |     No
30950  *             false          true      x86      |     Yes
30951  *             false          true     sparc     |     Yes
30952  *             true             x        x       |     Yes
30953  *     ----------------------------------------------------------
30954  *
30955  *
30956  * 5. Supported blocksizes of target devices
30957  *
30958  *     Sd supports non-512-byte blocksize for removable media devices only.
30959  *     For other devices, only 512-byte blocksize is supported. This may be
30960  *     changed in near future because some RAID devices require non-512-byte
30961  *     blocksize
30962  *
30963  *     -----------------------------------------------------------
30964  *     removable media    hotpluggable    | non-512-byte blocksize
30965  *     -----------------------------------------------------------
30966  *           false          false         |   No
30967  *           false          true          |   No
30968  *           true             x           |   Yes
30969  *     -----------------------------------------------------------
30970  *
30971  *
30972  * 6. Automatic mount & unmount
30973  *
30974  *     sd(4D) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
30975  *     if a device is removable media device. It return 1 for removable media
30976  *     devices, and 0 for others.
30977  *
30978  *     The automatic mounting subsystem should distinguish between the types
30979  *     of devices and apply automounting policies to each.
30980  *
30981  *
30982  * 7. fdisk partition management
30983  *
30984  *     Fdisk is traditional partition method on x86 platform. sd(4D) driver
30985  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
30986  *     doesn't support fdisk partitions at all. Note: pcfs(4FS) can recognize
30987  *     fdisk partitions on both x86 and SPARC platform.
30988  *
30989  *     -----------------------------------------------------------
30990  *       platform   removable media  USB/1394  |  fdisk supported
30991  *     -----------------------------------------------------------
30992  *        x86         X               X        |       true
30993  *     ------------------------------------------------------------
30994  *        sparc       X               X        |       false
30995  *     ------------------------------------------------------------
30996  *
30997  *
30998  * 8. MBOOT/MBR
30999  *
31000  *     Although sd(4D) doesn't support fdisk on SPARC platform, it does support
31001  *     read/write mboot for removable media devices on sparc platform.
31002  *
31003  *     -----------------------------------------------------------
31004  *       platform   removable media  USB/1394  |  mboot supported
31005  *     -----------------------------------------------------------
31006  *        x86         X               X        |       true
31007  *     ------------------------------------------------------------
31008  *        sparc      false           false     |       false
31009  *        sparc      false           true      |       true
31010  *        sparc      true            false     |       true
31011  *        sparc      true            true      |       true
31012  *     ------------------------------------------------------------
31013  *
31014  *
31015  * 9.  error handling during opening device
31016  *
31017  *     If failed to open a disk device, an errno is returned. For some kinds
31018  *     of errors, different errno is returned depending on if this device is
31019  *     a removable media device. This brings USB/1394 hard disks in line with
31020  *     expected hard disk behavior. It is not expected that this breaks any
31021  *     application.
31022  *
31023  *     ------------------------------------------------------
31024  *       removable media    hotpluggable   |  errno
31025  *     ------------------------------------------------------
31026  *             false          false        |   EIO
31027  *             false          true         |   EIO
31028  *             true             x          |   ENXIO
31029  *     ------------------------------------------------------
31030  *
31031  *
31032  * 11. ioctls: DKIOCEJECT, CDROMEJECT
31033  *
31034  *     These IOCTLs are applicable only to removable media devices.
31035  *
31036  *     -----------------------------------------------------------
31037  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
31038  *     -----------------------------------------------------------
31039  *             false          false        |     No
31040  *             false          true         |     No
31041  *             true            x           |     Yes
31042  *     -----------------------------------------------------------
31043  *
31044  *
31045  * 12. Kstats for partitions
31046  *
31047  *     sd creates partition kstat for non-removable media devices. USB and
31048  *     Firewire hard disks now have partition kstats
31049  *
31050  *      ------------------------------------------------------
31051  *       removable media    hotpluggable   |   kstat
31052  *      ------------------------------------------------------
31053  *             false          false        |    Yes
31054  *             false          true         |    Yes
31055  *             true             x          |    No
31056  *       ------------------------------------------------------
31057  *
31058  *
31059  * 13. Removable media & hotpluggable properties
31060  *
31061  *     Sd driver creates a "removable-media" property for removable media
31062  *     devices. Parent nexus drivers create a "hotpluggable" property if
31063  *     it supports hotplugging.
31064  *
31065  *     ---------------------------------------------------------------------
31066  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
31067  *     ---------------------------------------------------------------------
31068  *       false            false       |    No                   No
31069  *       false            true        |    No                   Yes
31070  *       true             false       |    Yes                  No
31071  *       true             true        |    Yes                  Yes
31072  *     ---------------------------------------------------------------------
31073  *
31074  *
31075  * 14. Power Management
31076  *
31077  *     sd only power manages removable media devices or devices that support
31078  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
31079  *
31080  *     A parent nexus that supports hotplugging can also set "pm-capable"
31081  *     if the disk can be power managed.
31082  *
31083  *     ------------------------------------------------------------
31084  *       removable media hotpluggable pm-capable  |   power manage
31085  *     ------------------------------------------------------------
31086  *             false          false     false     |     No
31087  *             false          false     true      |     Yes
31088  *             false          true      false     |     No
31089  *             false          true      true      |     Yes
31090  *             true             x        x        |     Yes
31091  *     ------------------------------------------------------------
31092  *
31093  *      USB and firewire hard disks can now be power managed independently
31094  *      of the framebuffer
31095  *
31096  *
31097  * 15. Support for USB disks with capacity larger than 1TB
31098  *
31099  *     Currently, sd doesn't permit a fixed disk device with capacity
31100  *     larger than 1TB to be used in a 32-bit operating system environment.
31101  *     However, sd doesn't do that for removable media devices. Instead, it
31102  *     assumes that removable media devices cannot have a capacity larger
31103  *     than 1TB. Therefore, using those devices on 32-bit system is partially
31104  *     supported, which can cause some unexpected results.
31105  *
31106  *     ---------------------------------------------------------------------
31107  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
31108  *     ---------------------------------------------------------------------
31109  *             false          false  |   true         |     no
31110  *             false          true   |   true         |     no
31111  *             true           false  |   true         |     Yes
31112  *             true           true   |   true         |     Yes
31113  *     ---------------------------------------------------------------------
31114  *
31115  *
31116  * 16. Check write-protection at open time
31117  *
31118  *     When a removable media device is being opened for writing without NDELAY
31119  *     flag, sd will check if this device is writable. If attempting to open
31120  *     without NDELAY flag a write-protected device, this operation will abort.
31121  *
31122  *     ------------------------------------------------------------
31123  *       removable media    USB/1394   |   WP Check
31124  *     ------------------------------------------------------------
31125  *             false          false    |     No
31126  *             false          true     |     No
31127  *             true           false    |     Yes
31128  *             true           true     |     Yes
31129  *     ------------------------------------------------------------
31130  *
31131  *
31132  * 17. syslog when corrupted VTOC is encountered
31133  *
31134  *      Currently, if an invalid VTOC is encountered, sd only print syslog
31135  *      for fixed SCSI disks.
31136  *     ------------------------------------------------------------
31137  *       removable media    USB/1394   |   print syslog
31138  *     ------------------------------------------------------------
31139  *             false          false    |     Yes
31140  *             false          true     |     No
31141  *             true           false    |     No
31142  *             true           true     |     No
31143  *     ------------------------------------------------------------
31144  */
31145 static void
31146 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
31147 {
31148 	int	pm_cap;
31149 
31150 	ASSERT(un->un_sd);
31151 	ASSERT(un->un_sd->sd_inq);
31152 
31153 	/*
31154 	 * Enable SYNC CACHE support for all devices.
31155 	 */
31156 	un->un_f_sync_cache_supported = TRUE;
31157 
31158 	/*
31159 	 * Set the sync cache required flag to false.
31160 	 * This would ensure that there is no SYNC CACHE
31161 	 * sent when there are no writes
31162 	 */
31163 	un->un_f_sync_cache_required = FALSE;
31164 
31165 	if (un->un_sd->sd_inq->inq_rmb) {
31166 		/*
31167 		 * The media of this device is removable. And for this kind
31168 		 * of devices, it is possible to change medium after opening
31169 		 * devices. Thus we should support this operation.
31170 		 */
31171 		un->un_f_has_removable_media = TRUE;
31172 
31173 		/*
31174 		 * support non-512-byte blocksize of removable media devices
31175 		 */
31176 		un->un_f_non_devbsize_supported = TRUE;
31177 
31178 		/*
31179 		 * Assume that all removable media devices support DOOR_LOCK
31180 		 */
31181 		un->un_f_doorlock_supported = TRUE;
31182 
31183 		/*
31184 		 * For a removable media device, it is possible to be opened
31185 		 * with NDELAY flag when there is no media in drive, in this
31186 		 * case we don't care if device is writable. But if without
31187 		 * NDELAY flag, we need to check if media is write-protected.
31188 		 */
31189 		un->un_f_chk_wp_open = TRUE;
31190 
31191 		/*
31192 		 * need to start a SCSI watch thread to monitor media state,
31193 		 * when media is being inserted or ejected, notify syseventd.
31194 		 */
31195 		un->un_f_monitor_media_state = TRUE;
31196 
31197 		/*
31198 		 * Some devices don't support START_STOP_UNIT command.
31199 		 * Therefore, we'd better check if a device supports it
31200 		 * before sending it.
31201 		 */
31202 		un->un_f_check_start_stop = TRUE;
31203 
31204 		/*
31205 		 * support eject media ioctl:
31206 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
31207 		 */
31208 		un->un_f_eject_media_supported = TRUE;
31209 
31210 		/*
31211 		 * Because many removable-media devices don't support
31212 		 * LOG_SENSE, we couldn't use this command to check if
31213 		 * a removable media device support power-management.
31214 		 * We assume that they support power-management via
31215 		 * START_STOP_UNIT command and can be spun up and down
31216 		 * without limitations.
31217 		 */
31218 		un->un_f_pm_supported = TRUE;
31219 
31220 		/*
31221 		 * Need to create a zero length (Boolean) property
31222 		 * removable-media for the removable media devices.
31223 		 * Note that the return value of the property is not being
31224 		 * checked, since if unable to create the property
31225 		 * then do not want the attach to fail altogether. Consistent
31226 		 * with other property creation in attach.
31227 		 */
31228 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
31229 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
31230 
31231 	} else {
31232 		/*
31233 		 * create device ID for device
31234 		 */
31235 		un->un_f_devid_supported = TRUE;
31236 
31237 		/*
31238 		 * Spin up non-removable-media devices once it is attached
31239 		 */
31240 		un->un_f_attach_spinup = TRUE;
31241 
31242 		/*
31243 		 * According to SCSI specification, Sense data has two kinds of
31244 		 * format: fixed format, and descriptor format. At present, we
31245 		 * don't support descriptor format sense data for removable
31246 		 * media.
31247 		 */
31248 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
31249 			un->un_f_descr_format_supported = TRUE;
31250 		}
31251 
31252 		/*
31253 		 * kstats are created only for non-removable media devices.
31254 		 *
31255 		 * Set this in sd.conf to 0 in order to disable kstats.  The
31256 		 * default is 1, so they are enabled by default.
31257 		 */
31258 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
31259 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
31260 		    "enable-partition-kstats", 1));
31261 
31262 		/*
31263 		 * Check if HBA has set the "pm-capable" property.
31264 		 * If "pm-capable" exists and is non-zero then we can
31265 		 * power manage the device without checking the start/stop
31266 		 * cycle count log sense page.
31267 		 *
31268 		 * If "pm-capable" exists and is set to be false (0),
31269 		 * then we should not power manage the device.
31270 		 *
31271 		 * If "pm-capable" doesn't exist then pm_cap will
31272 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
31273 		 * sd will check the start/stop cycle count log sense page
31274 		 * and power manage the device if the cycle count limit has
31275 		 * not been exceeded.
31276 		 */
31277 		pm_cap = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
31278 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
31279 		if (SD_PM_CAPABLE_IS_UNDEFINED(pm_cap)) {
31280 			un->un_f_log_sense_supported = TRUE;
31281 			if (!un->un_f_power_condition_disabled &&
31282 			    SD_INQUIRY(un)->inq_ansi == 6) {
31283 				un->un_f_power_condition_supported = TRUE;
31284 			}
31285 		} else {
31286 			/*
31287 			 * pm-capable property exists.
31288 			 *
31289 			 * Convert "TRUE" values for pm_cap to
31290 			 * SD_PM_CAPABLE_IS_TRUE to make it easier to check
31291 			 * later. "TRUE" values are any values defined in
31292 			 * inquiry.h.
31293 			 */
31294 			if (SD_PM_CAPABLE_IS_FALSE(pm_cap)) {
31295 				un->un_f_log_sense_supported = FALSE;
31296 			} else {
31297 				/* SD_PM_CAPABLE_IS_TRUE case */
31298 				un->un_f_pm_supported = TRUE;
31299 				if (!un->un_f_power_condition_disabled &&
31300 				    SD_PM_CAPABLE_IS_SPC_4(pm_cap)) {
31301 					un->un_f_power_condition_supported =
31302 					    TRUE;
31303 				}
31304 				if (SD_PM_CAP_LOG_SUPPORTED(pm_cap)) {
31305 					un->un_f_log_sense_supported = TRUE;
31306 					un->un_f_pm_log_sense_smart =
31307 					    SD_PM_CAP_SMART_LOG(pm_cap);
31308 				}
31309 			}
31310 
31311 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
31312 			    "sd_unit_attach: un:0x%p pm-capable "
31313 			    "property set to %d.\n", un, un->un_f_pm_supported);
31314 		}
31315 	}
31316 
31317 	if (un->un_f_is_hotpluggable) {
31318 
31319 		/*
31320 		 * Have to watch hotpluggable devices as well, since
31321 		 * that's the only way for userland applications to
31322 		 * detect hot removal while device is busy/mounted.
31323 		 */
31324 		un->un_f_monitor_media_state = TRUE;
31325 
31326 		un->un_f_check_start_stop = TRUE;
31327 
31328 	}
31329 }
31330 
31331 /*
31332  * sd_tg_rdwr:
31333  * Provides rdwr access for cmlb via sd_tgops. The start_block is
31334  * in sys block size, req_length in bytes.
31335  *
31336  */
31337 static int
31338 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
31339     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
31340 {
31341 	struct sd_lun *un;
31342 	int path_flag = (int)(uintptr_t)tg_cookie;
31343 	char *dkl = NULL;
31344 	diskaddr_t real_addr = start_block;
31345 	diskaddr_t first_byte, end_block;
31346 
31347 	size_t	buffer_size = reqlength;
31348 	int rval = 0;
31349 	diskaddr_t	cap;
31350 	uint32_t	lbasize;
31351 	sd_ssc_t	*ssc;
31352 
31353 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31354 	if (un == NULL)
31355 		return (ENXIO);
31356 
31357 	if (cmd != TG_READ && cmd != TG_WRITE)
31358 		return (EINVAL);
31359 
31360 	ssc = sd_ssc_init(un);
31361 	mutex_enter(SD_MUTEX(un));
31362 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
31363 		mutex_exit(SD_MUTEX(un));
31364 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31365 		    &lbasize, path_flag);
31366 		if (rval != 0)
31367 			goto done1;
31368 		mutex_enter(SD_MUTEX(un));
31369 		sd_update_block_info(un, lbasize, cap);
31370 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
31371 			mutex_exit(SD_MUTEX(un));
31372 			rval = EIO;
31373 			goto done;
31374 		}
31375 	}
31376 
31377 	if (NOT_DEVBSIZE(un)) {
31378 		/*
31379 		 * sys_blocksize != tgt_blocksize, need to re-adjust
31380 		 * blkno and save the index to beginning of dk_label
31381 		 */
31382 		first_byte  = SD_SYSBLOCKS2BYTES(start_block);
31383 		real_addr = first_byte / un->un_tgt_blocksize;
31384 
31385 		end_block = (first_byte + reqlength +
31386 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
31387 
31388 		/* round up buffer size to multiple of target block size */
31389 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
31390 
31391 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
31392 		    "label_addr: 0x%x allocation size: 0x%x\n",
31393 		    real_addr, buffer_size);
31394 
31395 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
31396 		    (reqlength % un->un_tgt_blocksize) != 0)
31397 			/* the request is not aligned */
31398 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
31399 	}
31400 
31401 	/*
31402 	 * The MMC standard allows READ CAPACITY to be
31403 	 * inaccurate by a bounded amount (in the interest of
31404 	 * response latency).  As a result, failed READs are
31405 	 * commonplace (due to the reading of metadata and not
31406 	 * data). Depending on the per-Vendor/drive Sense data,
31407 	 * the failed READ can cause many (unnecessary) retries.
31408 	 */
31409 
31410 	if (ISCD(un) && (cmd == TG_READ) &&
31411 	    (un->un_f_blockcount_is_valid == TRUE) &&
31412 	    ((start_block == (un->un_blockcount - 1)) ||
31413 	    (start_block == (un->un_blockcount - 2)))) {
31414 			path_flag = SD_PATH_DIRECT_PRIORITY;
31415 	}
31416 
31417 	mutex_exit(SD_MUTEX(un));
31418 	if (cmd == TG_READ) {
31419 		rval = sd_send_scsi_READ(ssc, (dkl != NULL) ? dkl : bufaddr,
31420 		    buffer_size, real_addr, path_flag);
31421 		if (dkl != NULL)
31422 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
31423 			    real_addr), bufaddr, reqlength);
31424 	} else {
31425 		if (dkl) {
31426 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
31427 			    real_addr, path_flag);
31428 			if (rval) {
31429 				goto done1;
31430 			}
31431 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
31432 			    real_addr), reqlength);
31433 		}
31434 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL) ? dkl : bufaddr,
31435 		    buffer_size, real_addr, path_flag);
31436 	}
31437 
31438 done1:
31439 	if (dkl != NULL)
31440 		kmem_free(dkl, buffer_size);
31441 
31442 	if (rval != 0) {
31443 		if (rval == EIO)
31444 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
31445 		else
31446 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31447 	}
31448 done:
31449 	sd_ssc_fini(ssc);
31450 	return (rval);
31451 }
31452 
31453 
31454 static int
31455 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
31456 {
31457 
31458 	struct sd_lun *un;
31459 	diskaddr_t	cap;
31460 	uint32_t	lbasize;
31461 	int		path_flag = (int)(uintptr_t)tg_cookie;
31462 	int		ret = 0;
31463 
31464 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31465 	if (un == NULL)
31466 		return (ENXIO);
31467 
31468 	switch (cmd) {
31469 	case TG_GETPHYGEOM:
31470 	case TG_GETVIRTGEOM:
31471 	case TG_GETCAPACITY:
31472 	case TG_GETBLOCKSIZE:
31473 		mutex_enter(SD_MUTEX(un));
31474 
31475 		if ((un->un_f_blockcount_is_valid == TRUE) &&
31476 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
31477 			cap = un->un_blockcount;
31478 			lbasize = un->un_tgt_blocksize;
31479 			mutex_exit(SD_MUTEX(un));
31480 		} else {
31481 			sd_ssc_t	*ssc;
31482 			mutex_exit(SD_MUTEX(un));
31483 			ssc = sd_ssc_init(un);
31484 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31485 			    &lbasize, path_flag);
31486 			if (ret != 0) {
31487 				if (ret == EIO)
31488 					sd_ssc_assessment(ssc,
31489 					    SD_FMT_STATUS_CHECK);
31490 				else
31491 					sd_ssc_assessment(ssc,
31492 					    SD_FMT_IGNORE);
31493 				sd_ssc_fini(ssc);
31494 				return (ret);
31495 			}
31496 			sd_ssc_fini(ssc);
31497 			mutex_enter(SD_MUTEX(un));
31498 			sd_update_block_info(un, lbasize, cap);
31499 			if ((un->un_f_blockcount_is_valid == FALSE) ||
31500 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
31501 				mutex_exit(SD_MUTEX(un));
31502 				return (EIO);
31503 			}
31504 			mutex_exit(SD_MUTEX(un));
31505 		}
31506 
31507 		if (cmd == TG_GETCAPACITY) {
31508 			*(diskaddr_t *)arg = cap;
31509 			return (0);
31510 		}
31511 
31512 		if (cmd == TG_GETBLOCKSIZE) {
31513 			*(uint32_t *)arg = lbasize;
31514 			return (0);
31515 		}
31516 
31517 		if (cmd == TG_GETPHYGEOM)
31518 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
31519 			    cap, lbasize, path_flag);
31520 		else
31521 			/* TG_GETVIRTGEOM */
31522 			ret = sd_get_virtual_geometry(un,
31523 			    (cmlb_geom_t *)arg, cap, lbasize);
31524 
31525 		return (ret);
31526 
31527 	case TG_GETATTR:
31528 		mutex_enter(SD_MUTEX(un));
31529 		((tg_attribute_t *)arg)->media_is_writable =
31530 		    un->un_f_mmc_writable_media;
31531 		((tg_attribute_t *)arg)->media_is_solid_state =
31532 		    un->un_f_is_solid_state;
31533 		((tg_attribute_t *)arg)->media_is_rotational =
31534 		    un->un_f_is_rotational;
31535 		mutex_exit(SD_MUTEX(un));
31536 		return (0);
31537 	default:
31538 		return (ENOTTY);
31539 
31540 	}
31541 }
31542 
31543 /*
31544  *    Function: sd_ssc_ereport_post
31545  *
31546  * Description: Will be called when SD driver need to post an ereport.
31547  *
31548  *    Context: Kernel thread or interrupt context.
31549  */
31550 
31551 #define	DEVID_IF_KNOWN(d) "devid", DATA_TYPE_STRING, (d) ? (d) : "unknown"
31552 
31553 static void
31554 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
31555 {
31556 	int uscsi_path_instance = 0;
31557 	uchar_t	uscsi_pkt_reason;
31558 	uint32_t uscsi_pkt_state;
31559 	uint32_t uscsi_pkt_statistics;
31560 	uint64_t uscsi_ena;
31561 	uchar_t op_code;
31562 	uint8_t *sensep;
31563 	union scsi_cdb *cdbp;
31564 	uint_t cdblen = 0;
31565 	uint_t senlen = 0;
31566 	struct sd_lun *un;
31567 	dev_info_t *dip;
31568 	char *devid;
31569 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
31570 	    SSC_FLAGS_INVALID_STATUS |
31571 	    SSC_FLAGS_INVALID_SENSE |
31572 	    SSC_FLAGS_INVALID_DATA;
31573 	char assessment[16];
31574 
31575 	ASSERT(ssc != NULL);
31576 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
31577 	ASSERT(ssc->ssc_uscsi_info != NULL);
31578 
31579 	un = ssc->ssc_un;
31580 	ASSERT(un != NULL);
31581 
31582 	dip = un->un_sd->sd_dev;
31583 
31584 	/*
31585 	 * Get the devid:
31586 	 *	devid will only be passed to non-transport error reports.
31587 	 */
31588 	devid = DEVI(dip)->devi_devid_str;
31589 
31590 	/*
31591 	 * If we are syncing or dumping, the command will not be executed
31592 	 * so we bypass this situation.
31593 	 */
31594 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
31595 	    (un->un_state == SD_STATE_DUMPING))
31596 		return;
31597 
31598 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
31599 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
31600 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
31601 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
31602 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
31603 
31604 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
31605 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
31606 
31607 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
31608 	if (cdbp == NULL) {
31609 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
31610 		    "sd_ssc_ereport_post meet empty cdb\n");
31611 		return;
31612 	}
31613 
31614 	op_code = cdbp->scc_cmd;
31615 
31616 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
31617 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
31618 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
31619 
31620 	if (senlen > 0)
31621 		ASSERT(sensep != NULL);
31622 
31623 	/*
31624 	 * Initialize drv_assess to corresponding values.
31625 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
31626 	 * on the sense-key returned back.
31627 	 */
31628 	switch (drv_assess) {
31629 		case SD_FM_DRV_RECOVERY:
31630 			(void) sprintf(assessment, "%s", "recovered");
31631 			break;
31632 		case SD_FM_DRV_RETRY:
31633 			(void) sprintf(assessment, "%s", "retry");
31634 			break;
31635 		case SD_FM_DRV_NOTICE:
31636 			(void) sprintf(assessment, "%s", "info");
31637 			break;
31638 		case SD_FM_DRV_FATAL:
31639 		default:
31640 			(void) sprintf(assessment, "%s", "unknown");
31641 	}
31642 	/*
31643 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
31644 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
31645 	 * driver-assessment will always be "recovered" here.
31646 	 */
31647 	if (drv_assess == SD_FM_DRV_RECOVERY) {
31648 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31649 		    "cmd.disk.recovered", uscsi_ena, devid, NULL,
31650 		    DDI_NOSLEEP, NULL,
31651 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31652 		    DEVID_IF_KNOWN(devid),
31653 		    "driver-assessment", DATA_TYPE_STRING, assessment,
31654 		    "op-code", DATA_TYPE_UINT8, op_code,
31655 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31656 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31657 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31658 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31659 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31660 		    NULL);
31661 		return;
31662 	}
31663 
31664 	/*
31665 	 * If there is un-expected/un-decodable data, we should post
31666 	 * ereport.io.scsi.cmd.disk.dev.uderr.
31667 	 * driver-assessment will be set based on parameter drv_assess.
31668 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
31669 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
31670 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
31671 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
31672 	 */
31673 	if (ssc->ssc_flags & ssc_invalid_flags) {
31674 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
31675 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31676 			    NULL, "cmd.disk.dev.uderr", uscsi_ena, devid,
31677 			    NULL, DDI_NOSLEEP, NULL,
31678 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31679 			    DEVID_IF_KNOWN(devid),
31680 			    "driver-assessment", DATA_TYPE_STRING,
31681 			    drv_assess == SD_FM_DRV_FATAL ?
31682 			    "fail" : assessment,
31683 			    "op-code", DATA_TYPE_UINT8, op_code,
31684 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31685 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31686 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31687 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31688 			    "pkt-stats", DATA_TYPE_UINT32,
31689 			    uscsi_pkt_statistics,
31690 			    "stat-code", DATA_TYPE_UINT8,
31691 			    ssc->ssc_uscsi_cmd->uscsi_status,
31692 			    "un-decode-info", DATA_TYPE_STRING,
31693 			    ssc->ssc_info,
31694 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31695 			    senlen, sensep,
31696 			    NULL);
31697 		} else {
31698 			/*
31699 			 * For other type of invalid data, the
31700 			 * un-decode-value field would be empty because the
31701 			 * un-decodable content could be seen from upper
31702 			 * level payload or inside un-decode-info.
31703 			 */
31704 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31705 			    NULL,
31706 			    "cmd.disk.dev.uderr", uscsi_ena, devid,
31707 			    NULL, DDI_NOSLEEP, NULL,
31708 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31709 			    DEVID_IF_KNOWN(devid),
31710 			    "driver-assessment", DATA_TYPE_STRING,
31711 			    drv_assess == SD_FM_DRV_FATAL ?
31712 			    "fail" : assessment,
31713 			    "op-code", DATA_TYPE_UINT8, op_code,
31714 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31715 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31716 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31717 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31718 			    "pkt-stats", DATA_TYPE_UINT32,
31719 			    uscsi_pkt_statistics,
31720 			    "stat-code", DATA_TYPE_UINT8,
31721 			    ssc->ssc_uscsi_cmd->uscsi_status,
31722 			    "un-decode-info", DATA_TYPE_STRING,
31723 			    ssc->ssc_info,
31724 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31725 			    0, NULL,
31726 			    NULL);
31727 		}
31728 		ssc->ssc_flags &= ~ssc_invalid_flags;
31729 		return;
31730 	}
31731 
31732 	if (uscsi_pkt_reason != CMD_CMPLT ||
31733 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
31734 		/*
31735 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
31736 		 * set inside sd_start_cmds due to errors(bad packet or
31737 		 * fatal transport error), we should take it as a
31738 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
31739 		 * driver-assessment will be set based on drv_assess.
31740 		 * We will set devid to NULL because it is a transport
31741 		 * error.
31742 		 */
31743 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
31744 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
31745 
31746 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31747 		    "cmd.disk.tran", uscsi_ena, NULL, NULL, DDI_NOSLEEP, NULL,
31748 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31749 		    DEVID_IF_KNOWN(devid),
31750 		    "driver-assessment", DATA_TYPE_STRING,
31751 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31752 		    "op-code", DATA_TYPE_UINT8, op_code,
31753 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31754 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31755 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31756 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
31757 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31758 		    NULL);
31759 	} else {
31760 		/*
31761 		 * If we got here, we have a completed command, and we need
31762 		 * to further investigate the sense data to see what kind
31763 		 * of ereport we should post.
31764 		 * No ereport is needed if sense-key is KEY_RECOVERABLE_ERROR
31765 		 * and asc/ascq is "ATA PASS-THROUGH INFORMATION AVAILABLE".
31766 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr if sense-key is
31767 		 * KEY_MEDIUM_ERROR.
31768 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
31769 		 * driver-assessment will be set based on the parameter
31770 		 * drv_assess.
31771 		 */
31772 		if (senlen > 0) {
31773 			/*
31774 			 * Here we have sense data available.
31775 			 */
31776 			uint8_t sense_key = scsi_sense_key(sensep);
31777 			uint8_t sense_asc = scsi_sense_asc(sensep);
31778 			uint8_t sense_ascq = scsi_sense_ascq(sensep);
31779 
31780 			if (sense_key == KEY_RECOVERABLE_ERROR &&
31781 			    sense_asc == 0x00 && sense_ascq == 0x1d)
31782 				return;
31783 
31784 			if (sense_key == KEY_MEDIUM_ERROR) {
31785 				/*
31786 				 * driver-assessment should be "fatal" if
31787 				 * drv_assess is SD_FM_DRV_FATAL.
31788 				 */
31789 				scsi_fm_ereport_post(un->un_sd,
31790 				    uscsi_path_instance, NULL,
31791 				    "cmd.disk.dev.rqs.merr",
31792 				    uscsi_ena, devid, NULL, DDI_NOSLEEP, NULL,
31793 				    FM_VERSION, DATA_TYPE_UINT8,
31794 				    FM_EREPORT_VERS0,
31795 				    DEVID_IF_KNOWN(devid),
31796 				    "driver-assessment",
31797 				    DATA_TYPE_STRING,
31798 				    drv_assess == SD_FM_DRV_FATAL ?
31799 				    "fatal" : assessment,
31800 				    "op-code",
31801 				    DATA_TYPE_UINT8, op_code,
31802 				    "cdb",
31803 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31804 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31805 				    "pkt-reason",
31806 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31807 				    "pkt-state",
31808 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31809 				    "pkt-stats",
31810 				    DATA_TYPE_UINT32,
31811 				    uscsi_pkt_statistics,
31812 				    "stat-code",
31813 				    DATA_TYPE_UINT8,
31814 				    ssc->ssc_uscsi_cmd->uscsi_status,
31815 				    "key",
31816 				    DATA_TYPE_UINT8,
31817 				    scsi_sense_key(sensep),
31818 				    "asc",
31819 				    DATA_TYPE_UINT8,
31820 				    scsi_sense_asc(sensep),
31821 				    "ascq",
31822 				    DATA_TYPE_UINT8,
31823 				    scsi_sense_ascq(sensep),
31824 				    "sense-data",
31825 				    DATA_TYPE_UINT8_ARRAY,
31826 				    senlen, sensep,
31827 				    "lba",
31828 				    DATA_TYPE_UINT64,
31829 				    ssc->ssc_uscsi_info->ui_lba,
31830 				    NULL);
31831 			} else {
31832 				/*
31833 				 * if sense-key == 0x4(hardware
31834 				 * error), driver-assessment should
31835 				 * be "fatal" if drv_assess is
31836 				 * SD_FM_DRV_FATAL.
31837 				 */
31838 				scsi_fm_ereport_post(un->un_sd,
31839 				    uscsi_path_instance, NULL,
31840 				    "cmd.disk.dev.rqs.derr",
31841 				    uscsi_ena, devid,
31842 				    NULL, DDI_NOSLEEP, NULL,
31843 				    FM_VERSION,
31844 				    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31845 				    DEVID_IF_KNOWN(devid),
31846 				    "driver-assessment",
31847 				    DATA_TYPE_STRING,
31848 				    drv_assess == SD_FM_DRV_FATAL ?
31849 				    (sense_key == 0x4 ?
31850 				    "fatal" : "fail") : assessment,
31851 				    "op-code",
31852 				    DATA_TYPE_UINT8, op_code,
31853 				    "cdb",
31854 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31855 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31856 				    "pkt-reason",
31857 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31858 				    "pkt-state",
31859 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31860 				    "pkt-stats",
31861 				    DATA_TYPE_UINT32,
31862 				    uscsi_pkt_statistics,
31863 				    "stat-code",
31864 				    DATA_TYPE_UINT8,
31865 				    ssc->ssc_uscsi_cmd->uscsi_status,
31866 				    "key",
31867 				    DATA_TYPE_UINT8,
31868 				    scsi_sense_key(sensep),
31869 				    "asc",
31870 				    DATA_TYPE_UINT8,
31871 				    scsi_sense_asc(sensep),
31872 				    "ascq",
31873 				    DATA_TYPE_UINT8,
31874 				    scsi_sense_ascq(sensep),
31875 				    "sense-data",
31876 				    DATA_TYPE_UINT8_ARRAY,
31877 				    senlen, sensep,
31878 				    NULL);
31879 			}
31880 		} else {
31881 			/*
31882 			 * For stat_code == STATUS_GOOD, this is not a
31883 			 * hardware error.
31884 			 */
31885 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
31886 				return;
31887 
31888 			/*
31889 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
31890 			 * stat-code but with sense data unavailable.
31891 			 * driver-assessment will be set based on parameter
31892 			 * drv_assess.
31893 			 */
31894 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31895 			    NULL,
31896 			    "cmd.disk.dev.serr", uscsi_ena,
31897 			    devid, NULL, DDI_NOSLEEP, NULL,
31898 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31899 			    DEVID_IF_KNOWN(devid),
31900 			    "driver-assessment", DATA_TYPE_STRING,
31901 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31902 			    "op-code", DATA_TYPE_UINT8, op_code,
31903 			    "cdb",
31904 			    DATA_TYPE_UINT8_ARRAY,
31905 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31906 			    "pkt-reason",
31907 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
31908 			    "pkt-state",
31909 			    DATA_TYPE_UINT8, uscsi_pkt_state,
31910 			    "pkt-stats",
31911 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
31912 			    "stat-code",
31913 			    DATA_TYPE_UINT8,
31914 			    ssc->ssc_uscsi_cmd->uscsi_status,
31915 			    NULL);
31916 		}
31917 	}
31918 }
31919 
31920 /*
31921  *     Function: sd_ssc_extract_info
31922  *
31923  * Description: Extract information available to help generate ereport.
31924  *
31925  *     Context: Kernel thread or interrupt context.
31926  */
31927 static void
31928 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
31929     struct buf *bp, struct sd_xbuf *xp)
31930 {
31931 	size_t senlen = 0;
31932 	union scsi_cdb *cdbp;
31933 	int path_instance;
31934 	/*
31935 	 * Need scsi_cdb_size array to determine the cdb length.
31936 	 */
31937 	extern uchar_t	scsi_cdb_size[];
31938 
31939 	ASSERT(un != NULL);
31940 	ASSERT(pktp != NULL);
31941 	ASSERT(bp != NULL);
31942 	ASSERT(xp != NULL);
31943 	ASSERT(ssc != NULL);
31944 	ASSERT(mutex_owned(SD_MUTEX(un)));
31945 
31946 	/*
31947 	 * Transfer the cdb buffer pointer here.
31948 	 */
31949 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
31950 
31951 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
31952 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
31953 
31954 	/*
31955 	 * Transfer the sense data buffer pointer if sense data is available,
31956 	 * calculate the sense data length first.
31957 	 */
31958 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
31959 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
31960 		/*
31961 		 * For arq case, we will enter here.
31962 		 */
31963 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
31964 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
31965 		} else {
31966 			senlen = SENSE_LENGTH;
31967 		}
31968 	} else {
31969 		/*
31970 		 * For non-arq case, we will enter this branch.
31971 		 */
31972 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
31973 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
31974 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
31975 		}
31976 
31977 	}
31978 
31979 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
31980 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
31981 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
31982 
31983 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
31984 
31985 	/*
31986 	 * Only transfer path_instance when scsi_pkt was properly allocated.
31987 	 */
31988 	path_instance = pktp->pkt_path_instance;
31989 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
31990 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
31991 	else
31992 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
31993 
31994 	/*
31995 	 * Copy in the other fields we may need when posting ereport.
31996 	 */
31997 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
31998 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
31999 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
32000 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
32001 
32002 	/*
32003 	 * For partially read/write command, we will not create ena
32004 	 * in case of a successful command be reconized as recovered.
32005 	 */
32006 	if ((pktp->pkt_reason == CMD_CMPLT) &&
32007 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
32008 	    (senlen == 0)) {
32009 		return;
32010 	}
32011 
32012 	/*
32013 	 * To associate ereports of a single command execution flow, we
32014 	 * need a shared ena for a specific command.
32015 	 */
32016 	if (xp->xb_ena == 0)
32017 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
32018 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
32019 }
32020 
32021 
32022 /*
32023  *     Function: sd_check_bdc_vpd
32024  *
32025  * Description: Query the optional INQUIRY VPD page 0xb1. If the device
32026  *              supports VPD page 0xb1, sd examines the MEDIUM ROTATION
32027  *              RATE.
32028  *
32029  *		Set the following based on RPM value:
32030  *		= 0	device is not solid state, non-rotational
32031  *		= 1	device is solid state, non-rotational
32032  *		> 1	device is not solid state, rotational
32033  *
32034  *     Context: Kernel thread or interrupt context.
32035  */
32036 
32037 static void
32038 sd_check_bdc_vpd(sd_ssc_t *ssc)
32039 {
32040 	int		rval		= 0;
32041 	uchar_t		*inqb1		= NULL;
32042 	size_t		inqb1_len	= MAX_INQUIRY_SIZE;
32043 	size_t		inqb1_resid	= 0;
32044 	struct sd_lun	*un;
32045 
32046 	ASSERT(ssc != NULL);
32047 	un = ssc->ssc_un;
32048 	ASSERT(un != NULL);
32049 	ASSERT(!mutex_owned(SD_MUTEX(un)));
32050 
32051 	mutex_enter(SD_MUTEX(un));
32052 	un->un_f_is_rotational = TRUE;
32053 	un->un_f_is_solid_state = FALSE;
32054 
32055 	if (ISCD(un)) {
32056 		mutex_exit(SD_MUTEX(un));
32057 		return;
32058 	}
32059 
32060 	if (sd_check_vpd_page_support(ssc) == 0 &&
32061 	    un->un_vpd_page_mask & SD_VPD_DEV_CHARACTER_PG) {
32062 		mutex_exit(SD_MUTEX(un));
32063 		/* collect page b1 data */
32064 		inqb1 = kmem_zalloc(inqb1_len, KM_SLEEP);
32065 
32066 		rval = sd_send_scsi_INQUIRY(ssc, inqb1, inqb1_len,
32067 		    0x01, 0xB1, &inqb1_resid);
32068 
32069 		if (rval == 0 && (inqb1_len - inqb1_resid > 5)) {
32070 			SD_TRACE(SD_LOG_COMMON, un,
32071 			    "sd_check_bdc_vpd: \
32072 			    successfully get VPD page: %x \
32073 			    PAGE LENGTH: %x BYTE 4: %x \
32074 			    BYTE 5: %x", inqb1[1], inqb1[3], inqb1[4],
32075 			    inqb1[5]);
32076 
32077 			mutex_enter(SD_MUTEX(un));
32078 			/*
32079 			 * Check the MEDIUM ROTATION RATE.
32080 			 */
32081 			if (inqb1[4] == 0) {
32082 				if (inqb1[5] == 0) {
32083 					un->un_f_is_rotational = FALSE;
32084 				} else if (inqb1[5] == 1) {
32085 					un->un_f_is_rotational = FALSE;
32086 					un->un_f_is_solid_state = TRUE;
32087 					/*
32088 					 * Solid state drives don't need
32089 					 * disksort.
32090 					 */
32091 					un->un_f_disksort_disabled = TRUE;
32092 				}
32093 			}
32094 			mutex_exit(SD_MUTEX(un));
32095 		} else if (rval != 0) {
32096 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
32097 		}
32098 
32099 		kmem_free(inqb1, inqb1_len);
32100 	} else {
32101 		mutex_exit(SD_MUTEX(un));
32102 	}
32103 }
32104 
32105 /*
32106  *	Function: sd_check_emulation_mode
32107  *
32108  *   Description: Check whether the SSD is at emulation mode
32109  *		  by issuing READ_CAPACITY_16 to see whether
32110  *		  we can get physical block size of the drive.
32111  *
32112  *	 Context: Kernel thread or interrupt context.
32113  */
32114 
32115 static void
32116 sd_check_emulation_mode(sd_ssc_t *ssc)
32117 {
32118 	int		rval = 0;
32119 	uint64_t	capacity;
32120 	uint_t		lbasize;
32121 	uint_t		pbsize;
32122 	int		i;
32123 	int		devid_len;
32124 	struct sd_lun	*un;
32125 
32126 	ASSERT(ssc != NULL);
32127 	un = ssc->ssc_un;
32128 	ASSERT(un != NULL);
32129 	ASSERT(!mutex_owned(SD_MUTEX(un)));
32130 
32131 	mutex_enter(SD_MUTEX(un));
32132 	if (ISCD(un)) {
32133 		mutex_exit(SD_MUTEX(un));
32134 		return;
32135 	}
32136 
32137 	if (un->un_f_descr_format_supported) {
32138 		mutex_exit(SD_MUTEX(un));
32139 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
32140 		    &pbsize, SD_PATH_DIRECT);
32141 		mutex_enter(SD_MUTEX(un));
32142 
32143 		if (rval != 0) {
32144 			un->un_phy_blocksize = DEV_BSIZE;
32145 		} else {
32146 			if (!ISP2(pbsize % DEV_BSIZE) || pbsize == 0) {
32147 				un->un_phy_blocksize = DEV_BSIZE;
32148 			} else if (pbsize > un->un_phy_blocksize) {
32149 				/*
32150 				 * Don't reset the physical blocksize
32151 				 * unless we've detected a larger value.
32152 				 */
32153 				un->un_phy_blocksize = pbsize;
32154 			}
32155 		}
32156 	}
32157 
32158 	for (i = 0; i < sd_flash_dev_table_size; i++) {
32159 		devid_len = (int)strlen(sd_flash_dev_table[i]);
32160 		if (sd_sdconf_id_match(un, sd_flash_dev_table[i], devid_len)
32161 		    == SD_SUCCESS) {
32162 			un->un_phy_blocksize = SSD_SECSIZE;
32163 			if (un->un_f_is_solid_state &&
32164 			    un->un_phy_blocksize != un->un_tgt_blocksize)
32165 				un->un_f_enable_rmw = TRUE;
32166 		}
32167 	}
32168 
32169 	mutex_exit(SD_MUTEX(un));
32170 }
32171