xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 50c81445)
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_log_buf			ssd_log_buf
186 #define	sd_log_mutex			ssd_log_mutex
187 
188 #define	sd_disk_table			ssd_disk_table
189 #define	sd_disk_table_size		ssd_disk_table_size
190 #define	sd_sense_mutex			ssd_sense_mutex
191 #define	sd_cdbtab			ssd_cdbtab
192 
193 #define	sd_cb_ops			ssd_cb_ops
194 #define	sd_ops				ssd_ops
195 #define	sd_additional_codes		ssd_additional_codes
196 #define	sd_tgops			ssd_tgops
197 
198 #define	sd_minor_data			ssd_minor_data
199 #define	sd_minor_data_efi		ssd_minor_data_efi
200 
201 #define	sd_tq				ssd_tq
202 #define	sd_wmr_tq			ssd_wmr_tq
203 #define	sd_taskq_name			ssd_taskq_name
204 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
205 #define	sd_taskq_minalloc		ssd_taskq_minalloc
206 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
207 
208 #define	sd_dump_format_string		ssd_dump_format_string
209 
210 #define	sd_iostart_chain		ssd_iostart_chain
211 #define	sd_iodone_chain			ssd_iodone_chain
212 
213 #define	sd_pm_idletime			ssd_pm_idletime
214 
215 #define	sd_force_pm_supported		ssd_force_pm_supported
216 
217 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
218 
219 #define	sd_ssc_init			ssd_ssc_init
220 #define	sd_ssc_send			ssd_ssc_send
221 #define	sd_ssc_fini			ssd_ssc_fini
222 #define	sd_ssc_assessment		ssd_ssc_assessment
223 #define	sd_ssc_post			ssd_ssc_post
224 #define	sd_ssc_print			ssd_ssc_print
225 #define	sd_ssc_ereport_post		ssd_ssc_ereport_post
226 #define	sd_ssc_set_info			ssd_ssc_set_info
227 #define	sd_ssc_extract_info		ssd_ssc_extract_info
228 
229 #endif
230 
231 #ifdef	SDDEBUG
232 int	sd_force_pm_supported		= 0;
233 #endif	/* SDDEBUG */
234 
235 void *sd_state				= NULL;
236 int sd_io_time				= SD_IO_TIME;
237 int sd_failfast_enable			= 1;
238 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
239 int sd_report_pfa			= 1;
240 int sd_max_throttle			= SD_MAX_THROTTLE;
241 int sd_min_throttle			= SD_MIN_THROTTLE;
242 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
243 int sd_qfull_throttle_enable		= TRUE;
244 
245 int sd_retry_on_reservation_conflict	= 1;
246 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
247 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
248 
249 static int sd_dtype_optical_bind	= -1;
250 
251 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
252 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
253 
254 /*
255  * Global data for debug logging. To enable debug printing, sd_component_mask
256  * and sd_level_mask should be set to the desired bit patterns as outlined in
257  * sddef.h.
258  */
259 uint_t	sd_component_mask		= 0x0;
260 uint_t	sd_level_mask			= 0x0;
261 struct	sd_lun *sd_debug_un		= NULL;
262 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
263 
264 /* Note: these may go away in the future... */
265 static uint32_t	sd_xbuf_active_limit	= 512;
266 static uint32_t sd_xbuf_reserve_limit	= 16;
267 
268 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
269 
270 /*
271  * Timer value used to reset the throttle after it has been reduced
272  * (typically in response to TRAN_BUSY or STATUS_QFULL)
273  */
274 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
275 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
276 
277 /*
278  * Interval value associated with the media change scsi watch.
279  */
280 static int sd_check_media_time		= 3000000;
281 
282 /*
283  * Wait value used for in progress operations during a DDI_SUSPEND
284  */
285 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
286 
287 /*
288  * Global buffer and mutex for debug logging
289  */
290 static char	sd_log_buf[1024];
291 static kmutex_t	sd_log_mutex;
292 
293 /*
294  * Structs and globals for recording attached lun information.
295  * This maintains a chain. Each node in the chain represents a SCSI controller.
296  * The structure records the number of luns attached to each target connected
297  * with the controller.
298  * For parallel scsi device only.
299  */
300 struct sd_scsi_hba_tgt_lun {
301 	struct sd_scsi_hba_tgt_lun	*next;
302 	dev_info_t			*pdip;
303 	int				nlun[NTARGETS_WIDE];
304 };
305 
306 /*
307  * Flag to indicate the lun is attached or detached
308  */
309 #define	SD_SCSI_LUN_ATTACH	0
310 #define	SD_SCSI_LUN_DETACH	1
311 
312 static kmutex_t	sd_scsi_target_lun_mutex;
313 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
314 
315 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
316     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
317 
318 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
319     sd_scsi_target_lun_head))
320 
321 /*
322  * "Smart" Probe Caching structs, globals, #defines, etc.
323  * For parallel scsi and non-self-identify device only.
324  */
325 
326 /*
327  * The following resources and routines are implemented to support
328  * "smart" probing, which caches the scsi_probe() results in an array,
329  * in order to help avoid long probe times.
330  */
331 struct sd_scsi_probe_cache {
332 	struct	sd_scsi_probe_cache	*next;
333 	dev_info_t	*pdip;
334 	int		cache[NTARGETS_WIDE];
335 };
336 
337 static kmutex_t	sd_scsi_probe_cache_mutex;
338 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
339 
340 /*
341  * Really we only need protection on the head of the linked list, but
342  * better safe than sorry.
343  */
344 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
345     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
346 
347 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
348     sd_scsi_probe_cache_head))
349 
350 /*
351  * Power attribute table
352  */
353 static sd_power_attr_ss sd_pwr_ss = {
354 	{ "NAME=spindle-motor", "0=off", "1=on", NULL },
355 	{0, 100},
356 	{30, 0},
357 	{20000, 0}
358 };
359 
360 static sd_power_attr_pc sd_pwr_pc = {
361 	{ "NAME=spindle-motor", "0=stopped", "1=standby", "2=idle",
362 		"3=active", NULL },
363 	{0, 0, 0, 100},
364 	{90, 90, 20, 0},
365 	{15000, 15000, 1000, 0}
366 };
367 
368 /*
369  * Power level to power condition
370  */
371 static int sd_pl2pc[] = {
372 	SD_TARGET_START_VALID,
373 	SD_TARGET_STANDBY,
374 	SD_TARGET_IDLE,
375 	SD_TARGET_ACTIVE
376 };
377 
378 /*
379  * Vendor specific data name property declarations
380  */
381 
382 #if defined(__fibre) || defined(__x86)
383 
384 static sd_tunables seagate_properties = {
385 	SEAGATE_THROTTLE_VALUE,
386 	0,
387 	0,
388 	0,
389 	0,
390 	0,
391 	0,
392 	0,
393 	0
394 };
395 
396 
397 static sd_tunables fujitsu_properties = {
398 	FUJITSU_THROTTLE_VALUE,
399 	0,
400 	0,
401 	0,
402 	0,
403 	0,
404 	0,
405 	0,
406 	0
407 };
408 
409 static sd_tunables ibm_properties = {
410 	IBM_THROTTLE_VALUE,
411 	0,
412 	0,
413 	0,
414 	0,
415 	0,
416 	0,
417 	0,
418 	0
419 };
420 
421 static sd_tunables sve_properties = {
422 	SVE_THROTTLE_VALUE,
423 	0,
424 	0,
425 	SVE_BUSY_RETRIES,
426 	SVE_RESET_RETRY_COUNT,
427 	SVE_RESERVE_RELEASE_TIME,
428 	SVE_MIN_THROTTLE_VALUE,
429 	SVE_DISKSORT_DISABLED_FLAG,
430 	0
431 };
432 
433 static sd_tunables maserati_properties = {
434 	0,
435 	0,
436 	0,
437 	0,
438 	0,
439 	0,
440 	0,
441 	MASERATI_DISKSORT_DISABLED_FLAG,
442 	MASERATI_LUN_RESET_ENABLED_FLAG
443 };
444 
445 static sd_tunables pirus_properties = {
446 	PIRUS_THROTTLE_VALUE,
447 	0,
448 	PIRUS_NRR_COUNT,
449 	PIRUS_BUSY_RETRIES,
450 	PIRUS_RESET_RETRY_COUNT,
451 	0,
452 	PIRUS_MIN_THROTTLE_VALUE,
453 	PIRUS_DISKSORT_DISABLED_FLAG,
454 	PIRUS_LUN_RESET_ENABLED_FLAG
455 };
456 
457 #endif
458 
459 #if (defined(__sparc) && !defined(__fibre)) || \
460 	(defined(__x86))
461 
462 
463 static sd_tunables elite_properties = {
464 	ELITE_THROTTLE_VALUE,
465 	0,
466 	0,
467 	0,
468 	0,
469 	0,
470 	0,
471 	0,
472 	0
473 };
474 
475 static sd_tunables st31200n_properties = {
476 	ST31200N_THROTTLE_VALUE,
477 	0,
478 	0,
479 	0,
480 	0,
481 	0,
482 	0,
483 	0,
484 	0
485 };
486 
487 #endif /* Fibre or not */
488 
489 static sd_tunables lsi_properties_scsi = {
490 	LSI_THROTTLE_VALUE,
491 	0,
492 	LSI_NOTREADY_RETRIES,
493 	0,
494 	0,
495 	0,
496 	0,
497 	0,
498 	0
499 };
500 
501 static sd_tunables symbios_properties = {
502 	SYMBIOS_THROTTLE_VALUE,
503 	0,
504 	SYMBIOS_NOTREADY_RETRIES,
505 	0,
506 	0,
507 	0,
508 	0,
509 	0,
510 	0
511 };
512 
513 static sd_tunables lsi_properties = {
514 	0,
515 	0,
516 	LSI_NOTREADY_RETRIES,
517 	0,
518 	0,
519 	0,
520 	0,
521 	0,
522 	0
523 };
524 
525 static sd_tunables lsi_oem_properties = {
526 	0,
527 	0,
528 	LSI_OEM_NOTREADY_RETRIES,
529 	0,
530 	0,
531 	0,
532 	0,
533 	0,
534 	0,
535 	1
536 };
537 
538 
539 
540 #if (defined(SD_PROP_TST))
541 
542 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
543 #define	SD_TST_THROTTLE_VAL	16
544 #define	SD_TST_NOTREADY_VAL	12
545 #define	SD_TST_BUSY_VAL		60
546 #define	SD_TST_RST_RETRY_VAL	36
547 #define	SD_TST_RSV_REL_TIME	60
548 
549 static sd_tunables tst_properties = {
550 	SD_TST_THROTTLE_VAL,
551 	SD_TST_CTYPE_VAL,
552 	SD_TST_NOTREADY_VAL,
553 	SD_TST_BUSY_VAL,
554 	SD_TST_RST_RETRY_VAL,
555 	SD_TST_RSV_REL_TIME,
556 	0,
557 	0,
558 	0
559 };
560 #endif
561 
562 /* This is similar to the ANSI toupper implementation */
563 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
564 
565 /*
566  * Static Driver Configuration Table
567  *
568  * This is the table of disks which need throttle adjustment (or, perhaps
569  * something else as defined by the flags at a future time.)  device_id
570  * is a string consisting of concatenated vid (vendor), pid (product/model)
571  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
572  * the parts of the string are as defined by the sizes in the scsi_inquiry
573  * structure.  Device type is searched as far as the device_id string is
574  * defined.  Flags defines which values are to be set in the driver from the
575  * properties list.
576  *
577  * Entries below which begin and end with a "*" are a special case.
578  * These do not have a specific vendor, and the string which follows
579  * can appear anywhere in the 16 byte PID portion of the inquiry data.
580  *
581  * Entries below which begin and end with a " " (blank) are a special
582  * case. The comparison function will treat multiple consecutive blanks
583  * as equivalent to a single blank. For example, this causes a
584  * sd_disk_table entry of " NEC CDROM " to match a device's id string
585  * of  "NEC       CDROM".
586  *
587  * Note: The MD21 controller type has been obsoleted.
588  *	 ST318202F is a Legacy device
589  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
590  *	 made with an FC connection. The entries here are a legacy.
591  */
592 static sd_disk_config_t sd_disk_table[] = {
593 #if defined(__fibre) || defined(__x86)
594 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
595 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
596 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
597 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
598 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
599 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
600 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
601 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
602 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
603 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
604 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
605 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
606 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
607 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
608 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
609 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
610 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
611 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
612 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
613 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
614 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
615 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
616 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
617 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
618 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
619 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
620 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
621 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
622 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
623 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
624 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
625 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
626 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
627 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
628 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
629 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
630 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
631 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
632 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
633 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
634 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
635 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
636 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
637 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
638 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
639 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
640 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
641 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
642 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
643 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
644 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
645 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
646 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
647 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
648 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
649 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
650 		SD_CONF_BSET_BSY_RETRY_COUNT|
651 		SD_CONF_BSET_RST_RETRIES|
652 		SD_CONF_BSET_RSV_REL_TIME|
653 		SD_CONF_BSET_MIN_THROTTLE|
654 		SD_CONF_BSET_DISKSORT_DISABLED,
655 		&sve_properties },
656 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
657 		SD_CONF_BSET_LUN_RESET_ENABLED,
658 		&maserati_properties },
659 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
660 		SD_CONF_BSET_NRR_COUNT|
661 		SD_CONF_BSET_BSY_RETRY_COUNT|
662 		SD_CONF_BSET_RST_RETRIES|
663 		SD_CONF_BSET_MIN_THROTTLE|
664 		SD_CONF_BSET_DISKSORT_DISABLED|
665 		SD_CONF_BSET_LUN_RESET_ENABLED,
666 		&pirus_properties },
667 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
668 		SD_CONF_BSET_NRR_COUNT|
669 		SD_CONF_BSET_BSY_RETRY_COUNT|
670 		SD_CONF_BSET_RST_RETRIES|
671 		SD_CONF_BSET_MIN_THROTTLE|
672 		SD_CONF_BSET_DISKSORT_DISABLED|
673 		SD_CONF_BSET_LUN_RESET_ENABLED,
674 		&pirus_properties },
675 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
676 		SD_CONF_BSET_NRR_COUNT|
677 		SD_CONF_BSET_BSY_RETRY_COUNT|
678 		SD_CONF_BSET_RST_RETRIES|
679 		SD_CONF_BSET_MIN_THROTTLE|
680 		SD_CONF_BSET_DISKSORT_DISABLED|
681 		SD_CONF_BSET_LUN_RESET_ENABLED,
682 		&pirus_properties },
683 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
684 		SD_CONF_BSET_NRR_COUNT|
685 		SD_CONF_BSET_BSY_RETRY_COUNT|
686 		SD_CONF_BSET_RST_RETRIES|
687 		SD_CONF_BSET_MIN_THROTTLE|
688 		SD_CONF_BSET_DISKSORT_DISABLED|
689 		SD_CONF_BSET_LUN_RESET_ENABLED,
690 		&pirus_properties },
691 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
692 		SD_CONF_BSET_NRR_COUNT|
693 		SD_CONF_BSET_BSY_RETRY_COUNT|
694 		SD_CONF_BSET_RST_RETRIES|
695 		SD_CONF_BSET_MIN_THROTTLE|
696 		SD_CONF_BSET_DISKSORT_DISABLED|
697 		SD_CONF_BSET_LUN_RESET_ENABLED,
698 		&pirus_properties },
699 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
700 		SD_CONF_BSET_NRR_COUNT|
701 		SD_CONF_BSET_BSY_RETRY_COUNT|
702 		SD_CONF_BSET_RST_RETRIES|
703 		SD_CONF_BSET_MIN_THROTTLE|
704 		SD_CONF_BSET_DISKSORT_DISABLED|
705 		SD_CONF_BSET_LUN_RESET_ENABLED,
706 		&pirus_properties },
707 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
708 	{ "SUN     SUN_6180", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
709 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
710 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
711 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
712 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
713 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
714 #endif /* fibre or NON-sparc platforms */
715 #if ((defined(__sparc) && !defined(__fibre)) ||\
716 	(defined(__x86)))
717 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
718 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
719 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
720 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
721 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
722 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
723 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
724 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
725 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
726 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
727 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
728 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
729 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
730 	    &symbios_properties },
731 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
732 	    &lsi_properties_scsi },
733 #if defined(__x86)
734 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
735 				    | SD_CONF_BSET_READSUB_BCD
736 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
737 				    | SD_CONF_BSET_NO_READ_HEADER
738 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
739 
740 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
741 				    | SD_CONF_BSET_READSUB_BCD
742 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
743 				    | SD_CONF_BSET_NO_READ_HEADER
744 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
745 #endif /* __x86 */
746 #endif /* sparc NON-fibre or NON-sparc platforms */
747 
748 #if (defined(SD_PROP_TST))
749 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
750 				| SD_CONF_BSET_CTYPE
751 				| SD_CONF_BSET_NRR_COUNT
752 				| SD_CONF_BSET_FAB_DEVID
753 				| SD_CONF_BSET_NOCACHE
754 				| SD_CONF_BSET_BSY_RETRY_COUNT
755 				| SD_CONF_BSET_PLAYMSF_BCD
756 				| SD_CONF_BSET_READSUB_BCD
757 				| SD_CONF_BSET_READ_TOC_TRK_BCD
758 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
759 				| SD_CONF_BSET_NO_READ_HEADER
760 				| SD_CONF_BSET_READ_CD_XD4
761 				| SD_CONF_BSET_RST_RETRIES
762 				| SD_CONF_BSET_RSV_REL_TIME
763 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
764 #endif
765 };
766 
767 static const int sd_disk_table_size =
768 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
769 
770 /*
771  * Emulation mode disk drive VID/PID table
772  */
773 static char sd_flash_dev_table[][25] = {
774 	"ATA     MARVELL SD88SA02",
775 	"MARVELL SD88SA02",
776 	"TOSHIBA THNSNV05",
777 };
778 
779 static const int sd_flash_dev_table_size =
780 	sizeof (sd_flash_dev_table) / sizeof (sd_flash_dev_table[0]);
781 
782 #define	SD_INTERCONNECT_PARALLEL	0
783 #define	SD_INTERCONNECT_FABRIC		1
784 #define	SD_INTERCONNECT_FIBRE		2
785 #define	SD_INTERCONNECT_SSA		3
786 #define	SD_INTERCONNECT_SATA		4
787 #define	SD_INTERCONNECT_SAS		5
788 
789 #define	SD_IS_PARALLEL_SCSI(un)		\
790 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
791 #define	SD_IS_SERIAL(un)		\
792 	(((un)->un_interconnect_type == SD_INTERCONNECT_SATA) ||\
793 	((un)->un_interconnect_type == SD_INTERCONNECT_SAS))
794 
795 /*
796  * Definitions used by device id registration routines
797  */
798 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
799 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
800 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
801 
802 static kmutex_t sd_sense_mutex = {0};
803 
804 /*
805  * Macros for updates of the driver state
806  */
807 #define	New_state(un, s)        \
808 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
809 #define	Restore_state(un)	\
810 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
811 
812 static struct sd_cdbinfo sd_cdbtab[] = {
813 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
814 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
815 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
816 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
817 };
818 
819 /*
820  * Specifies the number of seconds that must have elapsed since the last
821  * cmd. has completed for a device to be declared idle to the PM framework.
822  */
823 static int sd_pm_idletime = 1;
824 
825 /*
826  * Internal function prototypes
827  */
828 
829 #if (defined(__fibre))
830 /*
831  * These #defines are to avoid namespace collisions that occur because this
832  * code is currently used to compile two separate driver modules: sd and ssd.
833  * All function names need to be treated this way (even if declared static)
834  * in order to allow the debugger to resolve the names properly.
835  * It is anticipated that in the near future the ssd module will be obsoleted,
836  * at which time this ugliness should go away.
837  */
838 #define	sd_log_trace			ssd_log_trace
839 #define	sd_log_info			ssd_log_info
840 #define	sd_log_err			ssd_log_err
841 #define	sdprobe				ssdprobe
842 #define	sdinfo				ssdinfo
843 #define	sd_prop_op			ssd_prop_op
844 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
845 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
846 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
847 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
848 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
849 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
850 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
851 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
852 #define	sd_spin_up_unit			ssd_spin_up_unit
853 #define	sd_enable_descr_sense		ssd_enable_descr_sense
854 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
855 #define	sd_set_mmc_caps			ssd_set_mmc_caps
856 #define	sd_read_unit_properties		ssd_read_unit_properties
857 #define	sd_process_sdconf_file		ssd_process_sdconf_file
858 #define	sd_process_sdconf_table		ssd_process_sdconf_table
859 #define	sd_sdconf_id_match		ssd_sdconf_id_match
860 #define	sd_blank_cmp			ssd_blank_cmp
861 #define	sd_chk_vers1_data		ssd_chk_vers1_data
862 #define	sd_set_vers1_properties		ssd_set_vers1_properties
863 #define	sd_check_bdc_vpd		ssd_check_bdc_vpd
864 #define	sd_check_emulation_mode		ssd_check_emulation_mode
865 
866 #define	sd_get_physical_geometry	ssd_get_physical_geometry
867 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
868 #define	sd_update_block_info		ssd_update_block_info
869 #define	sd_register_devid		ssd_register_devid
870 #define	sd_get_devid			ssd_get_devid
871 #define	sd_create_devid			ssd_create_devid
872 #define	sd_write_deviceid		ssd_write_deviceid
873 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
874 #define	sd_setup_pm			ssd_setup_pm
875 #define	sd_create_pm_components		ssd_create_pm_components
876 #define	sd_ddi_suspend			ssd_ddi_suspend
877 #define	sd_ddi_resume			ssd_ddi_resume
878 #define	sd_pm_state_change		ssd_pm_state_change
879 #define	sdpower				ssdpower
880 #define	sdattach			ssdattach
881 #define	sddetach			ssddetach
882 #define	sd_unit_attach			ssd_unit_attach
883 #define	sd_unit_detach			ssd_unit_detach
884 #define	sd_set_unit_attributes		ssd_set_unit_attributes
885 #define	sd_create_errstats		ssd_create_errstats
886 #define	sd_set_errstats			ssd_set_errstats
887 #define	sd_set_pstats			ssd_set_pstats
888 #define	sddump				ssddump
889 #define	sd_scsi_poll			ssd_scsi_poll
890 #define	sd_send_polled_RQS		ssd_send_polled_RQS
891 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
892 #define	sd_init_event_callbacks		ssd_init_event_callbacks
893 #define	sd_event_callback		ssd_event_callback
894 #define	sd_cache_control		ssd_cache_control
895 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
896 #define	sd_get_write_cache_changeable	ssd_get_write_cache_changeable
897 #define	sd_get_nv_sup			ssd_get_nv_sup
898 #define	sd_make_device			ssd_make_device
899 #define	sdopen				ssdopen
900 #define	sdclose				ssdclose
901 #define	sd_ready_and_valid		ssd_ready_and_valid
902 #define	sdmin				ssdmin
903 #define	sdread				ssdread
904 #define	sdwrite				ssdwrite
905 #define	sdaread				ssdaread
906 #define	sdawrite			ssdawrite
907 #define	sdstrategy			ssdstrategy
908 #define	sdioctl				ssdioctl
909 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
910 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
911 #define	sd_checksum_iostart		ssd_checksum_iostart
912 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
913 #define	sd_pm_iostart			ssd_pm_iostart
914 #define	sd_core_iostart			ssd_core_iostart
915 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
916 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
917 #define	sd_checksum_iodone		ssd_checksum_iodone
918 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
919 #define	sd_pm_iodone			ssd_pm_iodone
920 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
921 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
922 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
923 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
924 #define	sd_buf_iodone			ssd_buf_iodone
925 #define	sd_uscsi_strategy		ssd_uscsi_strategy
926 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
927 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
928 #define	sd_uscsi_iodone			ssd_uscsi_iodone
929 #define	sd_xbuf_strategy		ssd_xbuf_strategy
930 #define	sd_xbuf_init			ssd_xbuf_init
931 #define	sd_pm_entry			ssd_pm_entry
932 #define	sd_pm_exit			ssd_pm_exit
933 
934 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
935 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
936 
937 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
938 #define	sdintr				ssdintr
939 #define	sd_start_cmds			ssd_start_cmds
940 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
941 #define	sd_bioclone_alloc		ssd_bioclone_alloc
942 #define	sd_bioclone_free		ssd_bioclone_free
943 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
944 #define	sd_shadow_buf_free		ssd_shadow_buf_free
945 #define	sd_print_transport_rejected_message	\
946 					ssd_print_transport_rejected_message
947 #define	sd_retry_command		ssd_retry_command
948 #define	sd_set_retry_bp			ssd_set_retry_bp
949 #define	sd_send_request_sense_command	ssd_send_request_sense_command
950 #define	sd_start_retry_command		ssd_start_retry_command
951 #define	sd_start_direct_priority_command	\
952 					ssd_start_direct_priority_command
953 #define	sd_return_failed_command	ssd_return_failed_command
954 #define	sd_return_failed_command_no_restart	\
955 					ssd_return_failed_command_no_restart
956 #define	sd_return_command		ssd_return_command
957 #define	sd_sync_with_callback		ssd_sync_with_callback
958 #define	sdrunout			ssdrunout
959 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
960 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
961 #define	sd_reduce_throttle		ssd_reduce_throttle
962 #define	sd_restore_throttle		ssd_restore_throttle
963 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
964 #define	sd_init_cdb_limits		ssd_init_cdb_limits
965 #define	sd_pkt_status_good		ssd_pkt_status_good
966 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
967 #define	sd_pkt_status_busy		ssd_pkt_status_busy
968 #define	sd_pkt_status_reservation_conflict	\
969 					ssd_pkt_status_reservation_conflict
970 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
971 #define	sd_handle_request_sense		ssd_handle_request_sense
972 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
973 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
974 #define	sd_validate_sense_data		ssd_validate_sense_data
975 #define	sd_decode_sense			ssd_decode_sense
976 #define	sd_print_sense_msg		ssd_print_sense_msg
977 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
978 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
979 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
980 #define	sd_sense_key_medium_or_hardware_error	\
981 					ssd_sense_key_medium_or_hardware_error
982 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
983 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
984 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
985 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
986 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
987 #define	sd_sense_key_default		ssd_sense_key_default
988 #define	sd_print_retry_msg		ssd_print_retry_msg
989 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
990 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
991 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
992 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
993 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
994 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
995 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
996 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
997 #define	sd_pkt_reason_default		ssd_pkt_reason_default
998 #define	sd_reset_target			ssd_reset_target
999 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
1000 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
1001 #define	sd_taskq_create			ssd_taskq_create
1002 #define	sd_taskq_delete			ssd_taskq_delete
1003 #define	sd_target_change_task		ssd_target_change_task
1004 #define	sd_log_dev_status_event		ssd_log_dev_status_event
1005 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
1006 #define	sd_log_eject_request_event	ssd_log_eject_request_event
1007 #define	sd_media_change_task		ssd_media_change_task
1008 #define	sd_handle_mchange		ssd_handle_mchange
1009 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
1010 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
1011 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
1012 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
1013 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
1014 					sd_send_scsi_feature_GET_CONFIGURATION
1015 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
1016 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
1017 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
1018 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
1019 					ssd_send_scsi_PERSISTENT_RESERVE_IN
1020 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
1021 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
1022 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
1023 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
1024 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1025 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1026 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1027 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1028 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1029 #define	sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION	\
1030 				ssd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
1031 #define	sd_gesn_media_data_valid	ssd_gesn_media_data_valid
1032 #define	sd_alloc_rqs			ssd_alloc_rqs
1033 #define	sd_free_rqs			ssd_free_rqs
1034 #define	sd_dump_memory			ssd_dump_memory
1035 #define	sd_get_media_info_com		ssd_get_media_info_com
1036 #define	sd_get_media_info		ssd_get_media_info
1037 #define	sd_get_media_info_ext		ssd_get_media_info_ext
1038 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1039 #define	sd_nvpair_str_decode		ssd_nvpair_str_decode
1040 #define	sd_set_properties		ssd_set_properties
1041 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1042 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1043 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1044 #define	sd_check_mhd			ssd_check_mhd
1045 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1046 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1047 #define	sd_sname			ssd_sname
1048 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1049 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1050 #define	sd_take_ownership		ssd_take_ownership
1051 #define	sd_reserve_release		ssd_reserve_release
1052 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1053 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1054 #define	sd_persistent_reservation_in_read_keys	\
1055 					ssd_persistent_reservation_in_read_keys
1056 #define	sd_persistent_reservation_in_read_resv	\
1057 					ssd_persistent_reservation_in_read_resv
1058 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1059 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1060 #define	sd_mhdioc_release		ssd_mhdioc_release
1061 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1062 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1063 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1064 #define	sr_change_blkmode		ssr_change_blkmode
1065 #define	sr_change_speed			ssr_change_speed
1066 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1067 #define	sr_pause_resume			ssr_pause_resume
1068 #define	sr_play_msf			ssr_play_msf
1069 #define	sr_play_trkind			ssr_play_trkind
1070 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1071 #define	sr_read_subchannel		ssr_read_subchannel
1072 #define	sr_read_tocentry		ssr_read_tocentry
1073 #define	sr_read_tochdr			ssr_read_tochdr
1074 #define	sr_read_cdda			ssr_read_cdda
1075 #define	sr_read_cdxa			ssr_read_cdxa
1076 #define	sr_read_mode1			ssr_read_mode1
1077 #define	sr_read_mode2			ssr_read_mode2
1078 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1079 #define	sr_sector_mode			ssr_sector_mode
1080 #define	sr_eject			ssr_eject
1081 #define	sr_ejected			ssr_ejected
1082 #define	sr_check_wp			ssr_check_wp
1083 #define	sd_watch_request_submit		ssd_watch_request_submit
1084 #define	sd_check_media			ssd_check_media
1085 #define	sd_media_watch_cb		ssd_media_watch_cb
1086 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1087 #define	sr_volume_ctrl			ssr_volume_ctrl
1088 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1089 #define	sd_log_page_supported		ssd_log_page_supported
1090 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1091 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1092 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1093 #define	sd_range_lock			ssd_range_lock
1094 #define	sd_get_range			ssd_get_range
1095 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1096 #define	sd_range_unlock			ssd_range_unlock
1097 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1098 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1099 
1100 #define	sd_iostart_chain		ssd_iostart_chain
1101 #define	sd_iodone_chain			ssd_iodone_chain
1102 #define	sd_initpkt_map			ssd_initpkt_map
1103 #define	sd_destroypkt_map		ssd_destroypkt_map
1104 #define	sd_chain_type_map		ssd_chain_type_map
1105 #define	sd_chain_index_map		ssd_chain_index_map
1106 
1107 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1108 #define	sd_failfast_flushq		ssd_failfast_flushq
1109 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1110 
1111 #define	sd_is_lsi			ssd_is_lsi
1112 #define	sd_tg_rdwr			ssd_tg_rdwr
1113 #define	sd_tg_getinfo			ssd_tg_getinfo
1114 #define	sd_rmw_msg_print_handler	ssd_rmw_msg_print_handler
1115 
1116 #endif	/* #if (defined(__fibre)) */
1117 
1118 typedef struct unmap_param_hdr_s {
1119 	uint16_t	uph_data_len;
1120 	uint16_t	uph_descr_data_len;
1121 	uint32_t	uph_reserved;
1122 } unmap_param_hdr_t;
1123 
1124 typedef struct unmap_blk_descr_s {
1125 	uint64_t	ubd_lba;
1126 	uint32_t	ubd_lba_cnt;
1127 	uint32_t	ubd_reserved;
1128 } unmap_blk_descr_t;
1129 
1130 /* Max number of block descriptors in UNMAP command */
1131 #define	SD_UNMAP_MAX_DESCR \
1132 	((UINT16_MAX - sizeof (unmap_param_hdr_t)) / sizeof (unmap_blk_descr_t))
1133 /* Max size of the UNMAP parameter list in bytes */
1134 #define	SD_UNMAP_PARAM_LIST_MAXSZ	(sizeof (unmap_param_hdr_t) + \
1135 	SD_UNMAP_MAX_DESCR * sizeof (unmap_blk_descr_t))
1136 
1137 int _init(void);
1138 int _fini(void);
1139 int _info(struct modinfo *modinfop);
1140 
1141 /*PRINTFLIKE3*/
1142 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1143 /*PRINTFLIKE3*/
1144 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1145 /*PRINTFLIKE3*/
1146 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1147 
1148 static int sdprobe(dev_info_t *devi);
1149 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1150     void **result);
1151 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1152     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1153 
1154 /*
1155  * Smart probe for parallel scsi
1156  */
1157 static void sd_scsi_probe_cache_init(void);
1158 static void sd_scsi_probe_cache_fini(void);
1159 static void sd_scsi_clear_probe_cache(void);
1160 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1161 
1162 /*
1163  * Attached luns on target for parallel scsi
1164  */
1165 static void sd_scsi_target_lun_init(void);
1166 static void sd_scsi_target_lun_fini(void);
1167 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1168 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1169 
1170 static int sd_spin_up_unit(sd_ssc_t *ssc);
1171 
1172 /*
1173  * Using sd_ssc_init to establish sd_ssc_t struct
1174  * Using sd_ssc_send to send uscsi internal command
1175  * Using sd_ssc_fini to free sd_ssc_t struct
1176  */
1177 static sd_ssc_t *sd_ssc_init(struct sd_lun *un);
1178 static int sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd,
1179     int flag, enum uio_seg dataspace, int path_flag);
1180 static void sd_ssc_fini(sd_ssc_t *ssc);
1181 
1182 /*
1183  * Using sd_ssc_assessment to set correct type-of-assessment
1184  * Using sd_ssc_post to post ereport & system log
1185  *       sd_ssc_post will call sd_ssc_print to print system log
1186  *       sd_ssc_post will call sd_ssd_ereport_post to post ereport
1187  */
1188 static void sd_ssc_assessment(sd_ssc_t *ssc,
1189     enum sd_type_assessment tp_assess);
1190 
1191 static void sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess);
1192 static void sd_ssc_print(sd_ssc_t *ssc, int sd_severity);
1193 static void sd_ssc_ereport_post(sd_ssc_t *ssc,
1194     enum sd_driver_assessment drv_assess);
1195 
1196 /*
1197  * Using sd_ssc_set_info to mark an un-decodable-data error.
1198  * Using sd_ssc_extract_info to transfer information from internal
1199  *       data structures to sd_ssc_t.
1200  */
1201 static void sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp,
1202     const char *fmt, ...);
1203 static void sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un,
1204     struct scsi_pkt *pktp, struct buf *bp, struct sd_xbuf *xp);
1205 
1206 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1207     enum uio_seg dataspace, int path_flag);
1208 
1209 #ifdef _LP64
1210 static void	sd_enable_descr_sense(sd_ssc_t *ssc);
1211 static void	sd_reenable_dsense_task(void *arg);
1212 #endif /* _LP64 */
1213 
1214 static void	sd_set_mmc_caps(sd_ssc_t *ssc);
1215 
1216 static void sd_read_unit_properties(struct sd_lun *un);
1217 static int  sd_process_sdconf_file(struct sd_lun *un);
1218 static void sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str);
1219 static void sd_set_properties(struct sd_lun *un, char *name, char *value);
1220 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1221     int *data_list, sd_tunables *values);
1222 static void sd_process_sdconf_table(struct sd_lun *un);
1223 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1224 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1225 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1226     int list_len, char *dataname_ptr);
1227 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1228     sd_tunables *prop_list);
1229 
1230 static void sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi,
1231     int reservation_flag);
1232 static int  sd_get_devid(sd_ssc_t *ssc);
1233 static ddi_devid_t sd_create_devid(sd_ssc_t *ssc);
1234 static int  sd_write_deviceid(sd_ssc_t *ssc);
1235 static int  sd_check_vpd_page_support(sd_ssc_t *ssc);
1236 
1237 static void sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi);
1238 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1239 
1240 static int  sd_ddi_suspend(dev_info_t *devi);
1241 static int  sd_ddi_resume(dev_info_t *devi);
1242 static int  sd_pm_state_change(struct sd_lun *un, int level, int flag);
1243 static int  sdpower(dev_info_t *devi, int component, int level);
1244 
1245 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1246 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1247 static int  sd_unit_attach(dev_info_t *devi);
1248 static int  sd_unit_detach(dev_info_t *devi);
1249 
1250 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1251 static void sd_create_errstats(struct sd_lun *un, int instance);
1252 static void sd_set_errstats(struct sd_lun *un);
1253 static void sd_set_pstats(struct sd_lun *un);
1254 
1255 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1256 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1257 static int  sd_send_polled_RQS(struct sd_lun *un);
1258 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1259 
1260 #if (defined(__fibre))
1261 /*
1262  * Event callbacks (photon)
1263  */
1264 static void sd_init_event_callbacks(struct sd_lun *un);
1265 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1266 #endif
1267 
1268 /*
1269  * Defines for sd_cache_control
1270  */
1271 
1272 #define	SD_CACHE_ENABLE		1
1273 #define	SD_CACHE_DISABLE	0
1274 #define	SD_CACHE_NOCHANGE	-1
1275 
1276 static int   sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag);
1277 static int   sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled);
1278 static void  sd_get_write_cache_changeable(sd_ssc_t *ssc, int *is_changeable);
1279 static void  sd_get_nv_sup(sd_ssc_t *ssc);
1280 static dev_t sd_make_device(dev_info_t *devi);
1281 static void  sd_check_bdc_vpd(sd_ssc_t *ssc);
1282 static void  sd_check_emulation_mode(sd_ssc_t *ssc);
1283 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1284     uint64_t capacity);
1285 
1286 /*
1287  * Driver entry point functions.
1288  */
1289 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1290 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1291 static int  sd_ready_and_valid(sd_ssc_t *ssc, int part);
1292 
1293 static void sdmin(struct buf *bp);
1294 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1295 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1296 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1297 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1298 
1299 static int sdstrategy(struct buf *bp);
1300 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1301 
1302 /*
1303  * Function prototypes for layering functions in the iostart chain.
1304  */
1305 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1306     struct buf *bp);
1307 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1308     struct buf *bp);
1309 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1310 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1311     struct buf *bp);
1312 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1313 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1314 
1315 /*
1316  * Function prototypes for layering functions in the iodone chain.
1317  */
1318 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1319 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1320 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1321     struct buf *bp);
1322 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1323     struct buf *bp);
1324 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1325 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1326     struct buf *bp);
1327 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1328 
1329 /*
1330  * Prototypes for functions to support buf(9S) based IO.
1331  */
1332 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1333 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1334 static void sd_destroypkt_for_buf(struct buf *);
1335 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1336     struct buf *bp, int flags,
1337     int (*callback)(caddr_t), caddr_t callback_arg,
1338     diskaddr_t lba, uint32_t blockcount);
1339 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1340     struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1341 
1342 /*
1343  * Prototypes for functions to support USCSI IO.
1344  */
1345 static int sd_uscsi_strategy(struct buf *bp);
1346 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1347 static void sd_destroypkt_for_uscsi(struct buf *);
1348 
1349 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1350     uchar_t chain_type, void *pktinfop);
1351 
1352 static int  sd_pm_entry(struct sd_lun *un);
1353 static void sd_pm_exit(struct sd_lun *un);
1354 
1355 static void sd_pm_idletimeout_handler(void *arg);
1356 
1357 /*
1358  * sd_core internal functions (used at the sd_core_io layer).
1359  */
1360 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1361 static void sdintr(struct scsi_pkt *pktp);
1362 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1363 
1364 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1365     enum uio_seg dataspace, int path_flag);
1366 
1367 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1368     daddr_t blkno, int (*func)(struct buf *));
1369 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1370     uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1371 static void sd_bioclone_free(struct buf *bp);
1372 static void sd_shadow_buf_free(struct buf *bp);
1373 
1374 static void sd_print_transport_rejected_message(struct sd_lun *un,
1375     struct sd_xbuf *xp, int code);
1376 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1377     void *arg, int code);
1378 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1379     void *arg, int code);
1380 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1381     void *arg, int code);
1382 
1383 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1384     int retry_check_flag,
1385     void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int c),
1386     void *user_arg, int failure_code,  clock_t retry_delay,
1387     void (*statp)(kstat_io_t *));
1388 
1389 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1390     clock_t retry_delay, void (*statp)(kstat_io_t *));
1391 
1392 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1393     struct scsi_pkt *pktp);
1394 static void sd_start_retry_command(void *arg);
1395 static void sd_start_direct_priority_command(void *arg);
1396 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1397     int errcode);
1398 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1399     struct buf *bp, int errcode);
1400 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1401 static void sd_sync_with_callback(struct sd_lun *un);
1402 static int sdrunout(caddr_t arg);
1403 
1404 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1405 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1406 
1407 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1408 static void sd_restore_throttle(void *arg);
1409 
1410 static void sd_init_cdb_limits(struct sd_lun *un);
1411 
1412 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1413     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1414 
1415 /*
1416  * Error handling functions
1417  */
1418 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1419     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1420 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1421     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1422 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1423     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1424 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1425     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1426 
1427 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1428     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1429 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1430     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1431 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1432     struct sd_xbuf *xp, size_t actual_len);
1433 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1434     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1435 
1436 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1437     void *arg, int code);
1438 
1439 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1440     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1441 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1442     uint8_t *sense_datap,
1443     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1444 static void sd_sense_key_not_ready(struct sd_lun *un,
1445     uint8_t *sense_datap,
1446     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1447 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1448     uint8_t *sense_datap,
1449     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1450 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1451     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1452 static void sd_sense_key_unit_attention(struct sd_lun *un,
1453     uint8_t *sense_datap,
1454     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1455 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1456     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1457 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1458     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1459 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1460     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1461 static void sd_sense_key_default(struct sd_lun *un,
1462     uint8_t *sense_datap,
1463     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1464 
1465 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1466     void *arg, int flag);
1467 
1468 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1469     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1470 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1471     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1472 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1473     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1474 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1475     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1476 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1477     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1478 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1479     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1480 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1481     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1482 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1483     struct sd_xbuf *xp, struct scsi_pkt *pktp);
1484 
1485 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1486 
1487 static void sd_start_stop_unit_callback(void *arg);
1488 static void sd_start_stop_unit_task(void *arg);
1489 
1490 static void sd_taskq_create(void);
1491 static void sd_taskq_delete(void);
1492 static void sd_target_change_task(void *arg);
1493 static void sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag);
1494 static void sd_log_lun_expansion_event(struct sd_lun *un, int km_flag);
1495 static void sd_log_eject_request_event(struct sd_lun *un, int km_flag);
1496 static void sd_media_change_task(void *arg);
1497 
1498 static int sd_handle_mchange(struct sd_lun *un);
1499 static int sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag);
1500 static int sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp,
1501     uint32_t *lbap, int path_flag);
1502 static int sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp,
1503     uint32_t *lbap, uint32_t *psp, int path_flag);
1504 static int sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag,
1505     int flag, int path_flag);
1506 static int sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr,
1507     size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1508 static int sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag);
1509 static int sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc,
1510     uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1511 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc,
1512     uchar_t usr_cmd, uchar_t *usr_bufp);
1513 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1514     struct dk_callback *dkc);
1515 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1516 static int sd_send_scsi_UNMAP(dev_t dev, sd_ssc_t *ssc, dkioc_free_list_t *dfl,
1517     int flag);
1518 static int sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc,
1519     struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1520     uchar_t *bufaddr, uint_t buflen, int path_flag);
1521 static int sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc,
1522     struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1523     uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1524 static int sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize,
1525     uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1526 static int sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize,
1527     uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1528 static int sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
1529     size_t buflen, daddr_t start_block, int path_flag);
1530 #define	sd_send_scsi_READ(ssc, bufaddr, buflen, start_block, path_flag)	\
1531     sd_send_scsi_RDWR(ssc, SCMD_READ, bufaddr, buflen, start_block, \
1532     path_flag)
1533 #define	sd_send_scsi_WRITE(ssc, bufaddr, buflen, start_block, path_flag)\
1534     sd_send_scsi_RDWR(ssc, SCMD_WRITE, bufaddr, buflen, start_block,\
1535     path_flag)
1536 
1537 static int sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr,
1538     uint16_t buflen, uchar_t page_code, uchar_t page_control,
1539     uint16_t param_ptr, int path_flag);
1540 static int sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc,
1541     uchar_t *bufaddr, size_t buflen, uchar_t class_req);
1542 static boolean_t sd_gesn_media_data_valid(uchar_t *data);
1543 
1544 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1545 static void sd_free_rqs(struct sd_lun *un);
1546 
1547 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1548     uchar_t *data, int len, int fmt);
1549 static void sd_panic_for_res_conflict(struct sd_lun *un);
1550 
1551 /*
1552  * Disk Ioctl Function Prototypes
1553  */
1554 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1555 static int sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag);
1556 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1557 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1558 
1559 /*
1560  * Multi-host Ioctl Prototypes
1561  */
1562 static int sd_check_mhd(dev_t dev, int interval);
1563 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1564 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1565 static char *sd_sname(uchar_t status);
1566 static void sd_mhd_resvd_recover(void *arg);
1567 static void sd_resv_reclaim_thread();
1568 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1569 static int sd_reserve_release(dev_t dev, int cmd);
1570 static void sd_rmv_resv_reclaim_req(dev_t dev);
1571 static void sd_mhd_reset_notify_cb(caddr_t arg);
1572 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1573     mhioc_inkeys_t *usrp, int flag);
1574 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1575     mhioc_inresvs_t *usrp, int flag);
1576 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1577 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1578 static int sd_mhdioc_release(dev_t dev);
1579 static int sd_mhdioc_register_devid(dev_t dev);
1580 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1581 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1582 
1583 /*
1584  * SCSI removable prototypes
1585  */
1586 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1587 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1588 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1589 static int sr_pause_resume(dev_t dev, int mode);
1590 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1591 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1592 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1593 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1594 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1595 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1596 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1597 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1598 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1599 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1600 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1601 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1602 static int sr_eject(dev_t dev);
1603 static void sr_ejected(register struct sd_lun *un);
1604 static int sr_check_wp(dev_t dev);
1605 static opaque_t sd_watch_request_submit(struct sd_lun *un);
1606 static int sd_check_media(dev_t dev, enum dkio_state state);
1607 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1608 static void sd_delayed_cv_broadcast(void *arg);
1609 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1610 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1611 
1612 static int sd_log_page_supported(sd_ssc_t *ssc, int log_page);
1613 
1614 /*
1615  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1616  */
1617 static void sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag);
1618 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1619 static void sd_wm_cache_destructor(void *wm, void *un);
1620 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1621     daddr_t endb, ushort_t typ);
1622 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1623     daddr_t endb);
1624 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1625 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1626 static void sd_read_modify_write_task(void * arg);
1627 static int
1628 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1629     struct buf **bpp);
1630 
1631 
1632 /*
1633  * Function prototypes for failfast support.
1634  */
1635 static void sd_failfast_flushq(struct sd_lun *un);
1636 static int sd_failfast_flushq_callback(struct buf *bp);
1637 
1638 /*
1639  * Function prototypes to check for lsi devices
1640  */
1641 static void sd_is_lsi(struct sd_lun *un);
1642 
1643 /*
1644  * Function prototypes for partial DMA support
1645  */
1646 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1647 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1648 
1649 
1650 /* Function prototypes for cmlb */
1651 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1652     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1653 
1654 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1655 
1656 /*
1657  * For printing RMW warning message timely
1658  */
1659 static void sd_rmw_msg_print_handler(void *arg);
1660 
1661 /*
1662  * Constants for failfast support:
1663  *
1664  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1665  * failfast processing being performed.
1666  *
1667  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1668  * failfast processing on all bufs with B_FAILFAST set.
1669  */
1670 
1671 #define	SD_FAILFAST_INACTIVE		0
1672 #define	SD_FAILFAST_ACTIVE		1
1673 
1674 /*
1675  * Bitmask to control behavior of buf(9S) flushes when a transition to
1676  * the failfast state occurs. Optional bits include:
1677  *
1678  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1679  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1680  * be flushed.
1681  *
1682  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1683  * driver, in addition to the regular wait queue. This includes the xbuf
1684  * queues. When clear, only the driver's wait queue will be flushed.
1685  */
1686 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1687 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1688 
1689 /*
1690  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1691  * to flush all queues within the driver.
1692  */
1693 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1694 
1695 
1696 /*
1697  * SD Testing Fault Injection
1698  */
1699 #ifdef SD_FAULT_INJECTION
1700 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1701 static void sd_faultinjection(struct scsi_pkt *pktp);
1702 static void sd_injection_log(char *buf, struct sd_lun *un);
1703 #endif
1704 
1705 /*
1706  * Device driver ops vector
1707  */
1708 static struct cb_ops sd_cb_ops = {
1709 	sdopen,			/* open */
1710 	sdclose,		/* close */
1711 	sdstrategy,		/* strategy */
1712 	nodev,			/* print */
1713 	sddump,			/* dump */
1714 	sdread,			/* read */
1715 	sdwrite,		/* write */
1716 	sdioctl,		/* ioctl */
1717 	nodev,			/* devmap */
1718 	nodev,			/* mmap */
1719 	nodev,			/* segmap */
1720 	nochpoll,		/* poll */
1721 	sd_prop_op,		/* cb_prop_op */
1722 	0,			/* streamtab  */
1723 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1724 	CB_REV,			/* cb_rev */
1725 	sdaread,		/* async I/O read entry point */
1726 	sdawrite		/* async I/O write entry point */
1727 };
1728 
1729 struct dev_ops sd_ops = {
1730 	DEVO_REV,		/* devo_rev, */
1731 	0,			/* refcnt  */
1732 	sdinfo,			/* info */
1733 	nulldev,		/* identify */
1734 	sdprobe,		/* probe */
1735 	sdattach,		/* attach */
1736 	sddetach,		/* detach */
1737 	nodev,			/* reset */
1738 	&sd_cb_ops,		/* driver operations */
1739 	NULL,			/* bus operations */
1740 	sdpower,		/* power */
1741 	ddi_quiesce_not_needed,		/* quiesce */
1742 };
1743 
1744 /*
1745  * This is the loadable module wrapper.
1746  */
1747 #include <sys/modctl.h>
1748 
1749 static struct modldrv modldrv = {
1750 	&mod_driverops,		/* Type of module. This one is a driver */
1751 	SD_MODULE_NAME,		/* Module name. */
1752 	&sd_ops			/* driver ops */
1753 };
1754 
1755 static struct modlinkage modlinkage = {
1756 	MODREV_1, &modldrv, NULL
1757 };
1758 
1759 static cmlb_tg_ops_t sd_tgops = {
1760 	TG_DK_OPS_VERSION_1,
1761 	sd_tg_rdwr,
1762 	sd_tg_getinfo
1763 };
1764 
1765 static struct scsi_asq_key_strings sd_additional_codes[] = {
1766 	0x81, 0, "Logical Unit is Reserved",
1767 	0x85, 0, "Audio Address Not Valid",
1768 	0xb6, 0, "Media Load Mechanism Failed",
1769 	0xB9, 0, "Audio Play Operation Aborted",
1770 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1771 	0x53, 2, "Medium removal prevented",
1772 	0x6f, 0, "Authentication failed during key exchange",
1773 	0x6f, 1, "Key not present",
1774 	0x6f, 2, "Key not established",
1775 	0x6f, 3, "Read without proper authentication",
1776 	0x6f, 4, "Mismatched region to this logical unit",
1777 	0x6f, 5, "Region reset count error",
1778 	0xffff, 0x0, NULL
1779 };
1780 
1781 
1782 /*
1783  * Struct for passing printing information for sense data messages
1784  */
1785 struct sd_sense_info {
1786 	int	ssi_severity;
1787 	int	ssi_pfa_flag;
1788 };
1789 
1790 /*
1791  * Table of function pointers for iostart-side routines. Separate "chains"
1792  * of layered function calls are formed by placing the function pointers
1793  * sequentially in the desired order. Functions are called according to an
1794  * incrementing table index ordering. The last function in each chain must
1795  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1796  * in the sd_iodone_chain[] array.
1797  *
1798  * Note: It may seem more natural to organize both the iostart and iodone
1799  * functions together, into an array of structures (or some similar
1800  * organization) with a common index, rather than two separate arrays which
1801  * must be maintained in synchronization. The purpose of this division is
1802  * to achieve improved performance: individual arrays allows for more
1803  * effective cache line utilization on certain platforms.
1804  */
1805 
1806 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1807 
1808 
1809 static sd_chain_t sd_iostart_chain[] = {
1810 
1811 	/* Chain for buf IO for disk drive targets (PM enabled) */
1812 	sd_mapblockaddr_iostart,	/* Index: 0 */
1813 	sd_pm_iostart,			/* Index: 1 */
1814 	sd_core_iostart,		/* Index: 2 */
1815 
1816 	/* Chain for buf IO for disk drive targets (PM disabled) */
1817 	sd_mapblockaddr_iostart,	/* Index: 3 */
1818 	sd_core_iostart,		/* Index: 4 */
1819 
1820 	/*
1821 	 * Chain for buf IO for removable-media or large sector size
1822 	 * disk drive targets with RMW needed (PM enabled)
1823 	 */
1824 	sd_mapblockaddr_iostart,	/* Index: 5 */
1825 	sd_mapblocksize_iostart,	/* Index: 6 */
1826 	sd_pm_iostart,			/* Index: 7 */
1827 	sd_core_iostart,		/* Index: 8 */
1828 
1829 	/*
1830 	 * Chain for buf IO for removable-media or large sector size
1831 	 * disk drive targets with RMW needed (PM disabled)
1832 	 */
1833 	sd_mapblockaddr_iostart,	/* Index: 9 */
1834 	sd_mapblocksize_iostart,	/* Index: 10 */
1835 	sd_core_iostart,		/* Index: 11 */
1836 
1837 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1838 	sd_mapblockaddr_iostart,	/* Index: 12 */
1839 	sd_checksum_iostart,		/* Index: 13 */
1840 	sd_pm_iostart,			/* Index: 14 */
1841 	sd_core_iostart,		/* Index: 15 */
1842 
1843 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1844 	sd_mapblockaddr_iostart,	/* Index: 16 */
1845 	sd_checksum_iostart,		/* Index: 17 */
1846 	sd_core_iostart,		/* Index: 18 */
1847 
1848 	/* Chain for USCSI commands (all targets) */
1849 	sd_pm_iostart,			/* Index: 19 */
1850 	sd_core_iostart,		/* Index: 20 */
1851 
1852 	/* Chain for checksumming USCSI commands (all targets) */
1853 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1854 	sd_pm_iostart,			/* Index: 22 */
1855 	sd_core_iostart,		/* Index: 23 */
1856 
1857 	/* Chain for "direct" USCSI commands (all targets) */
1858 	sd_core_iostart,		/* Index: 24 */
1859 
1860 	/* Chain for "direct priority" USCSI commands (all targets) */
1861 	sd_core_iostart,		/* Index: 25 */
1862 
1863 	/*
1864 	 * Chain for buf IO for large sector size disk drive targets
1865 	 * with RMW needed with checksumming (PM enabled)
1866 	 */
1867 	sd_mapblockaddr_iostart,	/* Index: 26 */
1868 	sd_mapblocksize_iostart,	/* Index: 27 */
1869 	sd_checksum_iostart,		/* Index: 28 */
1870 	sd_pm_iostart,			/* Index: 29 */
1871 	sd_core_iostart,		/* Index: 30 */
1872 
1873 	/*
1874 	 * Chain for buf IO for large sector size disk drive targets
1875 	 * with RMW needed with checksumming (PM disabled)
1876 	 */
1877 	sd_mapblockaddr_iostart,	/* Index: 31 */
1878 	sd_mapblocksize_iostart,	/* Index: 32 */
1879 	sd_checksum_iostart,		/* Index: 33 */
1880 	sd_core_iostart,		/* Index: 34 */
1881 
1882 };
1883 
1884 /*
1885  * Macros to locate the first function of each iostart chain in the
1886  * sd_iostart_chain[] array. These are located by the index in the array.
1887  */
1888 #define	SD_CHAIN_DISK_IOSTART			0
1889 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1890 #define	SD_CHAIN_MSS_DISK_IOSTART		5
1891 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1892 #define	SD_CHAIN_MSS_DISK_IOSTART_NO_PM		9
1893 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1894 #define	SD_CHAIN_CHKSUM_IOSTART			12
1895 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1896 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1897 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1898 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1899 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1900 #define	SD_CHAIN_MSS_CHKSUM_IOSTART		26
1901 #define	SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM	31
1902 
1903 
1904 /*
1905  * Table of function pointers for the iodone-side routines for the driver-
1906  * internal layering mechanism.  The calling sequence for iodone routines
1907  * uses a decrementing table index, so the last routine called in a chain
1908  * must be at the lowest array index location for that chain.  The last
1909  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1910  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1911  * of the functions in an iodone side chain must correspond to the ordering
1912  * of the iostart routines for that chain.  Note that there is no iodone
1913  * side routine that corresponds to sd_core_iostart(), so there is no
1914  * entry in the table for this.
1915  */
1916 
1917 static sd_chain_t sd_iodone_chain[] = {
1918 
1919 	/* Chain for buf IO for disk drive targets (PM enabled) */
1920 	sd_buf_iodone,			/* Index: 0 */
1921 	sd_mapblockaddr_iodone,		/* Index: 1 */
1922 	sd_pm_iodone,			/* Index: 2 */
1923 
1924 	/* Chain for buf IO for disk drive targets (PM disabled) */
1925 	sd_buf_iodone,			/* Index: 3 */
1926 	sd_mapblockaddr_iodone,		/* Index: 4 */
1927 
1928 	/*
1929 	 * Chain for buf IO for removable-media or large sector size
1930 	 * disk drive targets with RMW needed (PM enabled)
1931 	 */
1932 	sd_buf_iodone,			/* Index: 5 */
1933 	sd_mapblockaddr_iodone,		/* Index: 6 */
1934 	sd_mapblocksize_iodone,		/* Index: 7 */
1935 	sd_pm_iodone,			/* Index: 8 */
1936 
1937 	/*
1938 	 * Chain for buf IO for removable-media or large sector size
1939 	 * disk drive targets with RMW needed (PM disabled)
1940 	 */
1941 	sd_buf_iodone,			/* Index: 9 */
1942 	sd_mapblockaddr_iodone,		/* Index: 10 */
1943 	sd_mapblocksize_iodone,		/* Index: 11 */
1944 
1945 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1946 	sd_buf_iodone,			/* Index: 12 */
1947 	sd_mapblockaddr_iodone,		/* Index: 13 */
1948 	sd_checksum_iodone,		/* Index: 14 */
1949 	sd_pm_iodone,			/* Index: 15 */
1950 
1951 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1952 	sd_buf_iodone,			/* Index: 16 */
1953 	sd_mapblockaddr_iodone,		/* Index: 17 */
1954 	sd_checksum_iodone,		/* Index: 18 */
1955 
1956 	/* Chain for USCSI commands (non-checksum targets) */
1957 	sd_uscsi_iodone,		/* Index: 19 */
1958 	sd_pm_iodone,			/* Index: 20 */
1959 
1960 	/* Chain for USCSI commands (checksum targets) */
1961 	sd_uscsi_iodone,		/* Index: 21 */
1962 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1963 	sd_pm_iodone,			/* Index: 22 */
1964 
1965 	/* Chain for "direct" USCSI commands (all targets) */
1966 	sd_uscsi_iodone,		/* Index: 24 */
1967 
1968 	/* Chain for "direct priority" USCSI commands (all targets) */
1969 	sd_uscsi_iodone,		/* Index: 25 */
1970 
1971 	/*
1972 	 * Chain for buf IO for large sector size disk drive targets
1973 	 * with checksumming (PM enabled)
1974 	 */
1975 	sd_buf_iodone,			/* Index: 26 */
1976 	sd_mapblockaddr_iodone,		/* Index: 27 */
1977 	sd_mapblocksize_iodone,		/* Index: 28 */
1978 	sd_checksum_iodone,		/* Index: 29 */
1979 	sd_pm_iodone,			/* Index: 30 */
1980 
1981 	/*
1982 	 * Chain for buf IO for large sector size disk drive targets
1983 	 * with checksumming (PM disabled)
1984 	 */
1985 	sd_buf_iodone,			/* Index: 31 */
1986 	sd_mapblockaddr_iodone,		/* Index: 32 */
1987 	sd_mapblocksize_iodone,		/* Index: 33 */
1988 	sd_checksum_iodone,		/* Index: 34 */
1989 };
1990 
1991 
1992 /*
1993  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1994  * each iodone-side chain. These are located by the array index, but as the
1995  * iodone side functions are called in a decrementing-index order, the
1996  * highest index number in each chain must be specified (as these correspond
1997  * to the first function in the iodone chain that will be called by the core
1998  * at IO completion time).
1999  */
2000 
2001 #define	SD_CHAIN_DISK_IODONE			2
2002 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
2003 #define	SD_CHAIN_RMMEDIA_IODONE			8
2004 #define	SD_CHAIN_MSS_DISK_IODONE		8
2005 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
2006 #define	SD_CHAIN_MSS_DISK_IODONE_NO_PM		11
2007 #define	SD_CHAIN_CHKSUM_IODONE			15
2008 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
2009 #define	SD_CHAIN_USCSI_CMD_IODONE		20
2010 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
2011 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
2012 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
2013 #define	SD_CHAIN_MSS_CHKSUM_IODONE		30
2014 #define	SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM	34
2015 
2016 
2017 
2018 /*
2019  * Array to map a layering chain index to the appropriate initpkt routine.
2020  * The redundant entries are present so that the index used for accessing
2021  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2022  * with this table as well.
2023  */
2024 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
2025 
2026 static sd_initpkt_t	sd_initpkt_map[] = {
2027 
2028 	/* Chain for buf IO for disk drive targets (PM enabled) */
2029 	sd_initpkt_for_buf,		/* Index: 0 */
2030 	sd_initpkt_for_buf,		/* Index: 1 */
2031 	sd_initpkt_for_buf,		/* Index: 2 */
2032 
2033 	/* Chain for buf IO for disk drive targets (PM disabled) */
2034 	sd_initpkt_for_buf,		/* Index: 3 */
2035 	sd_initpkt_for_buf,		/* Index: 4 */
2036 
2037 	/*
2038 	 * Chain for buf IO for removable-media or large sector size
2039 	 * disk drive targets (PM enabled)
2040 	 */
2041 	sd_initpkt_for_buf,		/* Index: 5 */
2042 	sd_initpkt_for_buf,		/* Index: 6 */
2043 	sd_initpkt_for_buf,		/* Index: 7 */
2044 	sd_initpkt_for_buf,		/* Index: 8 */
2045 
2046 	/*
2047 	 * Chain for buf IO for removable-media or large sector size
2048 	 * disk drive targets (PM disabled)
2049 	 */
2050 	sd_initpkt_for_buf,		/* Index: 9 */
2051 	sd_initpkt_for_buf,		/* Index: 10 */
2052 	sd_initpkt_for_buf,		/* Index: 11 */
2053 
2054 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2055 	sd_initpkt_for_buf,		/* Index: 12 */
2056 	sd_initpkt_for_buf,		/* Index: 13 */
2057 	sd_initpkt_for_buf,		/* Index: 14 */
2058 	sd_initpkt_for_buf,		/* Index: 15 */
2059 
2060 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2061 	sd_initpkt_for_buf,		/* Index: 16 */
2062 	sd_initpkt_for_buf,		/* Index: 17 */
2063 	sd_initpkt_for_buf,		/* Index: 18 */
2064 
2065 	/* Chain for USCSI commands (non-checksum targets) */
2066 	sd_initpkt_for_uscsi,		/* Index: 19 */
2067 	sd_initpkt_for_uscsi,		/* Index: 20 */
2068 
2069 	/* Chain for USCSI commands (checksum targets) */
2070 	sd_initpkt_for_uscsi,		/* Index: 21 */
2071 	sd_initpkt_for_uscsi,		/* Index: 22 */
2072 	sd_initpkt_for_uscsi,		/* Index: 22 */
2073 
2074 	/* Chain for "direct" USCSI commands (all targets) */
2075 	sd_initpkt_for_uscsi,		/* Index: 24 */
2076 
2077 	/* Chain for "direct priority" USCSI commands (all targets) */
2078 	sd_initpkt_for_uscsi,		/* Index: 25 */
2079 
2080 	/*
2081 	 * Chain for buf IO for large sector size disk drive targets
2082 	 * with checksumming (PM enabled)
2083 	 */
2084 	sd_initpkt_for_buf,		/* Index: 26 */
2085 	sd_initpkt_for_buf,		/* Index: 27 */
2086 	sd_initpkt_for_buf,		/* Index: 28 */
2087 	sd_initpkt_for_buf,		/* Index: 29 */
2088 	sd_initpkt_for_buf,		/* Index: 30 */
2089 
2090 	/*
2091 	 * Chain for buf IO for large sector size disk drive targets
2092 	 * with checksumming (PM disabled)
2093 	 */
2094 	sd_initpkt_for_buf,		/* Index: 31 */
2095 	sd_initpkt_for_buf,		/* Index: 32 */
2096 	sd_initpkt_for_buf,		/* Index: 33 */
2097 	sd_initpkt_for_buf,		/* Index: 34 */
2098 };
2099 
2100 
2101 /*
2102  * Array to map a layering chain index to the appropriate destroypktpkt routine.
2103  * The redundant entries are present so that the index used for accessing
2104  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2105  * with this table as well.
2106  */
2107 typedef void (*sd_destroypkt_t)(struct buf *);
2108 
2109 static sd_destroypkt_t	sd_destroypkt_map[] = {
2110 
2111 	/* Chain for buf IO for disk drive targets (PM enabled) */
2112 	sd_destroypkt_for_buf,		/* Index: 0 */
2113 	sd_destroypkt_for_buf,		/* Index: 1 */
2114 	sd_destroypkt_for_buf,		/* Index: 2 */
2115 
2116 	/* Chain for buf IO for disk drive targets (PM disabled) */
2117 	sd_destroypkt_for_buf,		/* Index: 3 */
2118 	sd_destroypkt_for_buf,		/* Index: 4 */
2119 
2120 	/*
2121 	 * Chain for buf IO for removable-media or large sector size
2122 	 * disk drive targets (PM enabled)
2123 	 */
2124 	sd_destroypkt_for_buf,		/* Index: 5 */
2125 	sd_destroypkt_for_buf,		/* Index: 6 */
2126 	sd_destroypkt_for_buf,		/* Index: 7 */
2127 	sd_destroypkt_for_buf,		/* Index: 8 */
2128 
2129 	/*
2130 	 * Chain for buf IO for removable-media or large sector size
2131 	 * disk drive targets (PM disabled)
2132 	 */
2133 	sd_destroypkt_for_buf,		/* Index: 9 */
2134 	sd_destroypkt_for_buf,		/* Index: 10 */
2135 	sd_destroypkt_for_buf,		/* Index: 11 */
2136 
2137 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2138 	sd_destroypkt_for_buf,		/* Index: 12 */
2139 	sd_destroypkt_for_buf,		/* Index: 13 */
2140 	sd_destroypkt_for_buf,		/* Index: 14 */
2141 	sd_destroypkt_for_buf,		/* Index: 15 */
2142 
2143 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2144 	sd_destroypkt_for_buf,		/* Index: 16 */
2145 	sd_destroypkt_for_buf,		/* Index: 17 */
2146 	sd_destroypkt_for_buf,		/* Index: 18 */
2147 
2148 	/* Chain for USCSI commands (non-checksum targets) */
2149 	sd_destroypkt_for_uscsi,	/* Index: 19 */
2150 	sd_destroypkt_for_uscsi,	/* Index: 20 */
2151 
2152 	/* Chain for USCSI commands (checksum targets) */
2153 	sd_destroypkt_for_uscsi,	/* Index: 21 */
2154 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2155 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2156 
2157 	/* Chain for "direct" USCSI commands (all targets) */
2158 	sd_destroypkt_for_uscsi,	/* Index: 24 */
2159 
2160 	/* Chain for "direct priority" USCSI commands (all targets) */
2161 	sd_destroypkt_for_uscsi,	/* Index: 25 */
2162 
2163 	/*
2164 	 * Chain for buf IO for large sector size disk drive targets
2165 	 * with checksumming (PM disabled)
2166 	 */
2167 	sd_destroypkt_for_buf,		/* Index: 26 */
2168 	sd_destroypkt_for_buf,		/* Index: 27 */
2169 	sd_destroypkt_for_buf,		/* Index: 28 */
2170 	sd_destroypkt_for_buf,		/* Index: 29 */
2171 	sd_destroypkt_for_buf,		/* Index: 30 */
2172 
2173 	/*
2174 	 * Chain for buf IO for large sector size disk drive targets
2175 	 * with checksumming (PM enabled)
2176 	 */
2177 	sd_destroypkt_for_buf,		/* Index: 31 */
2178 	sd_destroypkt_for_buf,		/* Index: 32 */
2179 	sd_destroypkt_for_buf,		/* Index: 33 */
2180 	sd_destroypkt_for_buf,		/* Index: 34 */
2181 };
2182 
2183 
2184 
2185 /*
2186  * Array to map a layering chain index to the appropriate chain "type".
2187  * The chain type indicates a specific property/usage of the chain.
2188  * The redundant entries are present so that the index used for accessing
2189  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2190  * with this table as well.
2191  */
2192 
2193 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2194 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2195 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2196 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2197 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2198 						/* (for error recovery) */
2199 
2200 static int sd_chain_type_map[] = {
2201 
2202 	/* Chain for buf IO for disk drive targets (PM enabled) */
2203 	SD_CHAIN_BUFIO,			/* Index: 0 */
2204 	SD_CHAIN_BUFIO,			/* Index: 1 */
2205 	SD_CHAIN_BUFIO,			/* Index: 2 */
2206 
2207 	/* Chain for buf IO for disk drive targets (PM disabled) */
2208 	SD_CHAIN_BUFIO,			/* Index: 3 */
2209 	SD_CHAIN_BUFIO,			/* Index: 4 */
2210 
2211 	/*
2212 	 * Chain for buf IO for removable-media or large sector size
2213 	 * disk drive targets (PM enabled)
2214 	 */
2215 	SD_CHAIN_BUFIO,			/* Index: 5 */
2216 	SD_CHAIN_BUFIO,			/* Index: 6 */
2217 	SD_CHAIN_BUFIO,			/* Index: 7 */
2218 	SD_CHAIN_BUFIO,			/* Index: 8 */
2219 
2220 	/*
2221 	 * Chain for buf IO for removable-media or large sector size
2222 	 * disk drive targets (PM disabled)
2223 	 */
2224 	SD_CHAIN_BUFIO,			/* Index: 9 */
2225 	SD_CHAIN_BUFIO,			/* Index: 10 */
2226 	SD_CHAIN_BUFIO,			/* Index: 11 */
2227 
2228 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2229 	SD_CHAIN_BUFIO,			/* Index: 12 */
2230 	SD_CHAIN_BUFIO,			/* Index: 13 */
2231 	SD_CHAIN_BUFIO,			/* Index: 14 */
2232 	SD_CHAIN_BUFIO,			/* Index: 15 */
2233 
2234 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2235 	SD_CHAIN_BUFIO,			/* Index: 16 */
2236 	SD_CHAIN_BUFIO,			/* Index: 17 */
2237 	SD_CHAIN_BUFIO,			/* Index: 18 */
2238 
2239 	/* Chain for USCSI commands (non-checksum targets) */
2240 	SD_CHAIN_USCSI,			/* Index: 19 */
2241 	SD_CHAIN_USCSI,			/* Index: 20 */
2242 
2243 	/* Chain for USCSI commands (checksum targets) */
2244 	SD_CHAIN_USCSI,			/* Index: 21 */
2245 	SD_CHAIN_USCSI,			/* Index: 22 */
2246 	SD_CHAIN_USCSI,			/* Index: 23 */
2247 
2248 	/* Chain for "direct" USCSI commands (all targets) */
2249 	SD_CHAIN_DIRECT,		/* Index: 24 */
2250 
2251 	/* Chain for "direct priority" USCSI commands (all targets) */
2252 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2253 
2254 	/*
2255 	 * Chain for buf IO for large sector size disk drive targets
2256 	 * with checksumming (PM enabled)
2257 	 */
2258 	SD_CHAIN_BUFIO,			/* Index: 26 */
2259 	SD_CHAIN_BUFIO,			/* Index: 27 */
2260 	SD_CHAIN_BUFIO,			/* Index: 28 */
2261 	SD_CHAIN_BUFIO,			/* Index: 29 */
2262 	SD_CHAIN_BUFIO,			/* Index: 30 */
2263 
2264 	/*
2265 	 * Chain for buf IO for large sector size disk drive targets
2266 	 * with checksumming (PM disabled)
2267 	 */
2268 	SD_CHAIN_BUFIO,			/* Index: 31 */
2269 	SD_CHAIN_BUFIO,			/* Index: 32 */
2270 	SD_CHAIN_BUFIO,			/* Index: 33 */
2271 	SD_CHAIN_BUFIO,			/* Index: 34 */
2272 };
2273 
2274 
2275 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2276 #define	SD_IS_BUFIO(xp)			\
2277 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2278 
2279 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2280 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2281 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2282 
2283 
2284 
2285 /*
2286  * Struct, array, and macros to map a specific chain to the appropriate
2287  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2288  *
2289  * The sd_chain_index_map[] array is used at attach time to set the various
2290  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2291  * chain to be used with the instance. This allows different instances to use
2292  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2293  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2294  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2295  * dynamically & without the use of locking; and (2) a layer may update the
2296  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2297  * to allow for deferred processing of an IO within the same chain from a
2298  * different execution context.
2299  */
2300 
2301 struct sd_chain_index {
2302 	int	sci_iostart_index;
2303 	int	sci_iodone_index;
2304 };
2305 
2306 static struct sd_chain_index	sd_chain_index_map[] = {
2307 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2308 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2309 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2310 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2311 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2312 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2313 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2314 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2315 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2316 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2317 	{ SD_CHAIN_MSS_CHKSUM_IOSTART,		SD_CHAIN_MSS_CHKSUM_IODONE },
2318 	{ SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM, SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM },
2319 
2320 };
2321 
2322 
2323 /*
2324  * The following are indexes into the sd_chain_index_map[] array.
2325  */
2326 
2327 /* un->un_buf_chain_type must be set to one of these */
2328 #define	SD_CHAIN_INFO_DISK		0
2329 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2330 #define	SD_CHAIN_INFO_RMMEDIA		2
2331 #define	SD_CHAIN_INFO_MSS_DISK		2
2332 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2333 #define	SD_CHAIN_INFO_MSS_DSK_NO_PM	3
2334 #define	SD_CHAIN_INFO_CHKSUM		4
2335 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2336 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM	10
2337 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM_NO_PM	11
2338 
2339 /* un->un_uscsi_chain_type must be set to one of these */
2340 #define	SD_CHAIN_INFO_USCSI_CMD		6
2341 /* USCSI with PM disabled is the same as DIRECT */
2342 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2343 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2344 
2345 /* un->un_direct_chain_type must be set to one of these */
2346 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2347 
2348 /* un->un_priority_chain_type must be set to one of these */
2349 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2350 
2351 /* size for devid inquiries */
2352 #define	MAX_INQUIRY_SIZE		0xF0
2353 
2354 /*
2355  * Macros used by functions to pass a given buf(9S) struct along to the
2356  * next function in the layering chain for further processing.
2357  *
2358  * In the following macros, passing more than three arguments to the called
2359  * routines causes the optimizer for the SPARC compiler to stop doing tail
2360  * call elimination which results in significant performance degradation.
2361  */
2362 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2363 	((*(sd_iostart_chain[index]))(index, un, bp))
2364 
2365 #define	SD_BEGIN_IODONE(index, un, bp)	\
2366 	((*(sd_iodone_chain[index]))(index, un, bp))
2367 
2368 #define	SD_NEXT_IOSTART(index, un, bp)				\
2369 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2370 
2371 #define	SD_NEXT_IODONE(index, un, bp)				\
2372 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2373 
2374 /*
2375  *    Function: _init
2376  *
2377  * Description: This is the driver _init(9E) entry point.
2378  *
2379  * Return Code: Returns the value from mod_install(9F) or
2380  *		ddi_soft_state_init(9F) as appropriate.
2381  *
2382  *     Context: Called when driver module loaded.
2383  */
2384 
2385 int
2386 _init(void)
2387 {
2388 	int	err;
2389 
2390 	/* establish driver name from module name */
2391 	sd_label = (char *)mod_modname(&modlinkage);
2392 
2393 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2394 	    SD_MAXUNIT);
2395 	if (err != 0) {
2396 		return (err);
2397 	}
2398 
2399 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2400 
2401 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2402 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2403 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2404 
2405 	/*
2406 	 * it's ok to init here even for fibre device
2407 	 */
2408 	sd_scsi_probe_cache_init();
2409 
2410 	sd_scsi_target_lun_init();
2411 
2412 	/*
2413 	 * Creating taskq before mod_install ensures that all callers (threads)
2414 	 * that enter the module after a successful mod_install encounter
2415 	 * a valid taskq.
2416 	 */
2417 	sd_taskq_create();
2418 
2419 	err = mod_install(&modlinkage);
2420 	if (err != 0) {
2421 		/* delete taskq if install fails */
2422 		sd_taskq_delete();
2423 
2424 		mutex_destroy(&sd_log_mutex);
2425 
2426 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2427 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2428 		cv_destroy(&sd_tr.srq_inprocess_cv);
2429 
2430 		sd_scsi_probe_cache_fini();
2431 
2432 		sd_scsi_target_lun_fini();
2433 
2434 		ddi_soft_state_fini(&sd_state);
2435 
2436 		return (err);
2437 	}
2438 
2439 	return (err);
2440 }
2441 
2442 
2443 /*
2444  *    Function: _fini
2445  *
2446  * Description: This is the driver _fini(9E) entry point.
2447  *
2448  * Return Code: Returns the value from mod_remove(9F)
2449  *
2450  *     Context: Called when driver module is unloaded.
2451  */
2452 
2453 int
2454 _fini(void)
2455 {
2456 	int err;
2457 
2458 	if ((err = mod_remove(&modlinkage)) != 0) {
2459 		return (err);
2460 	}
2461 
2462 	sd_taskq_delete();
2463 
2464 	mutex_destroy(&sd_log_mutex);
2465 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2466 
2467 	sd_scsi_probe_cache_fini();
2468 
2469 	sd_scsi_target_lun_fini();
2470 
2471 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2472 	cv_destroy(&sd_tr.srq_inprocess_cv);
2473 
2474 	ddi_soft_state_fini(&sd_state);
2475 
2476 	return (err);
2477 }
2478 
2479 
2480 /*
2481  *    Function: _info
2482  *
2483  * Description: This is the driver _info(9E) entry point.
2484  *
2485  *   Arguments: modinfop - pointer to the driver modinfo structure
2486  *
2487  * Return Code: Returns the value from mod_info(9F).
2488  *
2489  *     Context: Kernel thread context
2490  */
2491 
2492 int
2493 _info(struct modinfo *modinfop)
2494 {
2495 	return (mod_info(&modlinkage, modinfop));
2496 }
2497 
2498 
2499 /*
2500  * The following routines implement the driver message logging facility.
2501  * They provide component- and level- based debug output filtering.
2502  * Output may also be restricted to messages for a single instance by
2503  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2504  * to NULL, then messages for all instances are printed.
2505  *
2506  * These routines have been cloned from each other due to the language
2507  * constraints of macros and variable argument list processing.
2508  */
2509 
2510 
2511 /*
2512  *    Function: sd_log_err
2513  *
2514  * Description: This routine is called by the SD_ERROR macro for debug
2515  *		logging of error conditions.
2516  *
2517  *   Arguments: comp - driver component being logged
2518  *		dev  - pointer to driver info structure
2519  *		fmt  - error string and format to be logged
2520  */
2521 
2522 static void
2523 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2524 {
2525 	va_list		ap;
2526 	dev_info_t	*dev;
2527 
2528 	ASSERT(un != NULL);
2529 	dev = SD_DEVINFO(un);
2530 	ASSERT(dev != NULL);
2531 
2532 	/*
2533 	 * Filter messages based on the global component and level masks.
2534 	 * Also print if un matches the value of sd_debug_un, or if
2535 	 * sd_debug_un is set to NULL.
2536 	 */
2537 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2538 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2539 		mutex_enter(&sd_log_mutex);
2540 		va_start(ap, fmt);
2541 		(void) vsprintf(sd_log_buf, fmt, ap);
2542 		va_end(ap);
2543 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2544 		mutex_exit(&sd_log_mutex);
2545 	}
2546 #ifdef SD_FAULT_INJECTION
2547 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2548 	if (un->sd_injection_mask & comp) {
2549 		mutex_enter(&sd_log_mutex);
2550 		va_start(ap, fmt);
2551 		(void) vsprintf(sd_log_buf, fmt, ap);
2552 		va_end(ap);
2553 		sd_injection_log(sd_log_buf, un);
2554 		mutex_exit(&sd_log_mutex);
2555 	}
2556 #endif
2557 }
2558 
2559 
2560 /*
2561  *    Function: sd_log_info
2562  *
2563  * Description: This routine is called by the SD_INFO macro for debug
2564  *		logging of general purpose informational conditions.
2565  *
2566  *   Arguments: comp - driver component being logged
2567  *		dev  - pointer to driver info structure
2568  *		fmt  - info string and format to be logged
2569  */
2570 
2571 static void
2572 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2573 {
2574 	va_list		ap;
2575 	dev_info_t	*dev;
2576 
2577 	ASSERT(un != NULL);
2578 	dev = SD_DEVINFO(un);
2579 	ASSERT(dev != NULL);
2580 
2581 	/*
2582 	 * Filter messages based on the global component and level masks.
2583 	 * Also print if un matches the value of sd_debug_un, or if
2584 	 * sd_debug_un is set to NULL.
2585 	 */
2586 	if ((sd_component_mask & component) &&
2587 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2588 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2589 		mutex_enter(&sd_log_mutex);
2590 		va_start(ap, fmt);
2591 		(void) vsprintf(sd_log_buf, fmt, ap);
2592 		va_end(ap);
2593 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2594 		mutex_exit(&sd_log_mutex);
2595 	}
2596 #ifdef SD_FAULT_INJECTION
2597 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2598 	if (un->sd_injection_mask & component) {
2599 		mutex_enter(&sd_log_mutex);
2600 		va_start(ap, fmt);
2601 		(void) vsprintf(sd_log_buf, fmt, ap);
2602 		va_end(ap);
2603 		sd_injection_log(sd_log_buf, un);
2604 		mutex_exit(&sd_log_mutex);
2605 	}
2606 #endif
2607 }
2608 
2609 
2610 /*
2611  *    Function: sd_log_trace
2612  *
2613  * Description: This routine is called by the SD_TRACE macro for debug
2614  *		logging of trace conditions (i.e. function entry/exit).
2615  *
2616  *   Arguments: comp - driver component being logged
2617  *		dev  - pointer to driver info structure
2618  *		fmt  - trace string and format to be logged
2619  */
2620 
2621 static void
2622 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2623 {
2624 	va_list		ap;
2625 	dev_info_t	*dev;
2626 
2627 	ASSERT(un != NULL);
2628 	dev = SD_DEVINFO(un);
2629 	ASSERT(dev != NULL);
2630 
2631 	/*
2632 	 * Filter messages based on the global component and level masks.
2633 	 * Also print if un matches the value of sd_debug_un, or if
2634 	 * sd_debug_un is set to NULL.
2635 	 */
2636 	if ((sd_component_mask & component) &&
2637 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2638 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2639 		mutex_enter(&sd_log_mutex);
2640 		va_start(ap, fmt);
2641 		(void) vsprintf(sd_log_buf, fmt, ap);
2642 		va_end(ap);
2643 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2644 		mutex_exit(&sd_log_mutex);
2645 	}
2646 #ifdef SD_FAULT_INJECTION
2647 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2648 	if (un->sd_injection_mask & component) {
2649 		mutex_enter(&sd_log_mutex);
2650 		va_start(ap, fmt);
2651 		(void) vsprintf(sd_log_buf, fmt, ap);
2652 		va_end(ap);
2653 		sd_injection_log(sd_log_buf, un);
2654 		mutex_exit(&sd_log_mutex);
2655 	}
2656 #endif
2657 }
2658 
2659 
2660 /*
2661  *    Function: sdprobe
2662  *
2663  * Description: This is the driver probe(9e) entry point function.
2664  *
2665  *   Arguments: devi - opaque device info handle
2666  *
2667  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2668  *              DDI_PROBE_FAILURE: If the probe failed.
2669  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2670  *				   but may be present in the future.
2671  */
2672 
2673 static int
2674 sdprobe(dev_info_t *devi)
2675 {
2676 	struct scsi_device	*devp;
2677 	int			rval;
2678 	int			instance = ddi_get_instance(devi);
2679 
2680 	/*
2681 	 * if it wasn't for pln, sdprobe could actually be nulldev
2682 	 * in the "__fibre" case.
2683 	 */
2684 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2685 		return (DDI_PROBE_DONTCARE);
2686 	}
2687 
2688 	devp = ddi_get_driver_private(devi);
2689 
2690 	if (devp == NULL) {
2691 		/* Ooops... nexus driver is mis-configured... */
2692 		return (DDI_PROBE_FAILURE);
2693 	}
2694 
2695 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2696 		return (DDI_PROBE_PARTIAL);
2697 	}
2698 
2699 	/*
2700 	 * Call the SCSA utility probe routine to see if we actually
2701 	 * have a target at this SCSI nexus.
2702 	 */
2703 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2704 	case SCSIPROBE_EXISTS:
2705 		switch (devp->sd_inq->inq_dtype) {
2706 		case DTYPE_DIRECT:
2707 			rval = DDI_PROBE_SUCCESS;
2708 			break;
2709 		case DTYPE_RODIRECT:
2710 			/* CDs etc. Can be removable media */
2711 			rval = DDI_PROBE_SUCCESS;
2712 			break;
2713 		case DTYPE_OPTICAL:
2714 			/*
2715 			 * Rewritable optical driver HP115AA
2716 			 * Can also be removable media
2717 			 */
2718 
2719 			/*
2720 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2721 			 * pre solaris 9 sparc sd behavior is required
2722 			 *
2723 			 * If first time through and sd_dtype_optical_bind
2724 			 * has not been set in /etc/system check properties
2725 			 */
2726 
2727 			if (sd_dtype_optical_bind  < 0) {
2728 				sd_dtype_optical_bind = ddi_prop_get_int
2729 				    (DDI_DEV_T_ANY, devi, 0,
2730 				    "optical-device-bind", 1);
2731 			}
2732 
2733 			if (sd_dtype_optical_bind == 0) {
2734 				rval = DDI_PROBE_FAILURE;
2735 			} else {
2736 				rval = DDI_PROBE_SUCCESS;
2737 			}
2738 			break;
2739 
2740 		case DTYPE_NOTPRESENT:
2741 		default:
2742 			rval = DDI_PROBE_FAILURE;
2743 			break;
2744 		}
2745 		break;
2746 	default:
2747 		rval = DDI_PROBE_PARTIAL;
2748 		break;
2749 	}
2750 
2751 	/*
2752 	 * This routine checks for resource allocation prior to freeing,
2753 	 * so it will take care of the "smart probing" case where a
2754 	 * scsi_probe() may or may not have been issued and will *not*
2755 	 * free previously-freed resources.
2756 	 */
2757 	scsi_unprobe(devp);
2758 	return (rval);
2759 }
2760 
2761 
2762 /*
2763  *    Function: sdinfo
2764  *
2765  * Description: This is the driver getinfo(9e) entry point function.
2766  *		Given the device number, return the devinfo pointer from
2767  *		the scsi_device structure or the instance number
2768  *		associated with the dev_t.
2769  *
2770  *   Arguments: dip     - pointer to device info structure
2771  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2772  *			  DDI_INFO_DEVT2INSTANCE)
2773  *		arg     - driver dev_t
2774  *		resultp - user buffer for request response
2775  *
2776  * Return Code: DDI_SUCCESS
2777  *              DDI_FAILURE
2778  */
2779 /* ARGSUSED */
2780 static int
2781 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2782 {
2783 	struct sd_lun	*un;
2784 	dev_t		dev;
2785 	int		instance;
2786 	int		error;
2787 
2788 	switch (infocmd) {
2789 	case DDI_INFO_DEVT2DEVINFO:
2790 		dev = (dev_t)arg;
2791 		instance = SDUNIT(dev);
2792 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2793 			return (DDI_FAILURE);
2794 		}
2795 		*result = (void *) SD_DEVINFO(un);
2796 		error = DDI_SUCCESS;
2797 		break;
2798 	case DDI_INFO_DEVT2INSTANCE:
2799 		dev = (dev_t)arg;
2800 		instance = SDUNIT(dev);
2801 		*result = (void *)(uintptr_t)instance;
2802 		error = DDI_SUCCESS;
2803 		break;
2804 	default:
2805 		error = DDI_FAILURE;
2806 	}
2807 	return (error);
2808 }
2809 
2810 /*
2811  *    Function: sd_prop_op
2812  *
2813  * Description: This is the driver prop_op(9e) entry point function.
2814  *		Return the number of blocks for the partition in question
2815  *		or forward the request to the property facilities.
2816  *
2817  *   Arguments: dev       - device number
2818  *		dip       - pointer to device info structure
2819  *		prop_op   - property operator
2820  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2821  *		name      - pointer to property name
2822  *		valuep    - pointer or address of the user buffer
2823  *		lengthp   - property length
2824  *
2825  * Return Code: DDI_PROP_SUCCESS
2826  *              DDI_PROP_NOT_FOUND
2827  *              DDI_PROP_UNDEFINED
2828  *              DDI_PROP_NO_MEMORY
2829  *              DDI_PROP_BUF_TOO_SMALL
2830  */
2831 
2832 static int
2833 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2834     char *name, caddr_t valuep, int *lengthp)
2835 {
2836 	struct sd_lun	*un;
2837 
2838 	if ((un = ddi_get_soft_state(sd_state, ddi_get_instance(dip))) == NULL)
2839 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2840 		    name, valuep, lengthp));
2841 
2842 	return (cmlb_prop_op(un->un_cmlbhandle,
2843 	    dev, dip, prop_op, mod_flags, name, valuep, lengthp,
2844 	    SDPART(dev), (void *)SD_PATH_DIRECT));
2845 }
2846 
2847 /*
2848  * The following functions are for smart probing:
2849  * sd_scsi_probe_cache_init()
2850  * sd_scsi_probe_cache_fini()
2851  * sd_scsi_clear_probe_cache()
2852  * sd_scsi_probe_with_cache()
2853  */
2854 
2855 /*
2856  *    Function: sd_scsi_probe_cache_init
2857  *
2858  * Description: Initializes the probe response cache mutex and head pointer.
2859  *
2860  *     Context: Kernel thread context
2861  */
2862 
2863 static void
2864 sd_scsi_probe_cache_init(void)
2865 {
2866 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2867 	sd_scsi_probe_cache_head = NULL;
2868 }
2869 
2870 
2871 /*
2872  *    Function: sd_scsi_probe_cache_fini
2873  *
2874  * Description: Frees all resources associated with the probe response cache.
2875  *
2876  *     Context: Kernel thread context
2877  */
2878 
2879 static void
2880 sd_scsi_probe_cache_fini(void)
2881 {
2882 	struct sd_scsi_probe_cache *cp;
2883 	struct sd_scsi_probe_cache *ncp;
2884 
2885 	/* Clean up our smart probing linked list */
2886 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2887 		ncp = cp->next;
2888 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2889 	}
2890 	sd_scsi_probe_cache_head = NULL;
2891 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2892 }
2893 
2894 
2895 /*
2896  *    Function: sd_scsi_clear_probe_cache
2897  *
2898  * Description: This routine clears the probe response cache. This is
2899  *		done when open() returns ENXIO so that when deferred
2900  *		attach is attempted (possibly after a device has been
2901  *		turned on) we will retry the probe. Since we don't know
2902  *		which target we failed to open, we just clear the
2903  *		entire cache.
2904  *
2905  *     Context: Kernel thread context
2906  */
2907 
2908 static void
2909 sd_scsi_clear_probe_cache(void)
2910 {
2911 	struct sd_scsi_probe_cache	*cp;
2912 	int				i;
2913 
2914 	mutex_enter(&sd_scsi_probe_cache_mutex);
2915 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2916 		/*
2917 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2918 		 * force probing to be performed the next time
2919 		 * sd_scsi_probe_with_cache is called.
2920 		 */
2921 		for (i = 0; i < NTARGETS_WIDE; i++) {
2922 			cp->cache[i] = SCSIPROBE_EXISTS;
2923 		}
2924 	}
2925 	mutex_exit(&sd_scsi_probe_cache_mutex);
2926 }
2927 
2928 
2929 /*
2930  *    Function: sd_scsi_probe_with_cache
2931  *
2932  * Description: This routine implements support for a scsi device probe
2933  *		with cache. The driver maintains a cache of the target
2934  *		responses to scsi probes. If we get no response from a
2935  *		target during a probe inquiry, we remember that, and we
2936  *		avoid additional calls to scsi_probe on non-zero LUNs
2937  *		on the same target until the cache is cleared. By doing
2938  *		so we avoid the 1/4 sec selection timeout for nonzero
2939  *		LUNs. lun0 of a target is always probed.
2940  *
2941  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2942  *              waitfunc - indicates what the allocator routines should
2943  *			   do when resources are not available. This value
2944  *			   is passed on to scsi_probe() when that routine
2945  *			   is called.
2946  *
2947  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2948  *		otherwise the value returned by scsi_probe(9F).
2949  *
2950  *     Context: Kernel thread context
2951  */
2952 
2953 static int
2954 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2955 {
2956 	struct sd_scsi_probe_cache	*cp;
2957 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2958 	int		lun, tgt;
2959 
2960 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2961 	    SCSI_ADDR_PROP_LUN, 0);
2962 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2963 	    SCSI_ADDR_PROP_TARGET, -1);
2964 
2965 	/* Make sure caching enabled and target in range */
2966 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2967 		/* do it the old way (no cache) */
2968 		return (scsi_probe(devp, waitfn));
2969 	}
2970 
2971 	mutex_enter(&sd_scsi_probe_cache_mutex);
2972 
2973 	/* Find the cache for this scsi bus instance */
2974 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2975 		if (cp->pdip == pdip) {
2976 			break;
2977 		}
2978 	}
2979 
2980 	/* If we can't find a cache for this pdip, create one */
2981 	if (cp == NULL) {
2982 		int i;
2983 
2984 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2985 		    KM_SLEEP);
2986 		cp->pdip = pdip;
2987 		cp->next = sd_scsi_probe_cache_head;
2988 		sd_scsi_probe_cache_head = cp;
2989 		for (i = 0; i < NTARGETS_WIDE; i++) {
2990 			cp->cache[i] = SCSIPROBE_EXISTS;
2991 		}
2992 	}
2993 
2994 	mutex_exit(&sd_scsi_probe_cache_mutex);
2995 
2996 	/* Recompute the cache for this target if LUN zero */
2997 	if (lun == 0) {
2998 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2999 	}
3000 
3001 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
3002 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
3003 		return (SCSIPROBE_NORESP);
3004 	}
3005 
3006 	/* Do the actual probe; save & return the result */
3007 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
3008 }
3009 
3010 
3011 /*
3012  *    Function: sd_scsi_target_lun_init
3013  *
3014  * Description: Initializes the attached lun chain mutex and head pointer.
3015  *
3016  *     Context: Kernel thread context
3017  */
3018 
3019 static void
3020 sd_scsi_target_lun_init(void)
3021 {
3022 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
3023 	sd_scsi_target_lun_head = NULL;
3024 }
3025 
3026 
3027 /*
3028  *    Function: sd_scsi_target_lun_fini
3029  *
3030  * Description: Frees all resources associated with the attached lun
3031  *              chain
3032  *
3033  *     Context: Kernel thread context
3034  */
3035 
3036 static void
3037 sd_scsi_target_lun_fini(void)
3038 {
3039 	struct sd_scsi_hba_tgt_lun	*cp;
3040 	struct sd_scsi_hba_tgt_lun	*ncp;
3041 
3042 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
3043 		ncp = cp->next;
3044 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
3045 	}
3046 	sd_scsi_target_lun_head = NULL;
3047 	mutex_destroy(&sd_scsi_target_lun_mutex);
3048 }
3049 
3050 
3051 /*
3052  *    Function: sd_scsi_get_target_lun_count
3053  *
3054  * Description: This routine will check in the attached lun chain to see
3055  *		how many luns are attached on the required SCSI controller
3056  *		and target. Currently, some capabilities like tagged queue
3057  *		are supported per target based by HBA. So all luns in a
3058  *		target have the same capabilities. Based on this assumption,
3059  *		sd should only set these capabilities once per target. This
3060  *		function is called when sd needs to decide how many luns
3061  *		already attached on a target.
3062  *
3063  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
3064  *			  controller device.
3065  *              target	- The target ID on the controller's SCSI bus.
3066  *
3067  * Return Code: The number of luns attached on the required target and
3068  *		controller.
3069  *		-1 if target ID is not in parallel SCSI scope or the given
3070  *		dip is not in the chain.
3071  *
3072  *     Context: Kernel thread context
3073  */
3074 
3075 static int
3076 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
3077 {
3078 	struct sd_scsi_hba_tgt_lun	*cp;
3079 
3080 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
3081 		return (-1);
3082 	}
3083 
3084 	mutex_enter(&sd_scsi_target_lun_mutex);
3085 
3086 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3087 		if (cp->pdip == dip) {
3088 			break;
3089 		}
3090 	}
3091 
3092 	mutex_exit(&sd_scsi_target_lun_mutex);
3093 
3094 	if (cp == NULL) {
3095 		return (-1);
3096 	}
3097 
3098 	return (cp->nlun[target]);
3099 }
3100 
3101 
3102 /*
3103  *    Function: sd_scsi_update_lun_on_target
3104  *
3105  * Description: This routine is used to update the attached lun chain when a
3106  *		lun is attached or detached on a target.
3107  *
3108  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
3109  *                        controller device.
3110  *              target  - The target ID on the controller's SCSI bus.
3111  *		flag	- Indicate the lun is attached or detached.
3112  *
3113  *     Context: Kernel thread context
3114  */
3115 
3116 static void
3117 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
3118 {
3119 	struct sd_scsi_hba_tgt_lun	*cp;
3120 
3121 	mutex_enter(&sd_scsi_target_lun_mutex);
3122 
3123 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3124 		if (cp->pdip == dip) {
3125 			break;
3126 		}
3127 	}
3128 
3129 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
3130 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
3131 		    KM_SLEEP);
3132 		cp->pdip = dip;
3133 		cp->next = sd_scsi_target_lun_head;
3134 		sd_scsi_target_lun_head = cp;
3135 	}
3136 
3137 	mutex_exit(&sd_scsi_target_lun_mutex);
3138 
3139 	if (cp != NULL) {
3140 		if (flag == SD_SCSI_LUN_ATTACH) {
3141 			cp->nlun[target] ++;
3142 		} else {
3143 			cp->nlun[target] --;
3144 		}
3145 	}
3146 }
3147 
3148 
3149 /*
3150  *    Function: sd_spin_up_unit
3151  *
3152  * Description: Issues the following commands to spin-up the device:
3153  *		START STOP UNIT, and INQUIRY.
3154  *
3155  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3156  *                      structure for this target.
3157  *
3158  * Return Code: 0 - success
3159  *		EIO - failure
3160  *		EACCES - reservation conflict
3161  *
3162  *     Context: Kernel thread context
3163  */
3164 
3165 static int
3166 sd_spin_up_unit(sd_ssc_t *ssc)
3167 {
3168 	size_t	resid		= 0;
3169 	int	has_conflict	= FALSE;
3170 	uchar_t *bufaddr;
3171 	int	status;
3172 	struct sd_lun	*un;
3173 
3174 	ASSERT(ssc != NULL);
3175 	un = ssc->ssc_un;
3176 	ASSERT(un != NULL);
3177 
3178 	/*
3179 	 * Send a throwaway START UNIT command.
3180 	 *
3181 	 * If we fail on this, we don't care presently what precisely
3182 	 * is wrong.  EMC's arrays will also fail this with a check
3183 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
3184 	 * we don't want to fail the attach because it may become
3185 	 * "active" later.
3186 	 * We don't know if power condition is supported or not at
3187 	 * this stage, use START STOP bit.
3188 	 */
3189 	status = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
3190 	    SD_TARGET_START, SD_PATH_DIRECT);
3191 
3192 	if (status != 0) {
3193 		if (status == EACCES)
3194 			has_conflict = TRUE;
3195 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3196 	}
3197 
3198 	/*
3199 	 * Send another INQUIRY command to the target. This is necessary for
3200 	 * non-removable media direct access devices because their INQUIRY data
3201 	 * may not be fully qualified until they are spun up (perhaps via the
3202 	 * START command above).  Note: This seems to be needed for some
3203 	 * legacy devices only.) The INQUIRY command should succeed even if a
3204 	 * Reservation Conflict is present.
3205 	 */
3206 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
3207 
3208 	if (sd_send_scsi_INQUIRY(ssc, bufaddr, SUN_INQSIZE, 0, 0, &resid)
3209 	    != 0) {
3210 		kmem_free(bufaddr, SUN_INQSIZE);
3211 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
3212 		return (EIO);
3213 	}
3214 
3215 	/*
3216 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
3217 	 * Note that this routine does not return a failure here even if the
3218 	 * INQUIRY command did not return any data.  This is a legacy behavior.
3219 	 */
3220 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
3221 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
3222 	}
3223 
3224 	kmem_free(bufaddr, SUN_INQSIZE);
3225 
3226 	/* If we hit a reservation conflict above, tell the caller. */
3227 	if (has_conflict == TRUE) {
3228 		return (EACCES);
3229 	}
3230 
3231 	return (0);
3232 }
3233 
3234 #ifdef _LP64
3235 /*
3236  *    Function: sd_enable_descr_sense
3237  *
3238  * Description: This routine attempts to select descriptor sense format
3239  *		using the Control mode page.  Devices that support 64 bit
3240  *		LBAs (for >2TB luns) should also implement descriptor
3241  *		sense data so we will call this function whenever we see
3242  *		a lun larger than 2TB.  If for some reason the device
3243  *		supports 64 bit LBAs but doesn't support descriptor sense
3244  *		presumably the mode select will fail.  Everything will
3245  *		continue to work normally except that we will not get
3246  *		complete sense data for commands that fail with an LBA
3247  *		larger than 32 bits.
3248  *
3249  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3250  *                      structure for this target.
3251  *
3252  *     Context: Kernel thread context only
3253  */
3254 
3255 static void
3256 sd_enable_descr_sense(sd_ssc_t *ssc)
3257 {
3258 	uchar_t			*header;
3259 	struct mode_control_scsi3 *ctrl_bufp;
3260 	size_t			buflen;
3261 	size_t			bd_len;
3262 	int			status;
3263 	struct sd_lun		*un;
3264 
3265 	ASSERT(ssc != NULL);
3266 	un = ssc->ssc_un;
3267 	ASSERT(un != NULL);
3268 
3269 	/*
3270 	 * Read MODE SENSE page 0xA, Control Mode Page
3271 	 */
3272 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3273 	    sizeof (struct mode_control_scsi3);
3274 	header = kmem_zalloc(buflen, KM_SLEEP);
3275 
3276 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
3277 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT);
3278 
3279 	if (status != 0) {
3280 		SD_ERROR(SD_LOG_COMMON, un,
3281 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3282 		goto eds_exit;
3283 	}
3284 
3285 	/*
3286 	 * Determine size of Block Descriptors in order to locate
3287 	 * the mode page data. ATAPI devices return 0, SCSI devices
3288 	 * should return MODE_BLK_DESC_LENGTH.
3289 	 */
3290 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3291 
3292 	/* Clear the mode data length field for MODE SELECT */
3293 	((struct mode_header *)header)->length = 0;
3294 
3295 	ctrl_bufp = (struct mode_control_scsi3 *)
3296 	    (header + MODE_HEADER_LENGTH + bd_len);
3297 
3298 	/*
3299 	 * If the page length is smaller than the expected value,
3300 	 * the target device doesn't support D_SENSE. Bail out here.
3301 	 */
3302 	if (ctrl_bufp->mode_page.length <
3303 	    sizeof (struct mode_control_scsi3) - 2) {
3304 		SD_ERROR(SD_LOG_COMMON, un,
3305 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3306 		goto eds_exit;
3307 	}
3308 
3309 	/*
3310 	 * Clear PS bit for MODE SELECT
3311 	 */
3312 	ctrl_bufp->mode_page.ps = 0;
3313 
3314 	/*
3315 	 * Set D_SENSE to enable descriptor sense format.
3316 	 */
3317 	ctrl_bufp->d_sense = 1;
3318 
3319 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3320 
3321 	/*
3322 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3323 	 */
3324 	status = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
3325 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT);
3326 
3327 	if (status != 0) {
3328 		SD_INFO(SD_LOG_COMMON, un,
3329 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3330 	} else {
3331 		kmem_free(header, buflen);
3332 		return;
3333 	}
3334 
3335 eds_exit:
3336 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3337 	kmem_free(header, buflen);
3338 }
3339 
3340 /*
3341  *    Function: sd_reenable_dsense_task
3342  *
3343  * Description: Re-enable descriptor sense after device or bus reset
3344  *
3345  *     Context: Executes in a taskq() thread context
3346  */
3347 static void
3348 sd_reenable_dsense_task(void *arg)
3349 {
3350 	struct	sd_lun	*un = arg;
3351 	sd_ssc_t	*ssc;
3352 
3353 	ASSERT(un != NULL);
3354 
3355 	ssc = sd_ssc_init(un);
3356 	sd_enable_descr_sense(ssc);
3357 	sd_ssc_fini(ssc);
3358 }
3359 #endif /* _LP64 */
3360 
3361 /*
3362  *    Function: sd_set_mmc_caps
3363  *
3364  * Description: This routine determines if the device is MMC compliant and if
3365  *		the device supports CDDA via a mode sense of the CDVD
3366  *		capabilities mode page. Also checks if the device is a
3367  *		dvdram writable device.
3368  *
3369  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3370  *                      structure for this target.
3371  *
3372  *     Context: Kernel thread context only
3373  */
3374 
3375 static void
3376 sd_set_mmc_caps(sd_ssc_t *ssc)
3377 {
3378 	struct mode_header_grp2		*sense_mhp;
3379 	uchar_t				*sense_page;
3380 	caddr_t				buf;
3381 	int				bd_len;
3382 	int				status;
3383 	struct uscsi_cmd		com;
3384 	int				rtn;
3385 	uchar_t				*out_data_rw, *out_data_hd;
3386 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3387 	uchar_t				*out_data_gesn;
3388 	int				gesn_len;
3389 	struct sd_lun			*un;
3390 
3391 	ASSERT(ssc != NULL);
3392 	un = ssc->ssc_un;
3393 	ASSERT(un != NULL);
3394 
3395 	/*
3396 	 * The flags which will be set in this function are - mmc compliant,
3397 	 * dvdram writable device, cdda support. Initialize them to FALSE
3398 	 * and if a capability is detected - it will be set to TRUE.
3399 	 */
3400 	un->un_f_mmc_cap = FALSE;
3401 	un->un_f_dvdram_writable_device = FALSE;
3402 	un->un_f_cfg_cdda = FALSE;
3403 
3404 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3405 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3406 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3407 
3408 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3409 
3410 	if (status != 0) {
3411 		/* command failed; just return */
3412 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3413 		return;
3414 	}
3415 	/*
3416 	 * If the mode sense request for the CDROM CAPABILITIES
3417 	 * page (0x2A) succeeds the device is assumed to be MMC.
3418 	 */
3419 	un->un_f_mmc_cap = TRUE;
3420 
3421 	/* See if GET STATUS EVENT NOTIFICATION is supported */
3422 	if (un->un_f_mmc_gesn_polling) {
3423 		gesn_len = SD_GESN_HEADER_LEN + SD_GESN_MEDIA_DATA_LEN;
3424 		out_data_gesn = kmem_zalloc(gesn_len, KM_SLEEP);
3425 
3426 		rtn = sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(ssc,
3427 		    out_data_gesn, gesn_len, 1 << SD_GESN_MEDIA_CLASS);
3428 
3429 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3430 
3431 		if ((rtn != 0) || !sd_gesn_media_data_valid(out_data_gesn)) {
3432 			un->un_f_mmc_gesn_polling = FALSE;
3433 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3434 			    "sd_set_mmc_caps: gesn not supported "
3435 			    "%d %x %x %x %x\n", rtn,
3436 			    out_data_gesn[0], out_data_gesn[1],
3437 			    out_data_gesn[2], out_data_gesn[3]);
3438 		}
3439 
3440 		kmem_free(out_data_gesn, gesn_len);
3441 	}
3442 
3443 	/* Get to the page data */
3444 	sense_mhp = (struct mode_header_grp2 *)buf;
3445 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3446 	    sense_mhp->bdesc_length_lo;
3447 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3448 		/*
3449 		 * We did not get back the expected block descriptor
3450 		 * length so we cannot determine if the device supports
3451 		 * CDDA. However, we still indicate the device is MMC
3452 		 * according to the successful response to the page
3453 		 * 0x2A mode sense request.
3454 		 */
3455 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3456 		    "sd_set_mmc_caps: Mode Sense returned "
3457 		    "invalid block descriptor length\n");
3458 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3459 		return;
3460 	}
3461 
3462 	/* See if read CDDA is supported */
3463 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3464 	    bd_len);
3465 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3466 
3467 	/* See if writing DVD RAM is supported. */
3468 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3469 	if (un->un_f_dvdram_writable_device == TRUE) {
3470 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3471 		return;
3472 	}
3473 
3474 	/*
3475 	 * If the device presents DVD or CD capabilities in the mode
3476 	 * page, we can return here since a RRD will not have
3477 	 * these capabilities.
3478 	 */
3479 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3480 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3481 		return;
3482 	}
3483 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3484 
3485 	/*
3486 	 * If un->un_f_dvdram_writable_device is still FALSE,
3487 	 * check for a Removable Rigid Disk (RRD).  A RRD
3488 	 * device is identified by the features RANDOM_WRITABLE and
3489 	 * HARDWARE_DEFECT_MANAGEMENT.
3490 	 */
3491 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3492 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3493 
3494 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3495 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3496 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3497 
3498 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3499 
3500 	if (rtn != 0) {
3501 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3502 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3503 		return;
3504 	}
3505 
3506 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3507 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3508 
3509 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3510 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3511 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3512 
3513 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3514 
3515 	if (rtn == 0) {
3516 		/*
3517 		 * We have good information, check for random writable
3518 		 * and hardware defect features.
3519 		 */
3520 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3521 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3522 			un->un_f_dvdram_writable_device = TRUE;
3523 		}
3524 	}
3525 
3526 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3527 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3528 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3529 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3530 }
3531 
3532 /*
3533  *    Function: sd_check_for_writable_cd
3534  *
3535  * Description: This routine determines if the media in the device is
3536  *		writable or not. It uses the get configuration command (0x46)
3537  *		to determine if the media is writable
3538  *
3539  *   Arguments: un - driver soft state (unit) structure
3540  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3541  *                           chain and the normal command waitq, or
3542  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3543  *                           "direct" chain and bypass the normal command
3544  *                           waitq.
3545  *
3546  *     Context: Never called at interrupt context.
3547  */
3548 
3549 static void
3550 sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag)
3551 {
3552 	struct uscsi_cmd		com;
3553 	uchar_t				*out_data;
3554 	uchar_t				*rqbuf;
3555 	int				rtn;
3556 	uchar_t				*out_data_rw, *out_data_hd;
3557 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3558 	struct mode_header_grp2		*sense_mhp;
3559 	uchar_t				*sense_page;
3560 	caddr_t				buf;
3561 	int				bd_len;
3562 	int				status;
3563 	struct sd_lun			*un;
3564 
3565 	ASSERT(ssc != NULL);
3566 	un = ssc->ssc_un;
3567 	ASSERT(un != NULL);
3568 	ASSERT(mutex_owned(SD_MUTEX(un)));
3569 
3570 	/*
3571 	 * Initialize the writable media to false, if configuration info.
3572 	 * tells us otherwise then only we will set it.
3573 	 */
3574 	un->un_f_mmc_writable_media = FALSE;
3575 	mutex_exit(SD_MUTEX(un));
3576 
3577 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3578 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3579 
3580 	rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf, SENSE_LENGTH,
3581 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3582 
3583 	if (rtn != 0)
3584 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3585 
3586 	mutex_enter(SD_MUTEX(un));
3587 	if (rtn == 0) {
3588 		/*
3589 		 * We have good information, check for writable DVD.
3590 		 */
3591 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3592 			un->un_f_mmc_writable_media = TRUE;
3593 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3594 			kmem_free(rqbuf, SENSE_LENGTH);
3595 			return;
3596 		}
3597 	}
3598 
3599 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3600 	kmem_free(rqbuf, SENSE_LENGTH);
3601 
3602 	/*
3603 	 * Determine if this is a RRD type device.
3604 	 */
3605 	mutex_exit(SD_MUTEX(un));
3606 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3607 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3608 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3609 
3610 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3611 
3612 	mutex_enter(SD_MUTEX(un));
3613 	if (status != 0) {
3614 		/* command failed; just return */
3615 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3616 		return;
3617 	}
3618 
3619 	/* Get to the page data */
3620 	sense_mhp = (struct mode_header_grp2 *)buf;
3621 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3622 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3623 		/*
3624 		 * We did not get back the expected block descriptor length so
3625 		 * we cannot check the mode page.
3626 		 */
3627 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3628 		    "sd_check_for_writable_cd: Mode Sense returned "
3629 		    "invalid block descriptor length\n");
3630 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3631 		return;
3632 	}
3633 
3634 	/*
3635 	 * If the device presents DVD or CD capabilities in the mode
3636 	 * page, we can return here since a RRD device will not have
3637 	 * these capabilities.
3638 	 */
3639 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3640 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3641 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3642 		return;
3643 	}
3644 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3645 
3646 	/*
3647 	 * If un->un_f_mmc_writable_media is still FALSE,
3648 	 * check for RRD type media.  A RRD device is identified
3649 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3650 	 */
3651 	mutex_exit(SD_MUTEX(un));
3652 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3653 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3654 
3655 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3656 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3657 	    RANDOM_WRITABLE, path_flag);
3658 
3659 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3660 	if (rtn != 0) {
3661 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3662 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3663 		mutex_enter(SD_MUTEX(un));
3664 		return;
3665 	}
3666 
3667 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3668 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3669 
3670 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3671 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3672 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3673 
3674 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3675 	mutex_enter(SD_MUTEX(un));
3676 	if (rtn == 0) {
3677 		/*
3678 		 * We have good information, check for random writable
3679 		 * and hardware defect features as current.
3680 		 */
3681 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3682 		    (out_data_rw[10] & 0x1) &&
3683 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3684 		    (out_data_hd[10] & 0x1)) {
3685 			un->un_f_mmc_writable_media = TRUE;
3686 		}
3687 	}
3688 
3689 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3690 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3691 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3692 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3693 }
3694 
3695 /*
3696  *    Function: sd_read_unit_properties
3697  *
3698  * Description: The following implements a property lookup mechanism.
3699  *		Properties for particular disks (keyed on vendor, model
3700  *		and rev numbers) are sought in the sd.conf file via
3701  *		sd_process_sdconf_file(), and if not found there, are
3702  *		looked for in a list hardcoded in this driver via
3703  *		sd_process_sdconf_table() Once located the properties
3704  *		are used to update the driver unit structure.
3705  *
3706  *   Arguments: un - driver soft state (unit) structure
3707  */
3708 
3709 static void
3710 sd_read_unit_properties(struct sd_lun *un)
3711 {
3712 	/*
3713 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3714 	 * the "sd-config-list" property (from the sd.conf file) or if
3715 	 * there was not a match for the inquiry vid/pid. If this event
3716 	 * occurs the static driver configuration table is searched for
3717 	 * a match.
3718 	 */
3719 	ASSERT(un != NULL);
3720 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3721 		sd_process_sdconf_table(un);
3722 	}
3723 
3724 	/* check for LSI device */
3725 	sd_is_lsi(un);
3726 
3727 
3728 }
3729 
3730 
3731 /*
3732  *    Function: sd_process_sdconf_file
3733  *
3734  * Description: Use ddi_prop_lookup(9F) to obtain the properties from the
3735  *		driver's config file (ie, sd.conf) and update the driver
3736  *		soft state structure accordingly.
3737  *
3738  *   Arguments: un - driver soft state (unit) structure
3739  *
3740  * Return Code: SD_SUCCESS - The properties were successfully set according
3741  *			     to the driver configuration file.
3742  *		SD_FAILURE - The driver config list was not obtained or
3743  *			     there was no vid/pid match. This indicates that
3744  *			     the static config table should be used.
3745  *
3746  * The config file has a property, "sd-config-list". Currently we support
3747  * two kinds of formats. For both formats, the value of this property
3748  * is a list of duplets:
3749  *
3750  *  sd-config-list=
3751  *	<duplet>,
3752  *	[,<duplet>]*;
3753  *
3754  * For the improved format, where
3755  *
3756  *     <duplet>:= "<vid+pid>","<tunable-list>"
3757  *
3758  * and
3759  *
3760  *     <tunable-list>:=   <tunable> [, <tunable> ]*;
3761  *     <tunable> =        <name> : <value>
3762  *
3763  * The <vid+pid> is the string that is returned by the target device on a
3764  * SCSI inquiry command, the <tunable-list> contains one or more tunables
3765  * to apply to all target devices with the specified <vid+pid>.
3766  *
3767  * Each <tunable> is a "<name> : <value>" pair.
3768  *
3769  * For the old format, the structure of each duplet is as follows:
3770  *
3771  *  <duplet>:= "<vid+pid>","<data-property-name_list>"
3772  *
3773  * The first entry of the duplet is the device ID string (the concatenated
3774  * vid & pid; not to be confused with a device_id).  This is defined in
3775  * the same way as in the sd_disk_table.
3776  *
3777  * The second part of the duplet is a string that identifies a
3778  * data-property-name-list. The data-property-name-list is defined as
3779  * follows:
3780  *
3781  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3782  *
3783  * The syntax of <data-property-name> depends on the <version> field.
3784  *
3785  * If version = SD_CONF_VERSION_1 we have the following syntax:
3786  *
3787  *	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3788  *
3789  * where the prop0 value will be used to set prop0 if bit0 set in the
3790  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3791  *
3792  */
3793 
3794 static int
3795 sd_process_sdconf_file(struct sd_lun *un)
3796 {
3797 	char	**config_list = NULL;
3798 	uint_t	nelements;
3799 	char	*vidptr;
3800 	int	vidlen;
3801 	char	*dnlist_ptr;
3802 	char	*dataname_ptr;
3803 	char	*dataname_lasts;
3804 	int	*data_list = NULL;
3805 	uint_t	data_list_len;
3806 	int	rval = SD_FAILURE;
3807 	int	i;
3808 
3809 	ASSERT(un != NULL);
3810 
3811 	/* Obtain the configuration list associated with the .conf file */
3812 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, SD_DEVINFO(un),
3813 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, sd_config_list,
3814 	    &config_list, &nelements) != DDI_PROP_SUCCESS) {
3815 		return (SD_FAILURE);
3816 	}
3817 
3818 	/*
3819 	 * Compare vids in each duplet to the inquiry vid - if a match is
3820 	 * made, get the data value and update the soft state structure
3821 	 * accordingly.
3822 	 *
3823 	 * Each duplet should show as a pair of strings, return SD_FAILURE
3824 	 * otherwise.
3825 	 */
3826 	if (nelements & 1) {
3827 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3828 		    "sd-config-list should show as pairs of strings.\n");
3829 		if (config_list)
3830 			ddi_prop_free(config_list);
3831 		return (SD_FAILURE);
3832 	}
3833 
3834 	for (i = 0; i < nelements; i += 2) {
3835 		/*
3836 		 * Note: The assumption here is that each vid entry is on
3837 		 * a unique line from its associated duplet.
3838 		 */
3839 		vidptr = config_list[i];
3840 		vidlen = (int)strlen(vidptr);
3841 		if (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS) {
3842 			continue;
3843 		}
3844 
3845 		/*
3846 		 * dnlist contains 1 or more blank separated
3847 		 * data-property-name entries
3848 		 */
3849 		dnlist_ptr = config_list[i + 1];
3850 
3851 		if (strchr(dnlist_ptr, ':') != NULL) {
3852 			/*
3853 			 * Decode the improved format sd-config-list.
3854 			 */
3855 			sd_nvpair_str_decode(un, dnlist_ptr);
3856 		} else {
3857 			/*
3858 			 * The old format sd-config-list, loop through all
3859 			 * data-property-name entries in the
3860 			 * data-property-name-list
3861 			 * setting the properties for each.
3862 			 */
3863 			for (dataname_ptr = strtok_r(dnlist_ptr, " \t",
3864 			    &dataname_lasts); dataname_ptr != NULL;
3865 			    dataname_ptr = strtok_r(NULL, " \t",
3866 			    &dataname_lasts)) {
3867 				int version;
3868 
3869 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3870 				    "sd_process_sdconf_file: disk:%s, "
3871 				    "data:%s\n", vidptr, dataname_ptr);
3872 
3873 				/* Get the data list */
3874 				if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY,
3875 				    SD_DEVINFO(un), 0, dataname_ptr, &data_list,
3876 				    &data_list_len) != DDI_PROP_SUCCESS) {
3877 					SD_INFO(SD_LOG_ATTACH_DETACH, un,
3878 					    "sd_process_sdconf_file: data "
3879 					    "property (%s) has no value\n",
3880 					    dataname_ptr);
3881 					continue;
3882 				}
3883 
3884 				version = data_list[0];
3885 
3886 				if (version == SD_CONF_VERSION_1) {
3887 					sd_tunables values;
3888 
3889 					/* Set the properties */
3890 					if (sd_chk_vers1_data(un, data_list[1],
3891 					    &data_list[2], data_list_len,
3892 					    dataname_ptr) == SD_SUCCESS) {
3893 						sd_get_tunables_from_conf(un,
3894 						    data_list[1], &data_list[2],
3895 						    &values);
3896 						sd_set_vers1_properties(un,
3897 						    data_list[1], &values);
3898 						rval = SD_SUCCESS;
3899 					} else {
3900 						rval = SD_FAILURE;
3901 					}
3902 				} else {
3903 					scsi_log(SD_DEVINFO(un), sd_label,
3904 					    CE_WARN, "data property %s version "
3905 					    "0x%x is invalid.",
3906 					    dataname_ptr, version);
3907 					rval = SD_FAILURE;
3908 				}
3909 				if (data_list)
3910 					ddi_prop_free(data_list);
3911 			}
3912 		}
3913 	}
3914 
3915 	/* free up the memory allocated by ddi_prop_lookup_string_array(). */
3916 	if (config_list) {
3917 		ddi_prop_free(config_list);
3918 	}
3919 
3920 	return (rval);
3921 }
3922 
3923 /*
3924  *    Function: sd_nvpair_str_decode()
3925  *
3926  * Description: Parse the improved format sd-config-list to get
3927  *    each entry of tunable, which includes a name-value pair.
3928  *    Then call sd_set_properties() to set the property.
3929  *
3930  *   Arguments: un - driver soft state (unit) structure
3931  *    nvpair_str - the tunable list
3932  */
3933 static void
3934 sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str)
3935 {
3936 	char	*nv, *name, *value, *token;
3937 	char	*nv_lasts, *v_lasts, *x_lasts;
3938 
3939 	for (nv = strtok_r(nvpair_str, ",", &nv_lasts); nv != NULL;
3940 	    nv = strtok_r(NULL, ",", &nv_lasts)) {
3941 		token = strtok_r(nv, ":", &v_lasts);
3942 		name  = strtok_r(token, " \t", &x_lasts);
3943 		token = strtok_r(NULL, ":", &v_lasts);
3944 		value = strtok_r(token, " \t", &x_lasts);
3945 		if (name == NULL || value == NULL) {
3946 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3947 			    "sd_nvpair_str_decode: "
3948 			    "name or value is not valid!\n");
3949 		} else {
3950 			sd_set_properties(un, name, value);
3951 		}
3952 	}
3953 }
3954 
3955 /*
3956  *    Function: sd_set_properties()
3957  *
3958  * Description: Set device properties based on the improved
3959  *    format sd-config-list.
3960  *
3961  *   Arguments: un - driver soft state (unit) structure
3962  *    name  - supported tunable name
3963  *    value - tunable value
3964  */
3965 static void
3966 sd_set_properties(struct sd_lun *un, char *name, char *value)
3967 {
3968 	char	*endptr = NULL;
3969 	long	val = 0;
3970 
3971 	if (strcasecmp(name, "cache-nonvolatile") == 0) {
3972 		if (strcasecmp(value, "true") == 0) {
3973 			un->un_f_suppress_cache_flush = TRUE;
3974 		} else if (strcasecmp(value, "false") == 0) {
3975 			un->un_f_suppress_cache_flush = FALSE;
3976 		} else {
3977 			goto value_invalid;
3978 		}
3979 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3980 		    "suppress_cache_flush flag set to %d\n",
3981 		    un->un_f_suppress_cache_flush);
3982 		return;
3983 	}
3984 
3985 	if (strcasecmp(name, "controller-type") == 0) {
3986 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3987 			un->un_ctype = val;
3988 		} else {
3989 			goto value_invalid;
3990 		}
3991 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3992 		    "ctype set to %d\n", un->un_ctype);
3993 		return;
3994 	}
3995 
3996 	if (strcasecmp(name, "delay-busy") == 0) {
3997 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3998 			un->un_busy_timeout = drv_usectohz(val / 1000);
3999 		} else {
4000 			goto value_invalid;
4001 		}
4002 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4003 		    "busy_timeout set to %d\n", un->un_busy_timeout);
4004 		return;
4005 	}
4006 
4007 	if (strcasecmp(name, "disksort") == 0) {
4008 		if (strcasecmp(value, "true") == 0) {
4009 			un->un_f_disksort_disabled = FALSE;
4010 		} else if (strcasecmp(value, "false") == 0) {
4011 			un->un_f_disksort_disabled = TRUE;
4012 		} else {
4013 			goto value_invalid;
4014 		}
4015 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4016 		    "disksort disabled flag set to %d\n",
4017 		    un->un_f_disksort_disabled);
4018 		return;
4019 	}
4020 
4021 	if (strcasecmp(name, "power-condition") == 0) {
4022 		if (strcasecmp(value, "true") == 0) {
4023 			un->un_f_power_condition_disabled = FALSE;
4024 		} else if (strcasecmp(value, "false") == 0) {
4025 			un->un_f_power_condition_disabled = TRUE;
4026 		} else {
4027 			goto value_invalid;
4028 		}
4029 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4030 		    "power condition disabled flag set to %d\n",
4031 		    un->un_f_power_condition_disabled);
4032 		return;
4033 	}
4034 
4035 	if (strcasecmp(name, "timeout-releasereservation") == 0) {
4036 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4037 			un->un_reserve_release_time = val;
4038 		} else {
4039 			goto value_invalid;
4040 		}
4041 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4042 		    "reservation release timeout set to %d\n",
4043 		    un->un_reserve_release_time);
4044 		return;
4045 	}
4046 
4047 	if (strcasecmp(name, "reset-lun") == 0) {
4048 		if (strcasecmp(value, "true") == 0) {
4049 			un->un_f_lun_reset_enabled = TRUE;
4050 		} else if (strcasecmp(value, "false") == 0) {
4051 			un->un_f_lun_reset_enabled = FALSE;
4052 		} else {
4053 			goto value_invalid;
4054 		}
4055 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4056 		    "lun reset enabled flag set to %d\n",
4057 		    un->un_f_lun_reset_enabled);
4058 		return;
4059 	}
4060 
4061 	if (strcasecmp(name, "retries-busy") == 0) {
4062 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4063 			un->un_busy_retry_count = val;
4064 		} else {
4065 			goto value_invalid;
4066 		}
4067 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4068 		    "busy retry count set to %d\n", un->un_busy_retry_count);
4069 		return;
4070 	}
4071 
4072 	if (strcasecmp(name, "retries-timeout") == 0) {
4073 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4074 			un->un_retry_count = val;
4075 		} else {
4076 			goto value_invalid;
4077 		}
4078 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4079 		    "timeout retry count set to %d\n", un->un_retry_count);
4080 		return;
4081 	}
4082 
4083 	if (strcasecmp(name, "retries-notready") == 0) {
4084 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4085 			un->un_notready_retry_count = val;
4086 		} else {
4087 			goto value_invalid;
4088 		}
4089 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4090 		    "notready retry count set to %d\n",
4091 		    un->un_notready_retry_count);
4092 		return;
4093 	}
4094 
4095 	if (strcasecmp(name, "retries-reset") == 0) {
4096 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4097 			un->un_reset_retry_count = val;
4098 		} else {
4099 			goto value_invalid;
4100 		}
4101 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4102 		    "reset retry count set to %d\n",
4103 		    un->un_reset_retry_count);
4104 		return;
4105 	}
4106 
4107 	if (strcasecmp(name, "throttle-max") == 0) {
4108 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4109 			un->un_saved_throttle = un->un_throttle = val;
4110 		} else {
4111 			goto value_invalid;
4112 		}
4113 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4114 		    "throttle set to %d\n", un->un_throttle);
4115 	}
4116 
4117 	if (strcasecmp(name, "throttle-min") == 0) {
4118 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4119 			un->un_min_throttle = val;
4120 		} else {
4121 			goto value_invalid;
4122 		}
4123 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4124 		    "min throttle set to %d\n", un->un_min_throttle);
4125 	}
4126 
4127 	if (strcasecmp(name, "rmw-type") == 0) {
4128 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4129 			un->un_f_rmw_type = val;
4130 		} else {
4131 			goto value_invalid;
4132 		}
4133 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4134 		    "RMW type set to %d\n", un->un_f_rmw_type);
4135 	}
4136 
4137 	if (strcasecmp(name, "physical-block-size") == 0) {
4138 		if (ddi_strtol(value, &endptr, 0, &val) == 0 &&
4139 		    ISP2(val) && val >= un->un_tgt_blocksize &&
4140 		    val >= un->un_sys_blocksize) {
4141 			un->un_phy_blocksize = val;
4142 		} else {
4143 			goto value_invalid;
4144 		}
4145 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4146 		    "physical block size set to %d\n", un->un_phy_blocksize);
4147 	}
4148 
4149 	if (strcasecmp(name, "retries-victim") == 0) {
4150 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4151 			un->un_victim_retry_count = val;
4152 		} else {
4153 			goto value_invalid;
4154 		}
4155 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4156 		    "victim retry count set to %d\n",
4157 		    un->un_victim_retry_count);
4158 		return;
4159 	}
4160 
4161 	/*
4162 	 * Validate the throttle values.
4163 	 * If any of the numbers are invalid, set everything to defaults.
4164 	 */
4165 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4166 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4167 	    (un->un_min_throttle > un->un_throttle)) {
4168 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4169 		un->un_min_throttle = sd_min_throttle;
4170 	}
4171 
4172 	if (strcasecmp(name, "mmc-gesn-polling") == 0) {
4173 		if (strcasecmp(value, "true") == 0) {
4174 			un->un_f_mmc_gesn_polling = TRUE;
4175 		} else if (strcasecmp(value, "false") == 0) {
4176 			un->un_f_mmc_gesn_polling = FALSE;
4177 		} else {
4178 			goto value_invalid;
4179 		}
4180 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4181 		    "mmc-gesn-polling set to %d\n",
4182 		    un->un_f_mmc_gesn_polling);
4183 	}
4184 
4185 	return;
4186 
4187 value_invalid:
4188 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4189 	    "value of prop %s is invalid\n", name);
4190 }
4191 
4192 /*
4193  *    Function: sd_get_tunables_from_conf()
4194  *
4195  *
4196  *    This function reads the data list from the sd.conf file and pulls
4197  *    the values that can have numeric values as arguments and places
4198  *    the values in the appropriate sd_tunables member.
4199  *    Since the order of the data list members varies across platforms
4200  *    This function reads them from the data list in a platform specific
4201  *    order and places them into the correct sd_tunable member that is
4202  *    consistent across all platforms.
4203  */
4204 static void
4205 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
4206     sd_tunables *values)
4207 {
4208 	int i;
4209 	int mask;
4210 
4211 	bzero(values, sizeof (sd_tunables));
4212 
4213 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4214 
4215 		mask = 1 << i;
4216 		if (mask > flags) {
4217 			break;
4218 		}
4219 
4220 		switch (mask & flags) {
4221 		case 0:	/* This mask bit not set in flags */
4222 			continue;
4223 		case SD_CONF_BSET_THROTTLE:
4224 			values->sdt_throttle = data_list[i];
4225 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4226 			    "sd_get_tunables_from_conf: throttle = %d\n",
4227 			    values->sdt_throttle);
4228 			break;
4229 		case SD_CONF_BSET_CTYPE:
4230 			values->sdt_ctype = data_list[i];
4231 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4232 			    "sd_get_tunables_from_conf: ctype = %d\n",
4233 			    values->sdt_ctype);
4234 			break;
4235 		case SD_CONF_BSET_NRR_COUNT:
4236 			values->sdt_not_rdy_retries = data_list[i];
4237 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4238 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
4239 			    values->sdt_not_rdy_retries);
4240 			break;
4241 		case SD_CONF_BSET_BSY_RETRY_COUNT:
4242 			values->sdt_busy_retries = data_list[i];
4243 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4244 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
4245 			    values->sdt_busy_retries);
4246 			break;
4247 		case SD_CONF_BSET_RST_RETRIES:
4248 			values->sdt_reset_retries = data_list[i];
4249 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4250 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
4251 			    values->sdt_reset_retries);
4252 			break;
4253 		case SD_CONF_BSET_RSV_REL_TIME:
4254 			values->sdt_reserv_rel_time = data_list[i];
4255 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4256 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
4257 			    values->sdt_reserv_rel_time);
4258 			break;
4259 		case SD_CONF_BSET_MIN_THROTTLE:
4260 			values->sdt_min_throttle = data_list[i];
4261 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4262 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
4263 			    values->sdt_min_throttle);
4264 			break;
4265 		case SD_CONF_BSET_DISKSORT_DISABLED:
4266 			values->sdt_disk_sort_dis = data_list[i];
4267 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4268 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
4269 			    values->sdt_disk_sort_dis);
4270 			break;
4271 		case SD_CONF_BSET_LUN_RESET_ENABLED:
4272 			values->sdt_lun_reset_enable = data_list[i];
4273 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4274 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
4275 			    "\n", values->sdt_lun_reset_enable);
4276 			break;
4277 		case SD_CONF_BSET_CACHE_IS_NV:
4278 			values->sdt_suppress_cache_flush = data_list[i];
4279 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4280 			    "sd_get_tunables_from_conf: \
4281 			    suppress_cache_flush = %d"
4282 			    "\n", values->sdt_suppress_cache_flush);
4283 			break;
4284 		case SD_CONF_BSET_PC_DISABLED:
4285 			values->sdt_disk_sort_dis = data_list[i];
4286 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4287 			    "sd_get_tunables_from_conf: power_condition_dis = "
4288 			    "%d\n", values->sdt_power_condition_dis);
4289 			break;
4290 		}
4291 	}
4292 }
4293 
4294 /*
4295  *    Function: sd_process_sdconf_table
4296  *
4297  * Description: Search the static configuration table for a match on the
4298  *		inquiry vid/pid and update the driver soft state structure
4299  *		according to the table property values for the device.
4300  *
4301  *		The form of a configuration table entry is:
4302  *		  <vid+pid>,<flags>,<property-data>
4303  *		  "SEAGATE ST42400N",1,0x40000,
4304  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
4305  *
4306  *   Arguments: un - driver soft state (unit) structure
4307  */
4308 
4309 static void
4310 sd_process_sdconf_table(struct sd_lun *un)
4311 {
4312 	char	*id = NULL;
4313 	int	table_index;
4314 	int	idlen;
4315 
4316 	ASSERT(un != NULL);
4317 	for (table_index = 0; table_index < sd_disk_table_size;
4318 	    table_index++) {
4319 		id = sd_disk_table[table_index].device_id;
4320 		idlen = strlen(id);
4321 
4322 		/*
4323 		 * The static configuration table currently does not
4324 		 * implement version 10 properties. Additionally,
4325 		 * multiple data-property-name entries are not
4326 		 * implemented in the static configuration table.
4327 		 */
4328 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4329 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4330 			    "sd_process_sdconf_table: disk %s\n", id);
4331 			sd_set_vers1_properties(un,
4332 			    sd_disk_table[table_index].flags,
4333 			    sd_disk_table[table_index].properties);
4334 			break;
4335 		}
4336 	}
4337 }
4338 
4339 
4340 /*
4341  *    Function: sd_sdconf_id_match
4342  *
4343  * Description: This local function implements a case sensitive vid/pid
4344  *		comparison as well as the boundary cases of wild card and
4345  *		multiple blanks.
4346  *
4347  *		Note: An implicit assumption made here is that the scsi
4348  *		inquiry structure will always keep the vid, pid and
4349  *		revision strings in consecutive sequence, so they can be
4350  *		read as a single string. If this assumption is not the
4351  *		case, a separate string, to be used for the check, needs
4352  *		to be built with these strings concatenated.
4353  *
4354  *   Arguments: un - driver soft state (unit) structure
4355  *		id - table or config file vid/pid
4356  *		idlen  - length of the vid/pid (bytes)
4357  *
4358  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4359  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4360  */
4361 
4362 static int
4363 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
4364 {
4365 	struct scsi_inquiry	*sd_inq;
4366 	int			rval = SD_SUCCESS;
4367 
4368 	ASSERT(un != NULL);
4369 	sd_inq = un->un_sd->sd_inq;
4370 	ASSERT(id != NULL);
4371 
4372 	/*
4373 	 * We use the inq_vid as a pointer to a buffer containing the
4374 	 * vid and pid and use the entire vid/pid length of the table
4375 	 * entry for the comparison. This works because the inq_pid
4376 	 * data member follows inq_vid in the scsi_inquiry structure.
4377 	 */
4378 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
4379 		/*
4380 		 * The user id string is compared to the inquiry vid/pid
4381 		 * using a case insensitive comparison and ignoring
4382 		 * multiple spaces.
4383 		 */
4384 		rval = sd_blank_cmp(un, id, idlen);
4385 		if (rval != SD_SUCCESS) {
4386 			/*
4387 			 * User id strings that start and end with a "*"
4388 			 * are a special case. These do not have a
4389 			 * specific vendor, and the product string can
4390 			 * appear anywhere in the 16 byte PID portion of
4391 			 * the inquiry data. This is a simple strstr()
4392 			 * type search for the user id in the inquiry data.
4393 			 */
4394 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
4395 				char	*pidptr = &id[1];
4396 				int	i;
4397 				int	j;
4398 				int	pidstrlen = idlen - 2;
4399 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
4400 				    pidstrlen;
4401 
4402 				if (j < 0) {
4403 					return (SD_FAILURE);
4404 				}
4405 				for (i = 0; i < j; i++) {
4406 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
4407 					    pidptr, pidstrlen) == 0) {
4408 						rval = SD_SUCCESS;
4409 						break;
4410 					}
4411 				}
4412 			}
4413 		}
4414 	}
4415 	return (rval);
4416 }
4417 
4418 
4419 /*
4420  *    Function: sd_blank_cmp
4421  *
4422  * Description: If the id string starts and ends with a space, treat
4423  *		multiple consecutive spaces as equivalent to a single
4424  *		space. For example, this causes a sd_disk_table entry
4425  *		of " NEC CDROM " to match a device's id string of
4426  *		"NEC       CDROM".
4427  *
4428  *		Note: The success exit condition for this routine is if
4429  *		the pointer to the table entry is '\0' and the cnt of
4430  *		the inquiry length is zero. This will happen if the inquiry
4431  *		string returned by the device is padded with spaces to be
4432  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
4433  *		SCSI spec states that the inquiry string is to be padded with
4434  *		spaces.
4435  *
4436  *   Arguments: un - driver soft state (unit) structure
4437  *		id - table or config file vid/pid
4438  *		idlen  - length of the vid/pid (bytes)
4439  *
4440  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4441  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4442  */
4443 
4444 static int
4445 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
4446 {
4447 	char		*p1;
4448 	char		*p2;
4449 	int		cnt;
4450 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
4451 	    sizeof (SD_INQUIRY(un)->inq_pid);
4452 
4453 	ASSERT(un != NULL);
4454 	p2 = un->un_sd->sd_inq->inq_vid;
4455 	ASSERT(id != NULL);
4456 	p1 = id;
4457 
4458 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
4459 		/*
4460 		 * Note: string p1 is terminated by a NUL but string p2
4461 		 * isn't.  The end of p2 is determined by cnt.
4462 		 */
4463 		for (;;) {
4464 			/* skip over any extra blanks in both strings */
4465 			while ((*p1 != '\0') && (*p1 == ' ')) {
4466 				p1++;
4467 			}
4468 			while ((cnt != 0) && (*p2 == ' ')) {
4469 				p2++;
4470 				cnt--;
4471 			}
4472 
4473 			/* compare the two strings */
4474 			if ((cnt == 0) ||
4475 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
4476 				break;
4477 			}
4478 			while ((cnt > 0) &&
4479 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
4480 				p1++;
4481 				p2++;
4482 				cnt--;
4483 			}
4484 		}
4485 	}
4486 
4487 	/* return SD_SUCCESS if both strings match */
4488 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
4489 }
4490 
4491 
4492 /*
4493  *    Function: sd_chk_vers1_data
4494  *
4495  * Description: Verify the version 1 device properties provided by the
4496  *		user via the configuration file
4497  *
4498  *   Arguments: un	     - driver soft state (unit) structure
4499  *		flags	     - integer mask indicating properties to be set
4500  *		prop_list    - integer list of property values
4501  *		list_len     - number of the elements
4502  *
4503  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
4504  *		SD_FAILURE - Indicates the user provided data is invalid
4505  */
4506 
4507 static int
4508 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
4509     int list_len, char *dataname_ptr)
4510 {
4511 	int i;
4512 	int mask = 1;
4513 	int index = 0;
4514 
4515 	ASSERT(un != NULL);
4516 
4517 	/* Check for a NULL property name and list */
4518 	if (dataname_ptr == NULL) {
4519 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4520 		    "sd_chk_vers1_data: NULL data property name.");
4521 		return (SD_FAILURE);
4522 	}
4523 	if (prop_list == NULL) {
4524 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4525 		    "sd_chk_vers1_data: %s NULL data property list.",
4526 		    dataname_ptr);
4527 		return (SD_FAILURE);
4528 	}
4529 
4530 	/* Display a warning if undefined bits are set in the flags */
4531 	if (flags & ~SD_CONF_BIT_MASK) {
4532 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4533 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
4534 		    "Properties not set.",
4535 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
4536 		return (SD_FAILURE);
4537 	}
4538 
4539 	/*
4540 	 * Verify the length of the list by identifying the highest bit set
4541 	 * in the flags and validating that the property list has a length
4542 	 * up to the index of this bit.
4543 	 */
4544 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4545 		if (flags & mask) {
4546 			index++;
4547 		}
4548 		mask = 1 << i;
4549 	}
4550 	if (list_len < (index + 2)) {
4551 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4552 		    "sd_chk_vers1_data: "
4553 		    "Data property list %s size is incorrect. "
4554 		    "Properties not set.", dataname_ptr);
4555 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
4556 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
4557 		return (SD_FAILURE);
4558 	}
4559 	return (SD_SUCCESS);
4560 }
4561 
4562 
4563 /*
4564  *    Function: sd_set_vers1_properties
4565  *
4566  * Description: Set version 1 device properties based on a property list
4567  *		retrieved from the driver configuration file or static
4568  *		configuration table. Version 1 properties have the format:
4569  *
4570  *	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
4571  *
4572  *		where the prop0 value will be used to set prop0 if bit0
4573  *		is set in the flags
4574  *
4575  *   Arguments: un	     - driver soft state (unit) structure
4576  *		flags	     - integer mask indicating properties to be set
4577  *		prop_list    - integer list of property values
4578  */
4579 
4580 static void
4581 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4582 {
4583 	ASSERT(un != NULL);
4584 
4585 	/*
4586 	 * Set the flag to indicate cache is to be disabled. An attempt
4587 	 * to disable the cache via sd_cache_control() will be made
4588 	 * later during attach once the basic initialization is complete.
4589 	 */
4590 	if (flags & SD_CONF_BSET_NOCACHE) {
4591 		un->un_f_opt_disable_cache = TRUE;
4592 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4593 		    "sd_set_vers1_properties: caching disabled flag set\n");
4594 	}
4595 
4596 	/* CD-specific configuration parameters */
4597 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4598 		un->un_f_cfg_playmsf_bcd = TRUE;
4599 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4600 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4601 	}
4602 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4603 		un->un_f_cfg_readsub_bcd = TRUE;
4604 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4605 		    "sd_set_vers1_properties: readsub_bcd set\n");
4606 	}
4607 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4608 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4609 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4610 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4611 	}
4612 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4613 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4614 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4615 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4616 	}
4617 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4618 		un->un_f_cfg_no_read_header = TRUE;
4619 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4620 		    "sd_set_vers1_properties: no_read_header set\n");
4621 	}
4622 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4623 		un->un_f_cfg_read_cd_xd4 = TRUE;
4624 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4625 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4626 	}
4627 
4628 	/* Support for devices which do not have valid/unique serial numbers */
4629 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4630 		un->un_f_opt_fab_devid = TRUE;
4631 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4632 		    "sd_set_vers1_properties: fab_devid bit set\n");
4633 	}
4634 
4635 	/* Support for user throttle configuration */
4636 	if (flags & SD_CONF_BSET_THROTTLE) {
4637 		ASSERT(prop_list != NULL);
4638 		un->un_saved_throttle = un->un_throttle =
4639 		    prop_list->sdt_throttle;
4640 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4641 		    "sd_set_vers1_properties: throttle set to %d\n",
4642 		    prop_list->sdt_throttle);
4643 	}
4644 
4645 	/* Set the per disk retry count according to the conf file or table. */
4646 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4647 		ASSERT(prop_list != NULL);
4648 		if (prop_list->sdt_not_rdy_retries) {
4649 			un->un_notready_retry_count =
4650 			    prop_list->sdt_not_rdy_retries;
4651 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4652 			    "sd_set_vers1_properties: not ready retry count"
4653 			    " set to %d\n", un->un_notready_retry_count);
4654 		}
4655 	}
4656 
4657 	/* The controller type is reported for generic disk driver ioctls */
4658 	if (flags & SD_CONF_BSET_CTYPE) {
4659 		ASSERT(prop_list != NULL);
4660 		switch (prop_list->sdt_ctype) {
4661 		case CTYPE_CDROM:
4662 			un->un_ctype = prop_list->sdt_ctype;
4663 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4664 			    "sd_set_vers1_properties: ctype set to "
4665 			    "CTYPE_CDROM\n");
4666 			break;
4667 		case CTYPE_CCS:
4668 			un->un_ctype = prop_list->sdt_ctype;
4669 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4670 			    "sd_set_vers1_properties: ctype set to "
4671 			    "CTYPE_CCS\n");
4672 			break;
4673 		case CTYPE_ROD:		/* RW optical */
4674 			un->un_ctype = prop_list->sdt_ctype;
4675 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4676 			    "sd_set_vers1_properties: ctype set to "
4677 			    "CTYPE_ROD\n");
4678 			break;
4679 		default:
4680 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4681 			    "sd_set_vers1_properties: Could not set "
4682 			    "invalid ctype value (%d)",
4683 			    prop_list->sdt_ctype);
4684 		}
4685 	}
4686 
4687 	/* Purple failover timeout */
4688 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4689 		ASSERT(prop_list != NULL);
4690 		un->un_busy_retry_count =
4691 		    prop_list->sdt_busy_retries;
4692 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4693 		    "sd_set_vers1_properties: "
4694 		    "busy retry count set to %d\n",
4695 		    un->un_busy_retry_count);
4696 	}
4697 
4698 	/* Purple reset retry count */
4699 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4700 		ASSERT(prop_list != NULL);
4701 		un->un_reset_retry_count =
4702 		    prop_list->sdt_reset_retries;
4703 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4704 		    "sd_set_vers1_properties: "
4705 		    "reset retry count set to %d\n",
4706 		    un->un_reset_retry_count);
4707 	}
4708 
4709 	/* Purple reservation release timeout */
4710 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4711 		ASSERT(prop_list != NULL);
4712 		un->un_reserve_release_time =
4713 		    prop_list->sdt_reserv_rel_time;
4714 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4715 		    "sd_set_vers1_properties: "
4716 		    "reservation release timeout set to %d\n",
4717 		    un->un_reserve_release_time);
4718 	}
4719 
4720 	/*
4721 	 * Driver flag telling the driver to verify that no commands are pending
4722 	 * for a device before issuing a Test Unit Ready. This is a workaround
4723 	 * for a firmware bug in some Seagate eliteI drives.
4724 	 */
4725 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4726 		un->un_f_cfg_tur_check = TRUE;
4727 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4728 		    "sd_set_vers1_properties: tur queue check set\n");
4729 	}
4730 
4731 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4732 		un->un_min_throttle = prop_list->sdt_min_throttle;
4733 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4734 		    "sd_set_vers1_properties: min throttle set to %d\n",
4735 		    un->un_min_throttle);
4736 	}
4737 
4738 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4739 		un->un_f_disksort_disabled =
4740 		    (prop_list->sdt_disk_sort_dis != 0) ?
4741 		    TRUE : FALSE;
4742 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4743 		    "sd_set_vers1_properties: disksort disabled "
4744 		    "flag set to %d\n",
4745 		    prop_list->sdt_disk_sort_dis);
4746 	}
4747 
4748 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4749 		un->un_f_lun_reset_enabled =
4750 		    (prop_list->sdt_lun_reset_enable != 0) ?
4751 		    TRUE : FALSE;
4752 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4753 		    "sd_set_vers1_properties: lun reset enabled "
4754 		    "flag set to %d\n",
4755 		    prop_list->sdt_lun_reset_enable);
4756 	}
4757 
4758 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4759 		un->un_f_suppress_cache_flush =
4760 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4761 		    TRUE : FALSE;
4762 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4763 		    "sd_set_vers1_properties: suppress_cache_flush "
4764 		    "flag set to %d\n",
4765 		    prop_list->sdt_suppress_cache_flush);
4766 	}
4767 
4768 	if (flags & SD_CONF_BSET_PC_DISABLED) {
4769 		un->un_f_power_condition_disabled =
4770 		    (prop_list->sdt_power_condition_dis != 0) ?
4771 		    TRUE : FALSE;
4772 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4773 		    "sd_set_vers1_properties: power_condition_disabled "
4774 		    "flag set to %d\n",
4775 		    prop_list->sdt_power_condition_dis);
4776 	}
4777 
4778 	/*
4779 	 * Validate the throttle values.
4780 	 * If any of the numbers are invalid, set everything to defaults.
4781 	 */
4782 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4783 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4784 	    (un->un_min_throttle > un->un_throttle)) {
4785 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4786 		un->un_min_throttle = sd_min_throttle;
4787 	}
4788 }
4789 
4790 /*
4791  *   Function: sd_is_lsi()
4792  *
4793  *   Description: Check for lsi devices, step through the static device
4794  *	table to match vid/pid.
4795  *
4796  *   Args: un - ptr to sd_lun
4797  *
4798  *   Notes:  When creating new LSI property, need to add the new LSI property
4799  *		to this function.
4800  */
4801 static void
4802 sd_is_lsi(struct sd_lun *un)
4803 {
4804 	char	*id = NULL;
4805 	int	table_index;
4806 	int	idlen;
4807 	void	*prop;
4808 
4809 	ASSERT(un != NULL);
4810 	for (table_index = 0; table_index < sd_disk_table_size;
4811 	    table_index++) {
4812 		id = sd_disk_table[table_index].device_id;
4813 		idlen = strlen(id);
4814 		if (idlen == 0) {
4815 			continue;
4816 		}
4817 
4818 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4819 			prop = sd_disk_table[table_index].properties;
4820 			if (prop == &lsi_properties ||
4821 			    prop == &lsi_oem_properties ||
4822 			    prop == &lsi_properties_scsi ||
4823 			    prop == &symbios_properties) {
4824 				un->un_f_cfg_is_lsi = TRUE;
4825 			}
4826 			break;
4827 		}
4828 	}
4829 }
4830 
4831 /*
4832  *    Function: sd_get_physical_geometry
4833  *
4834  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4835  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4836  *		target, and use this information to initialize the physical
4837  *		geometry cache specified by pgeom_p.
4838  *
4839  *		MODE SENSE is an optional command, so failure in this case
4840  *		does not necessarily denote an error. We want to use the
4841  *		MODE SENSE commands to derive the physical geometry of the
4842  *		device, but if either command fails, the logical geometry is
4843  *		used as the fallback for disk label geometry in cmlb.
4844  *
4845  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4846  *		have already been initialized for the current target and
4847  *		that the current values be passed as args so that we don't
4848  *		end up ever trying to use -1 as a valid value. This could
4849  *		happen if either value is reset while we're not holding
4850  *		the mutex.
4851  *
4852  *   Arguments: un - driver soft state (unit) structure
4853  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4854  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4855  *			to use the USCSI "direct" chain and bypass the normal
4856  *			command waitq.
4857  *
4858  *     Context: Kernel thread only (can sleep).
4859  */
4860 
4861 static int
4862 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4863     diskaddr_t capacity, int lbasize, int path_flag)
4864 {
4865 	struct	mode_format	*page3p;
4866 	struct	mode_geometry	*page4p;
4867 	struct	mode_header	*headerp;
4868 	int	sector_size;
4869 	int	nsect;
4870 	int	nhead;
4871 	int	ncyl;
4872 	int	intrlv;
4873 	int	spc;
4874 	diskaddr_t	modesense_capacity;
4875 	int	rpm;
4876 	int	bd_len;
4877 	int	mode_header_length;
4878 	uchar_t	*p3bufp;
4879 	uchar_t	*p4bufp;
4880 	int	cdbsize;
4881 	int	ret = EIO;
4882 	sd_ssc_t *ssc;
4883 	int	status;
4884 
4885 	ASSERT(un != NULL);
4886 
4887 	if (lbasize == 0) {
4888 		if (ISCD(un)) {
4889 			lbasize = 2048;
4890 		} else {
4891 			lbasize = un->un_sys_blocksize;
4892 		}
4893 	}
4894 	pgeom_p->g_secsize = (unsigned short)lbasize;
4895 
4896 	/*
4897 	 * If the unit is a cd/dvd drive MODE SENSE page three
4898 	 * and MODE SENSE page four are reserved (see SBC spec
4899 	 * and MMC spec). To prevent soft errors just return
4900 	 * using the default LBA size.
4901 	 *
4902 	 * Since SATA MODE SENSE function (sata_txlt_mode_sense()) does not
4903 	 * implement support for mode pages 3 and 4 return here to prevent
4904 	 * illegal requests on SATA drives.
4905 	 *
4906 	 * These pages are also reserved in SBC-2 and later.  We assume SBC-2
4907 	 * or later for a direct-attached block device if the SCSI version is
4908 	 * at least SPC-3.
4909 	 */
4910 
4911 	if (ISCD(un) ||
4912 	    un->un_interconnect_type == SD_INTERCONNECT_SATA ||
4913 	    (un->un_ctype == CTYPE_CCS && SD_INQUIRY(un)->inq_ansi >= 5))
4914 		return (ret);
4915 
4916 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4917 
4918 	/*
4919 	 * Retrieve MODE SENSE page 3 - Format Device Page
4920 	 */
4921 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4922 	ssc = sd_ssc_init(un);
4923 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p3bufp,
4924 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag);
4925 	if (status != 0) {
4926 		SD_ERROR(SD_LOG_COMMON, un,
4927 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4928 		goto page3_exit;
4929 	}
4930 
4931 	/*
4932 	 * Determine size of Block Descriptors in order to locate the mode
4933 	 * page data.  ATAPI devices return 0, SCSI devices should return
4934 	 * MODE_BLK_DESC_LENGTH.
4935 	 */
4936 	headerp = (struct mode_header *)p3bufp;
4937 	if (un->un_f_cfg_is_atapi == TRUE) {
4938 		struct mode_header_grp2 *mhp =
4939 		    (struct mode_header_grp2 *)headerp;
4940 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4941 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4942 	} else {
4943 		mode_header_length = MODE_HEADER_LENGTH;
4944 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4945 	}
4946 
4947 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4948 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4949 		    "sd_get_physical_geometry: received unexpected bd_len "
4950 		    "of %d, page3\n", bd_len);
4951 		status = EIO;
4952 		goto page3_exit;
4953 	}
4954 
4955 	page3p = (struct mode_format *)
4956 	    ((caddr_t)headerp + mode_header_length + bd_len);
4957 
4958 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4959 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4960 		    "sd_get_physical_geometry: mode sense pg3 code mismatch "
4961 		    "%d\n", page3p->mode_page.code);
4962 		status = EIO;
4963 		goto page3_exit;
4964 	}
4965 
4966 	/*
4967 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4968 	 * complete successfully; otherwise, revert to the logical geometry.
4969 	 * So, we need to save everything in temporary variables.
4970 	 */
4971 	sector_size = BE_16(page3p->data_bytes_sect);
4972 
4973 	/*
4974 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4975 	 */
4976 	if (sector_size == 0) {
4977 		sector_size = un->un_sys_blocksize;
4978 	} else {
4979 		sector_size &= ~(un->un_sys_blocksize - 1);
4980 	}
4981 
4982 	nsect  = BE_16(page3p->sect_track);
4983 	intrlv = BE_16(page3p->interleave);
4984 
4985 	SD_INFO(SD_LOG_COMMON, un,
4986 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4987 	SD_INFO(SD_LOG_COMMON, un,
4988 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4989 	    page3p->mode_page.code, nsect, sector_size);
4990 	SD_INFO(SD_LOG_COMMON, un,
4991 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4992 	    BE_16(page3p->track_skew),
4993 	    BE_16(page3p->cylinder_skew));
4994 
4995 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
4996 
4997 	/*
4998 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4999 	 */
5000 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
5001 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p4bufp,
5002 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag);
5003 	if (status != 0) {
5004 		SD_ERROR(SD_LOG_COMMON, un,
5005 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
5006 		goto page4_exit;
5007 	}
5008 
5009 	/*
5010 	 * Determine size of Block Descriptors in order to locate the mode
5011 	 * page data.  ATAPI devices return 0, SCSI devices should return
5012 	 * MODE_BLK_DESC_LENGTH.
5013 	 */
5014 	headerp = (struct mode_header *)p4bufp;
5015 	if (un->un_f_cfg_is_atapi == TRUE) {
5016 		struct mode_header_grp2 *mhp =
5017 		    (struct mode_header_grp2 *)headerp;
5018 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
5019 	} else {
5020 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
5021 	}
5022 
5023 	if (bd_len > MODE_BLK_DESC_LENGTH) {
5024 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5025 		    "sd_get_physical_geometry: received unexpected bd_len of "
5026 		    "%d, page4\n", bd_len);
5027 		status = EIO;
5028 		goto page4_exit;
5029 	}
5030 
5031 	page4p = (struct mode_geometry *)
5032 	    ((caddr_t)headerp + mode_header_length + bd_len);
5033 
5034 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
5035 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
5036 		    "sd_get_physical_geometry: mode sense pg4 code mismatch "
5037 		    "%d\n", page4p->mode_page.code);
5038 		status = EIO;
5039 		goto page4_exit;
5040 	}
5041 
5042 	/*
5043 	 * Stash the data now, after we know that both commands completed.
5044 	 */
5045 
5046 
5047 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
5048 	spc   = nhead * nsect;
5049 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
5050 	rpm   = BE_16(page4p->rpm);
5051 
5052 	modesense_capacity = spc * ncyl;
5053 
5054 	SD_INFO(SD_LOG_COMMON, un,
5055 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
5056 	SD_INFO(SD_LOG_COMMON, un,
5057 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
5058 	SD_INFO(SD_LOG_COMMON, un,
5059 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
5060 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
5061 	    (void *)pgeom_p, capacity);
5062 
5063 	/*
5064 	 * Compensate if the drive's geometry is not rectangular, i.e.,
5065 	 * the product of C * H * S returned by MODE SENSE >= that returned
5066 	 * by read capacity. This is an idiosyncrasy of the original x86
5067 	 * disk subsystem.
5068 	 */
5069 	if (modesense_capacity >= capacity) {
5070 		SD_INFO(SD_LOG_COMMON, un,
5071 		    "sd_get_physical_geometry: adjusting acyl; "
5072 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
5073 		    (modesense_capacity - capacity + spc - 1) / spc);
5074 		if (sector_size != 0) {
5075 			/* 1243403: NEC D38x7 drives don't support sec size */
5076 			pgeom_p->g_secsize = (unsigned short)sector_size;
5077 		}
5078 		pgeom_p->g_nsect    = (unsigned short)nsect;
5079 		pgeom_p->g_nhead    = (unsigned short)nhead;
5080 		pgeom_p->g_capacity = capacity;
5081 		pgeom_p->g_acyl	    =
5082 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
5083 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
5084 	}
5085 
5086 	pgeom_p->g_rpm    = (unsigned short)rpm;
5087 	pgeom_p->g_intrlv = (unsigned short)intrlv;
5088 	ret = 0;
5089 
5090 	SD_INFO(SD_LOG_COMMON, un,
5091 	    "sd_get_physical_geometry: mode sense geometry:\n");
5092 	SD_INFO(SD_LOG_COMMON, un,
5093 	    "   nsect: %d; sector size: %d; interlv: %d\n",
5094 	    nsect, sector_size, intrlv);
5095 	SD_INFO(SD_LOG_COMMON, un,
5096 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
5097 	    nhead, ncyl, rpm, modesense_capacity);
5098 	SD_INFO(SD_LOG_COMMON, un,
5099 	    "sd_get_physical_geometry: (cached)\n");
5100 	SD_INFO(SD_LOG_COMMON, un,
5101 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5102 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
5103 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
5104 	SD_INFO(SD_LOG_COMMON, un,
5105 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
5106 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
5107 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
5108 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5109 
5110 page4_exit:
5111 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
5112 
5113 page3_exit:
5114 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
5115 
5116 	if (status != 0) {
5117 		if (status == EIO) {
5118 			/*
5119 			 * Some disks do not support mode sense(6), we
5120 			 * should ignore this kind of error(sense key is
5121 			 * 0x5 - illegal request).
5122 			 */
5123 			uint8_t *sensep;
5124 			int senlen;
5125 
5126 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
5127 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
5128 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
5129 
5130 			if (senlen > 0 &&
5131 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
5132 				sd_ssc_assessment(ssc,
5133 				    SD_FMT_IGNORE_COMPROMISE);
5134 			} else {
5135 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
5136 			}
5137 		} else {
5138 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5139 		}
5140 	}
5141 	sd_ssc_fini(ssc);
5142 	return (ret);
5143 }
5144 
5145 /*
5146  *    Function: sd_get_virtual_geometry
5147  *
5148  * Description: Ask the controller to tell us about the target device.
5149  *
5150  *   Arguments: un - pointer to softstate
5151  *		capacity - disk capacity in #blocks
5152  *		lbasize - disk block size in bytes
5153  *
5154  *     Context: Kernel thread only
5155  */
5156 
5157 static int
5158 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
5159     diskaddr_t capacity, int lbasize)
5160 {
5161 	uint_t	geombuf;
5162 	int	spc;
5163 
5164 	ASSERT(un != NULL);
5165 
5166 	/* Set sector size, and total number of sectors */
5167 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
5168 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
5169 
5170 	/* Let the HBA tell us its geometry */
5171 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
5172 
5173 	/* A value of -1 indicates an undefined "geometry" property */
5174 	if (geombuf == (-1)) {
5175 		return (EINVAL);
5176 	}
5177 
5178 	/* Initialize the logical geometry cache. */
5179 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
5180 	lgeom_p->g_nsect   = geombuf & 0xffff;
5181 	lgeom_p->g_secsize = un->un_sys_blocksize;
5182 
5183 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
5184 
5185 	/*
5186 	 * Note: The driver originally converted the capacity value from
5187 	 * target blocks to system blocks. However, the capacity value passed
5188 	 * to this routine is already in terms of system blocks (this scaling
5189 	 * is done when the READ CAPACITY command is issued and processed).
5190 	 * This 'error' may have gone undetected because the usage of g_ncyl
5191 	 * (which is based upon g_capacity) is very limited within the driver
5192 	 */
5193 	lgeom_p->g_capacity = capacity;
5194 
5195 	/*
5196 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
5197 	 * hba may return zero values if the device has been removed.
5198 	 */
5199 	if (spc == 0) {
5200 		lgeom_p->g_ncyl = 0;
5201 	} else {
5202 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
5203 	}
5204 	lgeom_p->g_acyl = 0;
5205 
5206 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
5207 	return (0);
5208 
5209 }
5210 /*
5211  *    Function: sd_update_block_info
5212  *
5213  * Description: Calculate a byte count to sector count bitshift value
5214  *		from sector size.
5215  *
5216  *   Arguments: un: unit struct.
5217  *		lbasize: new target sector size
5218  *		capacity: new target capacity, ie. block count
5219  *
5220  *     Context: Kernel thread context
5221  */
5222 
5223 static void
5224 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
5225 {
5226 	if (lbasize != 0) {
5227 		un->un_tgt_blocksize = lbasize;
5228 		un->un_f_tgt_blocksize_is_valid = TRUE;
5229 		if (!un->un_f_has_removable_media) {
5230 			un->un_sys_blocksize = lbasize;
5231 		}
5232 	}
5233 
5234 	if (capacity != 0) {
5235 		un->un_blockcount		= capacity;
5236 		un->un_f_blockcount_is_valid	= TRUE;
5237 
5238 		/*
5239 		 * The capacity has changed so update the errstats.
5240 		 */
5241 		if (un->un_errstats != NULL) {
5242 			struct sd_errstats *stp;
5243 
5244 			capacity *= un->un_sys_blocksize;
5245 			stp = (struct sd_errstats *)un->un_errstats->ks_data;
5246 			if (stp->sd_capacity.value.ui64 < capacity)
5247 				stp->sd_capacity.value.ui64 = capacity;
5248 		}
5249 	}
5250 }
5251 
5252 /*
5253  * Parses the SCSI Block Limits VPD page (0xB0). It's legal to pass NULL for
5254  * vpd_pg, in which case all the block limits will be reset to the defaults.
5255  */
5256 static void
5257 sd_parse_blk_limits_vpd(struct sd_lun *un, uchar_t *vpd_pg)
5258 {
5259 	sd_blk_limits_t *lim = &un->un_blk_lim;
5260 	unsigned pg_len;
5261 
5262 	if (vpd_pg != NULL)
5263 		pg_len = BE_IN16(&vpd_pg[2]);
5264 	else
5265 		pg_len = 0;
5266 
5267 	/* Block Limits VPD can be 16 bytes or 64 bytes long - support both */
5268 	if (pg_len >= 0x10) {
5269 		lim->lim_opt_xfer_len_gran = BE_IN16(&vpd_pg[6]);
5270 		lim->lim_max_xfer_len = BE_IN32(&vpd_pg[8]);
5271 		lim->lim_opt_xfer_len = BE_IN32(&vpd_pg[12]);
5272 
5273 		/* Zero means not reported, so use "unlimited" */
5274 		if (lim->lim_max_xfer_len == 0)
5275 			lim->lim_max_xfer_len = UINT32_MAX;
5276 		if (lim->lim_opt_xfer_len == 0)
5277 			lim->lim_opt_xfer_len = UINT32_MAX;
5278 	} else {
5279 		lim->lim_opt_xfer_len_gran = 0;
5280 		lim->lim_max_xfer_len = UINT32_MAX;
5281 		lim->lim_opt_xfer_len = UINT32_MAX;
5282 	}
5283 	if (pg_len >= 0x3c) {
5284 		lim->lim_max_pfetch_len = BE_IN32(&vpd_pg[16]);
5285 		/*
5286 		 * A zero in either of the following two fields indicates lack
5287 		 * of UNMAP support.
5288 		 */
5289 		lim->lim_max_unmap_lba_cnt = BE_IN32(&vpd_pg[20]);
5290 		lim->lim_max_unmap_descr_cnt = BE_IN32(&vpd_pg[24]);
5291 		lim->lim_opt_unmap_gran = BE_IN32(&vpd_pg[28]);
5292 		if ((vpd_pg[32] >> 7) == 1) {
5293 			lim->lim_unmap_gran_align =
5294 			    ((vpd_pg[32] & 0x7f) << 24) | (vpd_pg[33] << 16) |
5295 			    (vpd_pg[34] << 8) | vpd_pg[35];
5296 		} else {
5297 			lim->lim_unmap_gran_align = 0;
5298 		}
5299 		lim->lim_max_write_same_len = BE_IN64(&vpd_pg[36]);
5300 	} else {
5301 		lim->lim_max_pfetch_len = UINT32_MAX;
5302 		lim->lim_max_unmap_lba_cnt = UINT32_MAX;
5303 		lim->lim_max_unmap_descr_cnt = SD_UNMAP_MAX_DESCR;
5304 		lim->lim_opt_unmap_gran = 0;
5305 		lim->lim_unmap_gran_align = 0;
5306 		lim->lim_max_write_same_len = UINT64_MAX;
5307 	}
5308 }
5309 
5310 /*
5311  * Collects VPD page B0 data if available (block limits). If the data is
5312  * not available or querying the device failed, we revert to the defaults.
5313  */
5314 static void
5315 sd_setup_blk_limits(sd_ssc_t *ssc)
5316 {
5317 	struct sd_lun	*un		= ssc->ssc_un;
5318 	uchar_t		*inqB0		= NULL;
5319 	size_t		inqB0_resid	= 0;
5320 	int		rval;
5321 
5322 	if (un->un_vpd_page_mask & SD_VPD_BLK_LIMITS_PG) {
5323 		inqB0 = kmem_zalloc(MAX_INQUIRY_SIZE, KM_SLEEP);
5324 		rval = sd_send_scsi_INQUIRY(ssc, inqB0, MAX_INQUIRY_SIZE, 0x01,
5325 		    0xB0, &inqB0_resid);
5326 		if (rval != 0) {
5327 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5328 			kmem_free(inqB0, MAX_INQUIRY_SIZE);
5329 			inqB0 = NULL;
5330 		}
5331 	}
5332 	/* passing NULL inqB0 will reset to defaults */
5333 	sd_parse_blk_limits_vpd(ssc->ssc_un, inqB0);
5334 	if (inqB0)
5335 		kmem_free(inqB0, MAX_INQUIRY_SIZE);
5336 }
5337 
5338 /*
5339  *    Function: sd_register_devid
5340  *
5341  * Description: This routine will obtain the device id information from the
5342  *		target, obtain the serial number, and register the device
5343  *		id with the ddi framework.
5344  *
5345  *   Arguments: devi - the system's dev_info_t for the device.
5346  *		un - driver soft state (unit) structure
5347  *		reservation_flag - indicates if a reservation conflict
5348  *		occurred during attach
5349  *
5350  *     Context: Kernel Thread
5351  */
5352 static void
5353 sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi, int reservation_flag)
5354 {
5355 	int		rval		= 0;
5356 	uchar_t		*inq80		= NULL;
5357 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5358 	size_t		inq80_resid	= 0;
5359 	uchar_t		*inq83		= NULL;
5360 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5361 	size_t		inq83_resid	= 0;
5362 	int		dlen, len;
5363 	char		*sn;
5364 	struct sd_lun	*un;
5365 
5366 	ASSERT(ssc != NULL);
5367 	un = ssc->ssc_un;
5368 	ASSERT(un != NULL);
5369 	ASSERT(mutex_owned(SD_MUTEX(un)));
5370 	ASSERT((SD_DEVINFO(un)) == devi);
5371 
5372 
5373 	/*
5374 	 * We check the availability of the World Wide Name (0x83) and Unit
5375 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5376 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5377 	 * 0x83 is available, that is the best choice.  Our next choice is
5378 	 * 0x80.  If neither are available, we munge the devid from the device
5379 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5380 	 * to fabricate a devid for non-Sun qualified disks.
5381 	 */
5382 	if (sd_check_vpd_page_support(ssc) == 0) {
5383 		/* collect page 80 data if available */
5384 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5385 
5386 			mutex_exit(SD_MUTEX(un));
5387 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5388 
5389 			rval = sd_send_scsi_INQUIRY(ssc, inq80, inq80_len,
5390 			    0x01, 0x80, &inq80_resid);
5391 
5392 			if (rval != 0) {
5393 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5394 				kmem_free(inq80, inq80_len);
5395 				inq80 = NULL;
5396 				inq80_len = 0;
5397 			} else if (ddi_prop_exists(
5398 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
5399 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
5400 			    INQUIRY_SERIAL_NO) == 0) {
5401 				/*
5402 				 * If we don't already have a serial number
5403 				 * property, do quick verify of data returned
5404 				 * and define property.
5405 				 */
5406 				dlen = inq80_len - inq80_resid;
5407 				len = (size_t)inq80[3];
5408 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
5409 					/*
5410 					 * Ensure sn termination, skip leading
5411 					 * blanks, and create property
5412 					 * 'inquiry-serial-no'.
5413 					 */
5414 					sn = (char *)&inq80[4];
5415 					sn[len] = 0;
5416 					while (*sn && (*sn == ' '))
5417 						sn++;
5418 					if (*sn) {
5419 						(void) ddi_prop_update_string(
5420 						    DDI_DEV_T_NONE,
5421 						    SD_DEVINFO(un),
5422 						    INQUIRY_SERIAL_NO, sn);
5423 					}
5424 				}
5425 			}
5426 			mutex_enter(SD_MUTEX(un));
5427 		}
5428 
5429 		/* collect page 83 data if available */
5430 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5431 			mutex_exit(SD_MUTEX(un));
5432 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
5433 
5434 			rval = sd_send_scsi_INQUIRY(ssc, inq83, inq83_len,
5435 			    0x01, 0x83, &inq83_resid);
5436 
5437 			if (rval != 0) {
5438 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5439 				kmem_free(inq83, inq83_len);
5440 				inq83 = NULL;
5441 				inq83_len = 0;
5442 			}
5443 			mutex_enter(SD_MUTEX(un));
5444 		}
5445 	}
5446 
5447 	/*
5448 	 * If transport has already registered a devid for this target
5449 	 * then that takes precedence over the driver's determination
5450 	 * of the devid.
5451 	 *
5452 	 * NOTE: The reason this check is done here instead of at the beginning
5453 	 * of the function is to allow the code above to create the
5454 	 * 'inquiry-serial-no' property.
5455 	 */
5456 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
5457 		ASSERT(un->un_devid);
5458 		un->un_f_devid_transport_defined = TRUE;
5459 		goto cleanup; /* use devid registered by the transport */
5460 	}
5461 
5462 	/*
5463 	 * This is the case of antiquated Sun disk drives that have the
5464 	 * FAB_DEVID property set in the disk_table.  These drives
5465 	 * manage the devid's by storing them in last 2 available sectors
5466 	 * on the drive and have them fabricated by the ddi layer by calling
5467 	 * ddi_devid_init and passing the DEVID_FAB flag.
5468 	 */
5469 	if (un->un_f_opt_fab_devid == TRUE) {
5470 		/*
5471 		 * Depending on EINVAL isn't reliable, since a reserved disk
5472 		 * may result in invalid geometry, so check to make sure a
5473 		 * reservation conflict did not occur during attach.
5474 		 */
5475 		if ((sd_get_devid(ssc) == EINVAL) &&
5476 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5477 			/*
5478 			 * The devid is invalid AND there is no reservation
5479 			 * conflict.  Fabricate a new devid.
5480 			 */
5481 			(void) sd_create_devid(ssc);
5482 		}
5483 
5484 		/* Register the devid if it exists */
5485 		if (un->un_devid != NULL) {
5486 			(void) ddi_devid_register(SD_DEVINFO(un),
5487 			    un->un_devid);
5488 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5489 			    "sd_register_devid: Devid Fabricated\n");
5490 		}
5491 		goto cleanup;
5492 	}
5493 
5494 	/* encode best devid possible based on data available */
5495 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
5496 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
5497 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
5498 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
5499 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
5500 
5501 		/* devid successfully encoded, register devid */
5502 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
5503 
5504 	} else {
5505 		/*
5506 		 * Unable to encode a devid based on data available.
5507 		 * This is not a Sun qualified disk.  Older Sun disk
5508 		 * drives that have the SD_FAB_DEVID property
5509 		 * set in the disk_table and non Sun qualified
5510 		 * disks are treated in the same manner.  These
5511 		 * drives manage the devid's by storing them in
5512 		 * last 2 available sectors on the drive and
5513 		 * have them fabricated by the ddi layer by
5514 		 * calling ddi_devid_init and passing the
5515 		 * DEVID_FAB flag.
5516 		 * Create a fabricate devid only if there's no
5517 		 * fabricate devid existed.
5518 		 */
5519 		if (sd_get_devid(ssc) == EINVAL) {
5520 			(void) sd_create_devid(ssc);
5521 		}
5522 		un->un_f_opt_fab_devid = TRUE;
5523 
5524 		/* Register the devid if it exists */
5525 		if (un->un_devid != NULL) {
5526 			(void) ddi_devid_register(SD_DEVINFO(un),
5527 			    un->un_devid);
5528 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5529 			    "sd_register_devid: devid fabricated using "
5530 			    "ddi framework\n");
5531 		}
5532 	}
5533 
5534 cleanup:
5535 	/* clean up resources */
5536 	if (inq80 != NULL) {
5537 		kmem_free(inq80, inq80_len);
5538 	}
5539 	if (inq83 != NULL) {
5540 		kmem_free(inq83, inq83_len);
5541 	}
5542 }
5543 
5544 
5545 
5546 /*
5547  *    Function: sd_get_devid
5548  *
5549  * Description: This routine will return 0 if a valid device id has been
5550  *		obtained from the target and stored in the soft state. If a
5551  *		valid device id has not been previously read and stored, a
5552  *		read attempt will be made.
5553  *
5554  *   Arguments: un - driver soft state (unit) structure
5555  *
5556  * Return Code: 0 if we successfully get the device id
5557  *
5558  *     Context: Kernel Thread
5559  */
5560 
5561 static int
5562 sd_get_devid(sd_ssc_t *ssc)
5563 {
5564 	struct dk_devid		*dkdevid;
5565 	ddi_devid_t		tmpid;
5566 	uint_t			*ip;
5567 	size_t			sz;
5568 	diskaddr_t		blk;
5569 	int			status;
5570 	int			chksum;
5571 	int			i;
5572 	size_t			buffer_size;
5573 	struct sd_lun		*un;
5574 
5575 	ASSERT(ssc != NULL);
5576 	un = ssc->ssc_un;
5577 	ASSERT(un != NULL);
5578 	ASSERT(mutex_owned(SD_MUTEX(un)));
5579 
5580 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
5581 	    un);
5582 
5583 	if (un->un_devid != NULL) {
5584 		return (0);
5585 	}
5586 
5587 	mutex_exit(SD_MUTEX(un));
5588 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5589 	    (void *)SD_PATH_DIRECT) != 0) {
5590 		mutex_enter(SD_MUTEX(un));
5591 		return (EINVAL);
5592 	}
5593 
5594 	/*
5595 	 * Read and verify device id, stored in the reserved cylinders at the
5596 	 * end of the disk. Backup label is on the odd sectors of the last
5597 	 * track of the last cylinder. Device id will be on track of the next
5598 	 * to last cylinder.
5599 	 */
5600 	mutex_enter(SD_MUTEX(un));
5601 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
5602 	mutex_exit(SD_MUTEX(un));
5603 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
5604 	status = sd_send_scsi_READ(ssc, dkdevid, buffer_size, blk,
5605 	    SD_PATH_DIRECT);
5606 
5607 	if (status != 0) {
5608 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5609 		goto error;
5610 	}
5611 
5612 	/* Validate the revision */
5613 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
5614 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
5615 		status = EINVAL;
5616 		goto error;
5617 	}
5618 
5619 	/* Calculate the checksum */
5620 	chksum = 0;
5621 	ip = (uint_t *)dkdevid;
5622 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5623 	    i++) {
5624 		chksum ^= ip[i];
5625 	}
5626 
5627 	/* Compare the checksums */
5628 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
5629 		status = EINVAL;
5630 		goto error;
5631 	}
5632 
5633 	/* Validate the device id */
5634 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
5635 		status = EINVAL;
5636 		goto error;
5637 	}
5638 
5639 	/*
5640 	 * Store the device id in the driver soft state
5641 	 */
5642 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
5643 	tmpid = kmem_alloc(sz, KM_SLEEP);
5644 
5645 	mutex_enter(SD_MUTEX(un));
5646 
5647 	un->un_devid = tmpid;
5648 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
5649 
5650 	kmem_free(dkdevid, buffer_size);
5651 
5652 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
5653 
5654 	return (status);
5655 error:
5656 	mutex_enter(SD_MUTEX(un));
5657 	kmem_free(dkdevid, buffer_size);
5658 	return (status);
5659 }
5660 
5661 
5662 /*
5663  *    Function: sd_create_devid
5664  *
5665  * Description: This routine will fabricate the device id and write it
5666  *		to the disk.
5667  *
5668  *   Arguments: un - driver soft state (unit) structure
5669  *
5670  * Return Code: value of the fabricated device id
5671  *
5672  *     Context: Kernel Thread
5673  */
5674 
5675 static ddi_devid_t
5676 sd_create_devid(sd_ssc_t *ssc)
5677 {
5678 	struct sd_lun	*un;
5679 
5680 	ASSERT(ssc != NULL);
5681 	un = ssc->ssc_un;
5682 	ASSERT(un != NULL);
5683 
5684 	/* Fabricate the devid */
5685 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
5686 	    == DDI_FAILURE) {
5687 		return (NULL);
5688 	}
5689 
5690 	/* Write the devid to disk */
5691 	if (sd_write_deviceid(ssc) != 0) {
5692 		ddi_devid_free(un->un_devid);
5693 		un->un_devid = NULL;
5694 	}
5695 
5696 	return (un->un_devid);
5697 }
5698 
5699 
5700 /*
5701  *    Function: sd_write_deviceid
5702  *
5703  * Description: This routine will write the device id to the disk
5704  *		reserved sector.
5705  *
5706  *   Arguments: un - driver soft state (unit) structure
5707  *
5708  * Return Code: EINVAL
5709  *		value returned by sd_send_scsi_cmd
5710  *
5711  *     Context: Kernel Thread
5712  */
5713 
5714 static int
5715 sd_write_deviceid(sd_ssc_t *ssc)
5716 {
5717 	struct dk_devid		*dkdevid;
5718 	uchar_t			*buf;
5719 	diskaddr_t		blk;
5720 	uint_t			*ip, chksum;
5721 	int			status;
5722 	int			i;
5723 	struct sd_lun		*un;
5724 
5725 	ASSERT(ssc != NULL);
5726 	un = ssc->ssc_un;
5727 	ASSERT(un != NULL);
5728 	ASSERT(mutex_owned(SD_MUTEX(un)));
5729 
5730 	mutex_exit(SD_MUTEX(un));
5731 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5732 	    (void *)SD_PATH_DIRECT) != 0) {
5733 		mutex_enter(SD_MUTEX(un));
5734 		return (-1);
5735 	}
5736 
5737 
5738 	/* Allocate the buffer */
5739 	buf = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5740 	dkdevid = (struct dk_devid *)buf;
5741 
5742 	/* Fill in the revision */
5743 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5744 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5745 
5746 	/* Copy in the device id */
5747 	mutex_enter(SD_MUTEX(un));
5748 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5749 	    ddi_devid_sizeof(un->un_devid));
5750 	mutex_exit(SD_MUTEX(un));
5751 
5752 	/* Calculate the checksum */
5753 	chksum = 0;
5754 	ip = (uint_t *)dkdevid;
5755 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5756 	    i++) {
5757 		chksum ^= ip[i];
5758 	}
5759 
5760 	/* Fill-in checksum */
5761 	DKD_FORMCHKSUM(chksum, dkdevid);
5762 
5763 	/* Write the reserved sector */
5764 	status = sd_send_scsi_WRITE(ssc, buf, un->un_sys_blocksize, blk,
5765 	    SD_PATH_DIRECT);
5766 	if (status != 0)
5767 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5768 
5769 	kmem_free(buf, un->un_sys_blocksize);
5770 
5771 	mutex_enter(SD_MUTEX(un));
5772 	return (status);
5773 }
5774 
5775 
5776 /*
5777  *    Function: sd_check_vpd_page_support
5778  *
5779  * Description: This routine sends an inquiry command with the EVPD bit set and
5780  *		a page code of 0x00 to the device. It is used to determine which
5781  *		vital product pages are available to find the devid. We are
5782  *		looking for pages 0x83 0x80 or 0xB1.  If we return a negative 1,
5783  *		the device does not support that command.
5784  *
5785  *   Arguments: un  - driver soft state (unit) structure
5786  *
5787  * Return Code: 0 - success
5788  *		1 - check condition
5789  *
5790  *     Context: This routine can sleep.
5791  */
5792 
5793 static int
5794 sd_check_vpd_page_support(sd_ssc_t *ssc)
5795 {
5796 	uchar_t	*page_list	= NULL;
5797 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5798 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5799 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5800 	int	rval		= 0;
5801 	int	counter;
5802 	struct sd_lun		*un;
5803 
5804 	ASSERT(ssc != NULL);
5805 	un = ssc->ssc_un;
5806 	ASSERT(un != NULL);
5807 	ASSERT(mutex_owned(SD_MUTEX(un)));
5808 
5809 	mutex_exit(SD_MUTEX(un));
5810 
5811 	/*
5812 	 * We'll set the page length to the maximum to save figuring it out
5813 	 * with an additional call.
5814 	 */
5815 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5816 
5817 	rval = sd_send_scsi_INQUIRY(ssc, page_list, page_length, evpd,
5818 	    page_code, NULL);
5819 
5820 	if (rval != 0)
5821 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5822 
5823 	mutex_enter(SD_MUTEX(un));
5824 
5825 	/*
5826 	 * Now we must validate that the device accepted the command, as some
5827 	 * drives do not support it.  If the drive does support it, we will
5828 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5829 	 * not, we return -1.
5830 	 */
5831 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5832 		/* Loop to find one of the 2 pages we need */
5833 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5834 
5835 		/*
5836 		 * Pages are returned in ascending order, and 0x83 is what we
5837 		 * are hoping for.
5838 		 */
5839 		while ((page_list[counter] <= 0xB1) &&
5840 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5841 		    VPD_HEAD_OFFSET))) {
5842 			/*
5843 			 * Add 3 because page_list[3] is the number of
5844 			 * pages minus 3
5845 			 */
5846 
5847 			switch (page_list[counter]) {
5848 			case 0x00:
5849 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5850 				break;
5851 			case 0x80:
5852 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5853 				break;
5854 			case 0x81:
5855 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5856 				break;
5857 			case 0x82:
5858 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5859 				break;
5860 			case 0x83:
5861 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5862 				break;
5863 			case 0x86:
5864 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5865 				break;
5866 			case 0xB0:
5867 				un->un_vpd_page_mask |= SD_VPD_BLK_LIMITS_PG;
5868 				break;
5869 			case 0xB1:
5870 				un->un_vpd_page_mask |= SD_VPD_DEV_CHARACTER_PG;
5871 				break;
5872 			}
5873 			counter++;
5874 		}
5875 
5876 	} else {
5877 		rval = -1;
5878 
5879 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5880 		    "sd_check_vpd_page_support: This drive does not implement "
5881 		    "VPD pages.\n");
5882 	}
5883 
5884 	kmem_free(page_list, page_length);
5885 
5886 	return (rval);
5887 }
5888 
5889 
5890 /*
5891  *    Function: sd_setup_pm
5892  *
5893  * Description: Initialize Power Management on the device
5894  *
5895  *     Context: Kernel Thread
5896  */
5897 
5898 static void
5899 sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi)
5900 {
5901 	uint_t		log_page_size;
5902 	uchar_t		*log_page_data;
5903 	int		rval = 0;
5904 	struct sd_lun	*un;
5905 
5906 	ASSERT(ssc != NULL);
5907 	un = ssc->ssc_un;
5908 	ASSERT(un != NULL);
5909 
5910 	/*
5911 	 * Since we are called from attach, holding a mutex for
5912 	 * un is unnecessary. Because some of the routines called
5913 	 * from here require SD_MUTEX to not be held, assert this
5914 	 * right up front.
5915 	 */
5916 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5917 	/*
5918 	 * Since the sd device does not have the 'reg' property,
5919 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5920 	 * The following code is to tell cpr that this device
5921 	 * DOES need to be suspended and resumed.
5922 	 */
5923 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5924 	    "pm-hardware-state", "needs-suspend-resume");
5925 
5926 	/*
5927 	 * This complies with the new power management framework
5928 	 * for certain desktop machines. Create the pm_components
5929 	 * property as a string array property.
5930 	 * If un_f_pm_supported is TRUE, that means the disk
5931 	 * attached HBA has set the "pm-capable" property and
5932 	 * the value of this property is bigger than 0.
5933 	 */
5934 	if (un->un_f_pm_supported) {
5935 		/*
5936 		 * not all devices have a motor, try it first.
5937 		 * some devices may return ILLEGAL REQUEST, some
5938 		 * will hang
5939 		 * The following START_STOP_UNIT is used to check if target
5940 		 * device has a motor.
5941 		 */
5942 		un->un_f_start_stop_supported = TRUE;
5943 
5944 		if (un->un_f_power_condition_supported) {
5945 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5946 			    SD_POWER_CONDITION, SD_TARGET_ACTIVE,
5947 			    SD_PATH_DIRECT);
5948 			if (rval != 0) {
5949 				un->un_f_power_condition_supported = FALSE;
5950 			}
5951 		}
5952 		if (!un->un_f_power_condition_supported) {
5953 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5954 			    SD_START_STOP, SD_TARGET_START, SD_PATH_DIRECT);
5955 		}
5956 		if (rval != 0) {
5957 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5958 			un->un_f_start_stop_supported = FALSE;
5959 		}
5960 
5961 		/*
5962 		 * create pm properties anyways otherwise the parent can't
5963 		 * go to sleep
5964 		 */
5965 		un->un_f_pm_is_enabled = TRUE;
5966 		(void) sd_create_pm_components(devi, un);
5967 
5968 		/*
5969 		 * If it claims that log sense is supported, check it out.
5970 		 */
5971 		if (un->un_f_log_sense_supported) {
5972 			rval = sd_log_page_supported(ssc,
5973 			    START_STOP_CYCLE_PAGE);
5974 			if (rval == 1) {
5975 				/* Page found, use it. */
5976 				un->un_start_stop_cycle_page =
5977 				    START_STOP_CYCLE_PAGE;
5978 			} else {
5979 				/*
5980 				 * Page not found or log sense is not
5981 				 * supported.
5982 				 * Notice we do not check the old style
5983 				 * START_STOP_CYCLE_VU_PAGE because this
5984 				 * code path does not apply to old disks.
5985 				 */
5986 				un->un_f_log_sense_supported = FALSE;
5987 				un->un_f_pm_log_sense_smart = FALSE;
5988 			}
5989 		}
5990 
5991 		return;
5992 	}
5993 
5994 	/*
5995 	 * For the disk whose attached HBA has not set the "pm-capable"
5996 	 * property, check if it supports the power management.
5997 	 */
5998 	if (!un->un_f_log_sense_supported) {
5999 		un->un_power_level = SD_SPINDLE_ON;
6000 		un->un_f_pm_is_enabled = FALSE;
6001 		return;
6002 	}
6003 
6004 	rval = sd_log_page_supported(ssc, START_STOP_CYCLE_PAGE);
6005 
6006 #ifdef	SDDEBUG
6007 	if (sd_force_pm_supported) {
6008 		/* Force a successful result */
6009 		rval = 1;
6010 	}
6011 #endif
6012 
6013 	/*
6014 	 * If the start-stop cycle counter log page is not supported
6015 	 * or if the pm-capable property is set to be false (0),
6016 	 * then we should not create the pm_components property.
6017 	 */
6018 	if (rval == -1) {
6019 		/*
6020 		 * Error.
6021 		 * Reading log sense failed, most likely this is
6022 		 * an older drive that does not support log sense.
6023 		 * If this fails auto-pm is not supported.
6024 		 */
6025 		un->un_power_level = SD_SPINDLE_ON;
6026 		un->un_f_pm_is_enabled = FALSE;
6027 
6028 	} else if (rval == 0) {
6029 		/*
6030 		 * Page not found.
6031 		 * The start stop cycle counter is implemented as page
6032 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
6033 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
6034 		 */
6035 		if (sd_log_page_supported(ssc, START_STOP_CYCLE_VU_PAGE) == 1) {
6036 			/*
6037 			 * Page found, use this one.
6038 			 */
6039 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
6040 			un->un_f_pm_is_enabled = TRUE;
6041 		} else {
6042 			/*
6043 			 * Error or page not found.
6044 			 * auto-pm is not supported for this device.
6045 			 */
6046 			un->un_power_level = SD_SPINDLE_ON;
6047 			un->un_f_pm_is_enabled = FALSE;
6048 		}
6049 	} else {
6050 		/*
6051 		 * Page found, use it.
6052 		 */
6053 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
6054 		un->un_f_pm_is_enabled = TRUE;
6055 	}
6056 
6057 
6058 	if (un->un_f_pm_is_enabled == TRUE) {
6059 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6060 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6061 
6062 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6063 		    log_page_size, un->un_start_stop_cycle_page,
6064 		    0x01, 0, SD_PATH_DIRECT);
6065 
6066 		if (rval != 0) {
6067 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6068 		}
6069 
6070 #ifdef	SDDEBUG
6071 		if (sd_force_pm_supported) {
6072 			/* Force a successful result */
6073 			rval = 0;
6074 		}
6075 #endif
6076 
6077 		/*
6078 		 * If the Log sense for Page( Start/stop cycle counter page)
6079 		 * succeeds, then power management is supported and we can
6080 		 * enable auto-pm.
6081 		 */
6082 		if (rval == 0)  {
6083 			(void) sd_create_pm_components(devi, un);
6084 		} else {
6085 			un->un_power_level = SD_SPINDLE_ON;
6086 			un->un_f_pm_is_enabled = FALSE;
6087 		}
6088 
6089 		kmem_free(log_page_data, log_page_size);
6090 	}
6091 }
6092 
6093 
6094 /*
6095  *    Function: sd_create_pm_components
6096  *
6097  * Description: Initialize PM property.
6098  *
6099  *     Context: Kernel thread context
6100  */
6101 
6102 static void
6103 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
6104 {
6105 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6106 
6107 	if (un->un_f_power_condition_supported) {
6108 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6109 		    "pm-components", sd_pwr_pc.pm_comp, 5)
6110 		    != DDI_PROP_SUCCESS) {
6111 			un->un_power_level = SD_SPINDLE_ACTIVE;
6112 			un->un_f_pm_is_enabled = FALSE;
6113 			return;
6114 		}
6115 	} else {
6116 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6117 		    "pm-components", sd_pwr_ss.pm_comp, 3)
6118 		    != DDI_PROP_SUCCESS) {
6119 			un->un_power_level = SD_SPINDLE_ON;
6120 			un->un_f_pm_is_enabled = FALSE;
6121 			return;
6122 		}
6123 	}
6124 	/*
6125 	 * When components are initially created they are idle,
6126 	 * power up any non-removables.
6127 	 * Note: the return value of pm_raise_power can't be used
6128 	 * for determining if PM should be enabled for this device.
6129 	 * Even if you check the return values and remove this
6130 	 * property created above, the PM framework will not honor the
6131 	 * change after the first call to pm_raise_power. Hence,
6132 	 * removal of that property does not help if pm_raise_power
6133 	 * fails. In the case of removable media, the start/stop
6134 	 * will fail if the media is not present.
6135 	 */
6136 	if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
6137 	    SD_PM_STATE_ACTIVE(un)) == DDI_SUCCESS)) {
6138 		mutex_enter(SD_MUTEX(un));
6139 		un->un_power_level = SD_PM_STATE_ACTIVE(un);
6140 		mutex_enter(&un->un_pm_mutex);
6141 		/* Set to on and not busy. */
6142 		un->un_pm_count = 0;
6143 	} else {
6144 		mutex_enter(SD_MUTEX(un));
6145 		un->un_power_level = SD_PM_STATE_STOPPED(un);
6146 		mutex_enter(&un->un_pm_mutex);
6147 		/* Set to off. */
6148 		un->un_pm_count = -1;
6149 	}
6150 	mutex_exit(&un->un_pm_mutex);
6151 	mutex_exit(SD_MUTEX(un));
6152 }
6153 
6154 
6155 /*
6156  *    Function: sd_ddi_suspend
6157  *
6158  * Description: Performs system power-down operations. This includes
6159  *		setting the drive state to indicate its suspended so
6160  *		that no new commands will be accepted. Also, wait for
6161  *		all commands that are in transport or queued to a timer
6162  *		for retry to complete. All timeout threads are cancelled.
6163  *
6164  * Return Code: DDI_FAILURE or DDI_SUCCESS
6165  *
6166  *     Context: Kernel thread context
6167  */
6168 
6169 static int
6170 sd_ddi_suspend(dev_info_t *devi)
6171 {
6172 	struct	sd_lun	*un;
6173 	clock_t		wait_cmds_complete;
6174 
6175 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6176 	if (un == NULL) {
6177 		return (DDI_FAILURE);
6178 	}
6179 
6180 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
6181 
6182 	mutex_enter(SD_MUTEX(un));
6183 
6184 	/* Return success if the device is already suspended. */
6185 	if (un->un_state == SD_STATE_SUSPENDED) {
6186 		mutex_exit(SD_MUTEX(un));
6187 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6188 		    "device already suspended, exiting\n");
6189 		return (DDI_SUCCESS);
6190 	}
6191 
6192 	/* Return failure if the device is being used by HA */
6193 	if (un->un_resvd_status &
6194 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
6195 		mutex_exit(SD_MUTEX(un));
6196 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6197 		    "device in use by HA, exiting\n");
6198 		return (DDI_FAILURE);
6199 	}
6200 
6201 	/*
6202 	 * Return failure if the device is in a resource wait
6203 	 * or power changing state.
6204 	 */
6205 	if ((un->un_state == SD_STATE_RWAIT) ||
6206 	    (un->un_state == SD_STATE_PM_CHANGING)) {
6207 		mutex_exit(SD_MUTEX(un));
6208 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6209 		    "device in resource wait state, exiting\n");
6210 		return (DDI_FAILURE);
6211 	}
6212 
6213 
6214 	un->un_save_state = un->un_last_state;
6215 	New_state(un, SD_STATE_SUSPENDED);
6216 
6217 	/*
6218 	 * Wait for all commands that are in transport or queued to a timer
6219 	 * for retry to complete.
6220 	 *
6221 	 * While waiting, no new commands will be accepted or sent because of
6222 	 * the new state we set above.
6223 	 *
6224 	 * Wait till current operation has completed. If we are in the resource
6225 	 * wait state (with an intr outstanding) then we need to wait till the
6226 	 * intr completes and starts the next cmd. We want to wait for
6227 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
6228 	 */
6229 	wait_cmds_complete = ddi_get_lbolt() +
6230 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
6231 
6232 	while (un->un_ncmds_in_transport != 0) {
6233 		/*
6234 		 * Fail if commands do not finish in the specified time.
6235 		 */
6236 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
6237 		    wait_cmds_complete) == -1) {
6238 			/*
6239 			 * Undo the state changes made above. Everything
6240 			 * must go back to it's original value.
6241 			 */
6242 			Restore_state(un);
6243 			un->un_last_state = un->un_save_state;
6244 			/* Wake up any threads that might be waiting. */
6245 			cv_broadcast(&un->un_suspend_cv);
6246 			mutex_exit(SD_MUTEX(un));
6247 			SD_ERROR(SD_LOG_IO_PM, un,
6248 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
6249 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
6250 			return (DDI_FAILURE);
6251 		}
6252 	}
6253 
6254 	/*
6255 	 * Cancel SCSI watch thread and timeouts, if any are active
6256 	 */
6257 
6258 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
6259 		opaque_t temp_token = un->un_swr_token;
6260 		mutex_exit(SD_MUTEX(un));
6261 		scsi_watch_suspend(temp_token);
6262 		mutex_enter(SD_MUTEX(un));
6263 	}
6264 
6265 	if (un->un_reset_throttle_timeid != NULL) {
6266 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
6267 		un->un_reset_throttle_timeid = NULL;
6268 		mutex_exit(SD_MUTEX(un));
6269 		(void) untimeout(temp_id);
6270 		mutex_enter(SD_MUTEX(un));
6271 	}
6272 
6273 	if (un->un_dcvb_timeid != NULL) {
6274 		timeout_id_t temp_id = un->un_dcvb_timeid;
6275 		un->un_dcvb_timeid = NULL;
6276 		mutex_exit(SD_MUTEX(un));
6277 		(void) untimeout(temp_id);
6278 		mutex_enter(SD_MUTEX(un));
6279 	}
6280 
6281 	mutex_enter(&un->un_pm_mutex);
6282 	if (un->un_pm_timeid != NULL) {
6283 		timeout_id_t temp_id = un->un_pm_timeid;
6284 		un->un_pm_timeid = NULL;
6285 		mutex_exit(&un->un_pm_mutex);
6286 		mutex_exit(SD_MUTEX(un));
6287 		(void) untimeout(temp_id);
6288 		mutex_enter(SD_MUTEX(un));
6289 	} else {
6290 		mutex_exit(&un->un_pm_mutex);
6291 	}
6292 
6293 	if (un->un_rmw_msg_timeid != NULL) {
6294 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
6295 		un->un_rmw_msg_timeid = NULL;
6296 		mutex_exit(SD_MUTEX(un));
6297 		(void) untimeout(temp_id);
6298 		mutex_enter(SD_MUTEX(un));
6299 	}
6300 
6301 	if (un->un_retry_timeid != NULL) {
6302 		timeout_id_t temp_id = un->un_retry_timeid;
6303 		un->un_retry_timeid = NULL;
6304 		mutex_exit(SD_MUTEX(un));
6305 		(void) untimeout(temp_id);
6306 		mutex_enter(SD_MUTEX(un));
6307 
6308 		if (un->un_retry_bp != NULL) {
6309 			un->un_retry_bp->av_forw = un->un_waitq_headp;
6310 			un->un_waitq_headp = un->un_retry_bp;
6311 			if (un->un_waitq_tailp == NULL) {
6312 				un->un_waitq_tailp = un->un_retry_bp;
6313 			}
6314 			un->un_retry_bp = NULL;
6315 			un->un_retry_statp = NULL;
6316 		}
6317 	}
6318 
6319 	if (un->un_direct_priority_timeid != NULL) {
6320 		timeout_id_t temp_id = un->un_direct_priority_timeid;
6321 		un->un_direct_priority_timeid = NULL;
6322 		mutex_exit(SD_MUTEX(un));
6323 		(void) untimeout(temp_id);
6324 		mutex_enter(SD_MUTEX(un));
6325 	}
6326 
6327 	if (un->un_f_is_fibre == TRUE) {
6328 		/*
6329 		 * Remove callbacks for insert and remove events
6330 		 */
6331 		if (un->un_insert_event != NULL) {
6332 			mutex_exit(SD_MUTEX(un));
6333 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
6334 			mutex_enter(SD_MUTEX(un));
6335 			un->un_insert_event = NULL;
6336 		}
6337 
6338 		if (un->un_remove_event != NULL) {
6339 			mutex_exit(SD_MUTEX(un));
6340 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
6341 			mutex_enter(SD_MUTEX(un));
6342 			un->un_remove_event = NULL;
6343 		}
6344 	}
6345 
6346 	mutex_exit(SD_MUTEX(un));
6347 
6348 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
6349 
6350 	return (DDI_SUCCESS);
6351 }
6352 
6353 
6354 /*
6355  *    Function: sd_ddi_resume
6356  *
6357  * Description: Performs system power-up operations..
6358  *
6359  * Return Code: DDI_SUCCESS
6360  *		DDI_FAILURE
6361  *
6362  *     Context: Kernel thread context
6363  */
6364 
6365 static int
6366 sd_ddi_resume(dev_info_t *devi)
6367 {
6368 	struct	sd_lun	*un;
6369 
6370 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6371 	if (un == NULL) {
6372 		return (DDI_FAILURE);
6373 	}
6374 
6375 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6376 
6377 	mutex_enter(SD_MUTEX(un));
6378 	Restore_state(un);
6379 
6380 	/*
6381 	 * Restore the state which was saved to give the
6382 	 * the right state in un_last_state
6383 	 */
6384 	un->un_last_state = un->un_save_state;
6385 	/*
6386 	 * Note: throttle comes back at full.
6387 	 * Also note: this MUST be done before calling pm_raise_power
6388 	 * otherwise the system can get hung in biowait. The scenario where
6389 	 * this'll happen is under cpr suspend. Writing of the system
6390 	 * state goes through sddump, which writes 0 to un_throttle. If
6391 	 * writing the system state then fails, example if the partition is
6392 	 * too small, then cpr attempts a resume. If throttle isn't restored
6393 	 * from the saved value until after calling pm_raise_power then
6394 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6395 	 * in biowait.
6396 	 */
6397 	un->un_throttle = un->un_saved_throttle;
6398 
6399 	/*
6400 	 * The chance of failure is very rare as the only command done in power
6401 	 * entry point is START command when you transition from 0->1 or
6402 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6403 	 * which suspend was done. Ignore the return value as the resume should
6404 	 * not be failed. In the case of removable media the media need not be
6405 	 * inserted and hence there is a chance that raise power will fail with
6406 	 * media not present.
6407 	 */
6408 	if (un->un_f_attach_spinup) {
6409 		mutex_exit(SD_MUTEX(un));
6410 		(void) pm_raise_power(SD_DEVINFO(un), 0,
6411 		    SD_PM_STATE_ACTIVE(un));
6412 		mutex_enter(SD_MUTEX(un));
6413 	}
6414 
6415 	/*
6416 	 * Don't broadcast to the suspend cv and therefore possibly
6417 	 * start I/O until after power has been restored.
6418 	 */
6419 	cv_broadcast(&un->un_suspend_cv);
6420 	cv_broadcast(&un->un_state_cv);
6421 
6422 	/* restart thread */
6423 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6424 		scsi_watch_resume(un->un_swr_token);
6425 	}
6426 
6427 #if (defined(__fibre))
6428 	if (un->un_f_is_fibre == TRUE) {
6429 		/*
6430 		 * Add callbacks for insert and remove events
6431 		 */
6432 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6433 			sd_init_event_callbacks(un);
6434 		}
6435 	}
6436 #endif
6437 
6438 	/*
6439 	 * Transport any pending commands to the target.
6440 	 *
6441 	 * If this is a low-activity device commands in queue will have to wait
6442 	 * until new commands come in, which may take awhile. Also, we
6443 	 * specifically don't check un_ncmds_in_transport because we know that
6444 	 * there really are no commands in progress after the unit was
6445 	 * suspended and we could have reached the throttle level, been
6446 	 * suspended, and have no new commands coming in for awhile. Highly
6447 	 * unlikely, but so is the low-activity disk scenario.
6448 	 */
6449 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6450 
6451 	sd_start_cmds(un, NULL);
6452 	mutex_exit(SD_MUTEX(un));
6453 
6454 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6455 
6456 	return (DDI_SUCCESS);
6457 }
6458 
6459 
6460 /*
6461  *    Function: sd_pm_state_change
6462  *
6463  * Description: Change the driver power state.
6464  *		Someone else is required to actually change the driver
6465  *		power level.
6466  *
6467  *   Arguments: un - driver soft state (unit) structure
6468  *              level - the power level that is changed to
6469  *              flag - to decide how to change the power state
6470  *
6471  * Return Code: DDI_SUCCESS
6472  *
6473  *     Context: Kernel thread context
6474  */
6475 static int
6476 sd_pm_state_change(struct sd_lun *un, int level, int flag)
6477 {
6478 	ASSERT(un != NULL);
6479 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: entry\n");
6480 
6481 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6482 	mutex_enter(SD_MUTEX(un));
6483 
6484 	if (flag == SD_PM_STATE_ROLLBACK || SD_PM_IS_IO_CAPABLE(un, level)) {
6485 		un->un_power_level = level;
6486 		ASSERT(!mutex_owned(&un->un_pm_mutex));
6487 		mutex_enter(&un->un_pm_mutex);
6488 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6489 			un->un_pm_count++;
6490 			ASSERT(un->un_pm_count == 0);
6491 		}
6492 		mutex_exit(&un->un_pm_mutex);
6493 	} else {
6494 		/*
6495 		 * Exit if power management is not enabled for this device,
6496 		 * or if the device is being used by HA.
6497 		 */
6498 		if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
6499 		    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
6500 			mutex_exit(SD_MUTEX(un));
6501 			SD_TRACE(SD_LOG_POWER, un,
6502 			    "sd_pm_state_change: exiting\n");
6503 			return (DDI_FAILURE);
6504 		}
6505 
6506 		SD_INFO(SD_LOG_POWER, un, "sd_pm_state_change: "
6507 		    "un_ncmds_in_driver=%ld\n", un->un_ncmds_in_driver);
6508 
6509 		/*
6510 		 * See if the device is not busy, ie.:
6511 		 *    - we have no commands in the driver for this device
6512 		 *    - not waiting for resources
6513 		 */
6514 		if ((un->un_ncmds_in_driver == 0) &&
6515 		    (un->un_state != SD_STATE_RWAIT)) {
6516 			/*
6517 			 * The device is not busy, so it is OK to go to low
6518 			 * power state. Indicate low power, but rely on someone
6519 			 * else to actually change it.
6520 			 */
6521 			mutex_enter(&un->un_pm_mutex);
6522 			un->un_pm_count = -1;
6523 			mutex_exit(&un->un_pm_mutex);
6524 			un->un_power_level = level;
6525 		}
6526 	}
6527 
6528 	mutex_exit(SD_MUTEX(un));
6529 
6530 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: exit\n");
6531 
6532 	return (DDI_SUCCESS);
6533 }
6534 
6535 
6536 /*
6537  *    Function: sd_pm_idletimeout_handler
6538  *
6539  * Description: A timer routine that's active only while a device is busy.
6540  *		The purpose is to extend slightly the pm framework's busy
6541  *		view of the device to prevent busy/idle thrashing for
6542  *		back-to-back commands. Do this by comparing the current time
6543  *		to the time at which the last command completed and when the
6544  *		difference is greater than sd_pm_idletime, call
6545  *		pm_idle_component. In addition to indicating idle to the pm
6546  *		framework, update the chain type to again use the internal pm
6547  *		layers of the driver.
6548  *
6549  *   Arguments: arg - driver soft state (unit) structure
6550  *
6551  *     Context: Executes in a timeout(9F) thread context
6552  */
6553 
6554 static void
6555 sd_pm_idletimeout_handler(void *arg)
6556 {
6557 	const hrtime_t idletime = sd_pm_idletime * NANOSEC;
6558 	struct sd_lun *un = arg;
6559 
6560 	/*
6561 	 * Grab both mutexes, in the proper order, since we're accessing
6562 	 * both PM and softstate variables.
6563 	 */
6564 	mutex_enter(SD_MUTEX(un));
6565 	mutex_enter(&un->un_pm_mutex);
6566 	/* if timeout id is NULL, we are being canceled via untimeout */
6567 	if (un->un_pm_idle_timeid == NULL) {
6568 		mutex_exit(&un->un_pm_mutex);
6569 		mutex_exit(SD_MUTEX(un));
6570 		return;
6571 	}
6572 	if (((gethrtime() - un->un_pm_idle_time) > idletime) &&
6573 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
6574 		/*
6575 		 * Update the chain types.
6576 		 * This takes affect on the next new command received.
6577 		 */
6578 		if (un->un_f_non_devbsize_supported) {
6579 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6580 		} else {
6581 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6582 		}
6583 		un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD;
6584 
6585 		SD_TRACE(SD_LOG_IO_PM, un,
6586 		    "sd_pm_idletimeout_handler: idling device\n");
6587 		(void) pm_idle_component(SD_DEVINFO(un), 0);
6588 		un->un_pm_idle_timeid = NULL;
6589 	} else {
6590 		un->un_pm_idle_timeid =
6591 		    timeout(sd_pm_idletimeout_handler, un,
6592 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
6593 	}
6594 	mutex_exit(&un->un_pm_mutex);
6595 	mutex_exit(SD_MUTEX(un));
6596 }
6597 
6598 
6599 /*
6600  *    Function: sd_pm_timeout_handler
6601  *
6602  * Description: Callback to tell framework we are idle.
6603  *
6604  *     Context: timeout(9f) thread context.
6605  */
6606 
6607 static void
6608 sd_pm_timeout_handler(void *arg)
6609 {
6610 	struct sd_lun *un = arg;
6611 
6612 	(void) pm_idle_component(SD_DEVINFO(un), 0);
6613 	mutex_enter(&un->un_pm_mutex);
6614 	un->un_pm_timeid = NULL;
6615 	mutex_exit(&un->un_pm_mutex);
6616 }
6617 
6618 
6619 /*
6620  *    Function: sdpower
6621  *
6622  * Description: PM entry point.
6623  *
6624  * Return Code: DDI_SUCCESS
6625  *		DDI_FAILURE
6626  *
6627  *     Context: Kernel thread context
6628  */
6629 
6630 static int
6631 sdpower(dev_info_t *devi, int component, int level)
6632 {
6633 	struct sd_lun	*un;
6634 	int		instance;
6635 	int		rval = DDI_SUCCESS;
6636 	uint_t		i, log_page_size, maxcycles, ncycles;
6637 	uchar_t		*log_page_data;
6638 	int		log_sense_page;
6639 	int		medium_present;
6640 	time_t		intvlp;
6641 	struct pm_trans_data	sd_pm_tran_data;
6642 	uchar_t		save_state = SD_STATE_NORMAL;
6643 	int		sval;
6644 	uchar_t		state_before_pm;
6645 	sd_ssc_t	*ssc;
6646 	int	last_power_level = SD_SPINDLE_UNINIT;
6647 
6648 	instance = ddi_get_instance(devi);
6649 
6650 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
6651 	    !SD_PM_IS_LEVEL_VALID(un, level) || component != 0) {
6652 		return (DDI_FAILURE);
6653 	}
6654 
6655 	ssc = sd_ssc_init(un);
6656 
6657 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
6658 
6659 	mutex_enter(SD_MUTEX(un));
6660 
6661 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
6662 	    un->un_ncmds_in_driver);
6663 
6664 	/*
6665 	 * If un_ncmds_in_driver is non-zero it indicates commands are
6666 	 * already being processed in the driver.
6667 	 * At the same time somebody is requesting to go to a lower power
6668 	 * that can't perform I/O, which can't happen, therefore we need to
6669 	 * return failure.
6670 	 */
6671 	if ((!SD_PM_IS_IO_CAPABLE(un, level)) &&
6672 	    (un->un_ncmds_in_driver != 0)) {
6673 		mutex_exit(SD_MUTEX(un));
6674 
6675 		SD_TRACE(SD_LOG_IO_PM, un,
6676 		    "sdpower: exit, device has queued cmds.\n");
6677 
6678 		goto sdpower_failed;
6679 	}
6680 
6681 	/*
6682 	 * if it is OFFLINE that means the disk is completely dead
6683 	 * in our case we have to put the disk in on or off by sending commands
6684 	 * Of course that will fail anyway so return back here.
6685 	 *
6686 	 * Power changes to a device that's OFFLINE or SUSPENDED
6687 	 * are not allowed.
6688 	 */
6689 	if ((un->un_state == SD_STATE_OFFLINE) ||
6690 	    (un->un_state == SD_STATE_SUSPENDED)) {
6691 		mutex_exit(SD_MUTEX(un));
6692 
6693 		SD_TRACE(SD_LOG_IO_PM, un,
6694 		    "sdpower: exit, device is off-line.\n");
6695 
6696 		goto sdpower_failed;
6697 	}
6698 
6699 	/*
6700 	 * Change the device's state to indicate it's power level
6701 	 * is being changed. Do this to prevent a power off in the
6702 	 * middle of commands, which is especially bad on devices
6703 	 * that are really powered off instead of just spun down.
6704 	 */
6705 	state_before_pm = un->un_state;
6706 	un->un_state = SD_STATE_PM_CHANGING;
6707 
6708 	mutex_exit(SD_MUTEX(un));
6709 
6710 	/*
6711 	 * If log sense command is not supported, bypass the
6712 	 * following checking, otherwise, check the log sense
6713 	 * information for this device.
6714 	 */
6715 	if (SD_PM_STOP_MOTOR_NEEDED(un, level) &&
6716 	    un->un_f_log_sense_supported) {
6717 		/*
6718 		 * Get the log sense information to understand whether the
6719 		 * the powercycle counts have gone beyond the threshhold.
6720 		 */
6721 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6722 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6723 
6724 		mutex_enter(SD_MUTEX(un));
6725 		log_sense_page = un->un_start_stop_cycle_page;
6726 		mutex_exit(SD_MUTEX(un));
6727 
6728 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6729 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
6730 
6731 		if (rval != 0) {
6732 			if (rval == EIO)
6733 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6734 			else
6735 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6736 		}
6737 
6738 #ifdef	SDDEBUG
6739 		if (sd_force_pm_supported) {
6740 			/* Force a successful result */
6741 			rval = 0;
6742 		}
6743 #endif
6744 		if (rval != 0) {
6745 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
6746 			    "Log Sense Failed\n");
6747 
6748 			kmem_free(log_page_data, log_page_size);
6749 			/* Cannot support power management on those drives */
6750 
6751 			/*
6752 			 * On exit put the state back to it's original value
6753 			 * and broadcast to anyone waiting for the power
6754 			 * change completion.
6755 			 */
6756 			mutex_enter(SD_MUTEX(un));
6757 			un->un_state = state_before_pm;
6758 			cv_broadcast(&un->un_suspend_cv);
6759 			mutex_exit(SD_MUTEX(un));
6760 			SD_TRACE(SD_LOG_IO_PM, un,
6761 			    "sdpower: exit, Log Sense Failed.\n");
6762 
6763 			goto sdpower_failed;
6764 		}
6765 
6766 		/*
6767 		 * From the page data - Convert the essential information to
6768 		 * pm_trans_data
6769 		 */
6770 		maxcycles =
6771 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
6772 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
6773 
6774 		ncycles =
6775 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6776 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6777 
6778 		if (un->un_f_pm_log_sense_smart) {
6779 			sd_pm_tran_data.un.smart_count.allowed = maxcycles;
6780 			sd_pm_tran_data.un.smart_count.consumed = ncycles;
6781 			sd_pm_tran_data.un.smart_count.flag = 0;
6782 			sd_pm_tran_data.format = DC_SMART_FORMAT;
6783 		} else {
6784 			sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6785 			sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6786 			for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6787 				sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6788 				    log_page_data[8+i];
6789 			}
6790 			sd_pm_tran_data.un.scsi_cycles.flag = 0;
6791 			sd_pm_tran_data.format = DC_SCSI_FORMAT;
6792 		}
6793 
6794 		kmem_free(log_page_data, log_page_size);
6795 
6796 		/*
6797 		 * Call pm_trans_check routine to get the Ok from
6798 		 * the global policy
6799 		 */
6800 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6801 #ifdef	SDDEBUG
6802 		if (sd_force_pm_supported) {
6803 			/* Force a successful result */
6804 			rval = 1;
6805 		}
6806 #endif
6807 		switch (rval) {
6808 		case 0:
6809 			/*
6810 			 * Not Ok to Power cycle or error in parameters passed
6811 			 * Would have given the advised time to consider power
6812 			 * cycle. Based on the new intvlp parameter we are
6813 			 * supposed to pretend we are busy so that pm framework
6814 			 * will never call our power entry point. Because of
6815 			 * that install a timeout handler and wait for the
6816 			 * recommended time to elapse so that power management
6817 			 * can be effective again.
6818 			 *
6819 			 * To effect this behavior, call pm_busy_component to
6820 			 * indicate to the framework this device is busy.
6821 			 * By not adjusting un_pm_count the rest of PM in
6822 			 * the driver will function normally, and independent
6823 			 * of this but because the framework is told the device
6824 			 * is busy it won't attempt powering down until it gets
6825 			 * a matching idle. The timeout handler sends this.
6826 			 * Note: sd_pm_entry can't be called here to do this
6827 			 * because sdpower may have been called as a result
6828 			 * of a call to pm_raise_power from within sd_pm_entry.
6829 			 *
6830 			 * If a timeout handler is already active then
6831 			 * don't install another.
6832 			 */
6833 			mutex_enter(&un->un_pm_mutex);
6834 			if (un->un_pm_timeid == NULL) {
6835 				un->un_pm_timeid =
6836 				    timeout(sd_pm_timeout_handler,
6837 				    un, intvlp * drv_usectohz(1000000));
6838 				mutex_exit(&un->un_pm_mutex);
6839 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6840 			} else {
6841 				mutex_exit(&un->un_pm_mutex);
6842 			}
6843 			/*
6844 			 * On exit put the state back to its original value
6845 			 * and broadcast to anyone waiting for the power
6846 			 * change completion.
6847 			 */
6848 			mutex_enter(SD_MUTEX(un));
6849 			un->un_state = state_before_pm;
6850 			cv_broadcast(&un->un_suspend_cv);
6851 			mutex_exit(SD_MUTEX(un));
6852 
6853 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6854 			    "trans check Failed, not ok to power cycle.\n");
6855 
6856 			goto sdpower_failed;
6857 		case -1:
6858 			/*
6859 			 * On exit put the state back to its original value
6860 			 * and broadcast to anyone waiting for the power
6861 			 * change completion.
6862 			 */
6863 			mutex_enter(SD_MUTEX(un));
6864 			un->un_state = state_before_pm;
6865 			cv_broadcast(&un->un_suspend_cv);
6866 			mutex_exit(SD_MUTEX(un));
6867 			SD_TRACE(SD_LOG_IO_PM, un,
6868 			    "sdpower: exit, trans check command Failed.\n");
6869 
6870 			goto sdpower_failed;
6871 		}
6872 	}
6873 
6874 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6875 		/*
6876 		 * Save the last state... if the STOP FAILS we need it
6877 		 * for restoring
6878 		 */
6879 		mutex_enter(SD_MUTEX(un));
6880 		save_state = un->un_last_state;
6881 		last_power_level = un->un_power_level;
6882 		/*
6883 		 * There must not be any cmds. getting processed
6884 		 * in the driver when we get here. Power to the
6885 		 * device is potentially going off.
6886 		 */
6887 		ASSERT(un->un_ncmds_in_driver == 0);
6888 		mutex_exit(SD_MUTEX(un));
6889 
6890 		/*
6891 		 * For now PM suspend the device completely before spindle is
6892 		 * turned off
6893 		 */
6894 		if ((rval = sd_pm_state_change(un, level, SD_PM_STATE_CHANGE))
6895 		    == DDI_FAILURE) {
6896 			/*
6897 			 * On exit put the state back to its original value
6898 			 * and broadcast to anyone waiting for the power
6899 			 * change completion.
6900 			 */
6901 			mutex_enter(SD_MUTEX(un));
6902 			un->un_state = state_before_pm;
6903 			un->un_power_level = last_power_level;
6904 			cv_broadcast(&un->un_suspend_cv);
6905 			mutex_exit(SD_MUTEX(un));
6906 			SD_TRACE(SD_LOG_IO_PM, un,
6907 			    "sdpower: exit, PM suspend Failed.\n");
6908 
6909 			goto sdpower_failed;
6910 		}
6911 	}
6912 
6913 	/*
6914 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6915 	 * close, or strategy. Dump no long uses this routine, it uses it's
6916 	 * own code so it can be done in polled mode.
6917 	 */
6918 
6919 	medium_present = TRUE;
6920 
6921 	/*
6922 	 * When powering up, issue a TUR in case the device is at unit
6923 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6924 	 * a deadlock on un_pm_busy_cv will occur.
6925 	 */
6926 	if (SD_PM_IS_IO_CAPABLE(un, level)) {
6927 		sval = sd_send_scsi_TEST_UNIT_READY(ssc,
6928 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6929 		if (sval != 0)
6930 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6931 	}
6932 
6933 	if (un->un_f_power_condition_supported) {
6934 		char *pm_condition_name[] = {"STOPPED", "STANDBY",
6935 		    "IDLE", "ACTIVE"};
6936 		SD_TRACE(SD_LOG_IO_PM, un,
6937 		    "sdpower: sending \'%s\' power condition",
6938 		    pm_condition_name[level]);
6939 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
6940 		    sd_pl2pc[level], SD_PATH_DIRECT);
6941 	} else {
6942 		SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6943 		    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6944 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
6945 		    ((level == SD_SPINDLE_ON) ? SD_TARGET_START :
6946 		    SD_TARGET_STOP), SD_PATH_DIRECT);
6947 	}
6948 	if (sval != 0) {
6949 		if (sval == EIO)
6950 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6951 		else
6952 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6953 	}
6954 
6955 	/* Command failed, check for media present. */
6956 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6957 		medium_present = FALSE;
6958 	}
6959 
6960 	/*
6961 	 * The conditions of interest here are:
6962 	 *   if a spindle off with media present fails,
6963 	 *	then restore the state and return an error.
6964 	 *   else if a spindle on fails,
6965 	 *	then return an error (there's no state to restore).
6966 	 * In all other cases we setup for the new state
6967 	 * and return success.
6968 	 */
6969 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6970 		if ((medium_present == TRUE) && (sval != 0)) {
6971 			/* The stop command from above failed */
6972 			rval = DDI_FAILURE;
6973 			/*
6974 			 * The stop command failed, and we have media
6975 			 * present. Put the level back by calling the
6976 			 * sd_pm_resume() and set the state back to
6977 			 * it's previous value.
6978 			 */
6979 			(void) sd_pm_state_change(un, last_power_level,
6980 			    SD_PM_STATE_ROLLBACK);
6981 			mutex_enter(SD_MUTEX(un));
6982 			un->un_last_state = save_state;
6983 			mutex_exit(SD_MUTEX(un));
6984 		} else if (un->un_f_monitor_media_state) {
6985 			/*
6986 			 * The stop command from above succeeded.
6987 			 * Terminate watch thread in case of removable media
6988 			 * devices going into low power state. This is as per
6989 			 * the requirements of pm framework, otherwise commands
6990 			 * will be generated for the device (through watch
6991 			 * thread), even when the device is in low power state.
6992 			 */
6993 			mutex_enter(SD_MUTEX(un));
6994 			un->un_f_watcht_stopped = FALSE;
6995 			if (un->un_swr_token != NULL) {
6996 				opaque_t temp_token = un->un_swr_token;
6997 				un->un_f_watcht_stopped = TRUE;
6998 				un->un_swr_token = NULL;
6999 				mutex_exit(SD_MUTEX(un));
7000 				(void) scsi_watch_request_terminate(temp_token,
7001 				    SCSI_WATCH_TERMINATE_ALL_WAIT);
7002 			} else {
7003 				mutex_exit(SD_MUTEX(un));
7004 			}
7005 		}
7006 	} else {
7007 		/*
7008 		 * The level requested is I/O capable.
7009 		 * Legacy behavior: return success on a failed spinup
7010 		 * if there is no media in the drive.
7011 		 * Do this by looking at medium_present here.
7012 		 */
7013 		if ((sval != 0) && medium_present) {
7014 			/* The start command from above failed */
7015 			rval = DDI_FAILURE;
7016 		} else {
7017 			/*
7018 			 * The start command from above succeeded
7019 			 * PM resume the devices now that we have
7020 			 * started the disks
7021 			 */
7022 			(void) sd_pm_state_change(un, level,
7023 			    SD_PM_STATE_CHANGE);
7024 
7025 			/*
7026 			 * Resume the watch thread since it was suspended
7027 			 * when the device went into low power mode.
7028 			 */
7029 			if (un->un_f_monitor_media_state) {
7030 				mutex_enter(SD_MUTEX(un));
7031 				if (un->un_f_watcht_stopped == TRUE) {
7032 					opaque_t temp_token;
7033 
7034 					un->un_f_watcht_stopped = FALSE;
7035 					mutex_exit(SD_MUTEX(un));
7036 					temp_token =
7037 					    sd_watch_request_submit(un);
7038 					mutex_enter(SD_MUTEX(un));
7039 					un->un_swr_token = temp_token;
7040 				}
7041 				mutex_exit(SD_MUTEX(un));
7042 			}
7043 		}
7044 	}
7045 
7046 	/*
7047 	 * On exit put the state back to its original value
7048 	 * and broadcast to anyone waiting for the power
7049 	 * change completion.
7050 	 */
7051 	mutex_enter(SD_MUTEX(un));
7052 	un->un_state = state_before_pm;
7053 	cv_broadcast(&un->un_suspend_cv);
7054 	mutex_exit(SD_MUTEX(un));
7055 
7056 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
7057 
7058 	sd_ssc_fini(ssc);
7059 	return (rval);
7060 
7061 sdpower_failed:
7062 
7063 	sd_ssc_fini(ssc);
7064 	return (DDI_FAILURE);
7065 }
7066 
7067 
7068 
7069 /*
7070  *    Function: sdattach
7071  *
7072  * Description: Driver's attach(9e) entry point function.
7073  *
7074  *   Arguments: devi - opaque device info handle
7075  *		cmd  - attach  type
7076  *
7077  * Return Code: DDI_SUCCESS
7078  *		DDI_FAILURE
7079  *
7080  *     Context: Kernel thread context
7081  */
7082 
7083 static int
7084 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
7085 {
7086 	switch (cmd) {
7087 	case DDI_ATTACH:
7088 		return (sd_unit_attach(devi));
7089 	case DDI_RESUME:
7090 		return (sd_ddi_resume(devi));
7091 	default:
7092 		break;
7093 	}
7094 	return (DDI_FAILURE);
7095 }
7096 
7097 
7098 /*
7099  *    Function: sddetach
7100  *
7101  * Description: Driver's detach(9E) entry point function.
7102  *
7103  *   Arguments: devi - opaque device info handle
7104  *		cmd  - detach  type
7105  *
7106  * Return Code: DDI_SUCCESS
7107  *		DDI_FAILURE
7108  *
7109  *     Context: Kernel thread context
7110  */
7111 
7112 static int
7113 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
7114 {
7115 	switch (cmd) {
7116 	case DDI_DETACH:
7117 		return (sd_unit_detach(devi));
7118 	case DDI_SUSPEND:
7119 		return (sd_ddi_suspend(devi));
7120 	default:
7121 		break;
7122 	}
7123 	return (DDI_FAILURE);
7124 }
7125 
7126 
7127 /*
7128  *     Function: sd_sync_with_callback
7129  *
7130  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
7131  *		 state while the callback routine is active.
7132  *
7133  *    Arguments: un: softstate structure for the instance
7134  *
7135  *	Context: Kernel thread context
7136  */
7137 
7138 static void
7139 sd_sync_with_callback(struct sd_lun *un)
7140 {
7141 	ASSERT(un != NULL);
7142 
7143 	mutex_enter(SD_MUTEX(un));
7144 
7145 	ASSERT(un->un_in_callback >= 0);
7146 
7147 	while (un->un_in_callback > 0) {
7148 		mutex_exit(SD_MUTEX(un));
7149 		delay(2);
7150 		mutex_enter(SD_MUTEX(un));
7151 	}
7152 
7153 	mutex_exit(SD_MUTEX(un));
7154 }
7155 
7156 /*
7157  *    Function: sd_unit_attach
7158  *
7159  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
7160  *		the soft state structure for the device and performs
7161  *		all necessary structure and device initializations.
7162  *
7163  *   Arguments: devi: the system's dev_info_t for the device.
7164  *
7165  * Return Code: DDI_SUCCESS if attach is successful.
7166  *		DDI_FAILURE if any part of the attach fails.
7167  *
7168  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
7169  *		Kernel thread context only.  Can sleep.
7170  */
7171 
7172 static int
7173 sd_unit_attach(dev_info_t *devi)
7174 {
7175 	struct	scsi_device	*devp;
7176 	struct	sd_lun		*un;
7177 	char			*variantp;
7178 	char			name_str[48];
7179 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
7180 	int	instance;
7181 	int	rval;
7182 	int	wc_enabled;
7183 	int	wc_changeable;
7184 	int	tgt;
7185 	uint64_t	capacity;
7186 	uint_t		lbasize = 0;
7187 	dev_info_t	*pdip = ddi_get_parent(devi);
7188 	int		offbyone = 0;
7189 	int		geom_label_valid = 0;
7190 	sd_ssc_t	*ssc;
7191 	int		status;
7192 	struct sd_fm_internal	*sfip = NULL;
7193 	int		max_xfer_size;
7194 
7195 	/*
7196 	 * Retrieve the target driver's private data area. This was set
7197 	 * up by the HBA.
7198 	 */
7199 	devp = ddi_get_driver_private(devi);
7200 
7201 	/*
7202 	 * Retrieve the target ID of the device.
7203 	 */
7204 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7205 	    SCSI_ADDR_PROP_TARGET, -1);
7206 
7207 	/*
7208 	 * Since we have no idea what state things were left in by the last
7209 	 * user of the device, set up some 'default' settings, ie. turn 'em
7210 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
7211 	 * Do this before the scsi_probe, which sends an inquiry.
7212 	 * This is a fix for bug (4430280).
7213 	 * Of special importance is wide-xfer. The drive could have been left
7214 	 * in wide transfer mode by the last driver to communicate with it,
7215 	 * this includes us. If that's the case, and if the following is not
7216 	 * setup properly or we don't re-negotiate with the drive prior to
7217 	 * transferring data to/from the drive, it causes bus parity errors,
7218 	 * data overruns, and unexpected interrupts. This first occurred when
7219 	 * the fix for bug (4378686) was made.
7220 	 */
7221 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
7222 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
7223 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
7224 
7225 	/*
7226 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
7227 	 * on a target. Setting it per lun instance actually sets the
7228 	 * capability of this target, which affects those luns already
7229 	 * attached on the same target. So during attach, we can only disable
7230 	 * this capability only when no other lun has been attached on this
7231 	 * target. By doing this, we assume a target has the same tagged-qing
7232 	 * capability for every lun. The condition can be removed when HBA
7233 	 * is changed to support per lun based tagged-qing capability.
7234 	 */
7235 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7236 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
7237 	}
7238 
7239 	/*
7240 	 * Use scsi_probe() to issue an INQUIRY command to the device.
7241 	 * This call will allocate and fill in the scsi_inquiry structure
7242 	 * and point the sd_inq member of the scsi_device structure to it.
7243 	 * If the attach succeeds, then this memory will not be de-allocated
7244 	 * (via scsi_unprobe()) until the instance is detached.
7245 	 */
7246 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
7247 		goto probe_failed;
7248 	}
7249 
7250 	/*
7251 	 * Check the device type as specified in the inquiry data and
7252 	 * claim it if it is of a type that we support.
7253 	 */
7254 	switch (devp->sd_inq->inq_dtype) {
7255 	case DTYPE_DIRECT:
7256 		break;
7257 	case DTYPE_RODIRECT:
7258 		break;
7259 	case DTYPE_OPTICAL:
7260 		break;
7261 	case DTYPE_NOTPRESENT:
7262 	default:
7263 		/* Unsupported device type; fail the attach. */
7264 		goto probe_failed;
7265 	}
7266 
7267 	/*
7268 	 * Allocate the soft state structure for this unit.
7269 	 *
7270 	 * We rely upon this memory being set to all zeroes by
7271 	 * ddi_soft_state_zalloc().  We assume that any member of the
7272 	 * soft state structure that is not explicitly initialized by
7273 	 * this routine will have a value of zero.
7274 	 */
7275 	instance = ddi_get_instance(devp->sd_dev);
7276 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
7277 		goto probe_failed;
7278 	}
7279 
7280 	/*
7281 	 * Retrieve a pointer to the newly-allocated soft state.
7282 	 *
7283 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
7284 	 * was successful, unless something has gone horribly wrong and the
7285 	 * ddi's soft state internals are corrupt (in which case it is
7286 	 * probably better to halt here than just fail the attach....)
7287 	 */
7288 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
7289 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
7290 		    instance);
7291 		/*NOTREACHED*/
7292 	}
7293 
7294 	/*
7295 	 * Link the back ptr of the driver soft state to the scsi_device
7296 	 * struct for this lun.
7297 	 * Save a pointer to the softstate in the driver-private area of
7298 	 * the scsi_device struct.
7299 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
7300 	 * we first set un->un_sd below.
7301 	 */
7302 	un->un_sd = devp;
7303 	devp->sd_private = (opaque_t)un;
7304 
7305 	/*
7306 	 * The following must be after devp is stored in the soft state struct.
7307 	 */
7308 #ifdef SDDEBUG
7309 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7310 	    "%s_unit_attach: un:0x%p instance:%d\n",
7311 	    ddi_driver_name(devi), un, instance);
7312 #endif
7313 
7314 	/*
7315 	 * Set up the device type and node type (for the minor nodes).
7316 	 * By default we assume that the device can at least support the
7317 	 * Common Command Set. Call it a CD-ROM if it reports itself
7318 	 * as a RODIRECT device.
7319 	 */
7320 	switch (devp->sd_inq->inq_dtype) {
7321 	case DTYPE_RODIRECT:
7322 		un->un_node_type = DDI_NT_CD_CHAN;
7323 		un->un_ctype	 = CTYPE_CDROM;
7324 		break;
7325 	case DTYPE_OPTICAL:
7326 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7327 		un->un_ctype	 = CTYPE_ROD;
7328 		break;
7329 	default:
7330 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7331 		un->un_ctype	 = CTYPE_CCS;
7332 		break;
7333 	}
7334 
7335 	/*
7336 	 * Try to read the interconnect type from the HBA.
7337 	 *
7338 	 * Note: This driver is currently compiled as two binaries, a parallel
7339 	 * scsi version (sd) and a fibre channel version (ssd). All functional
7340 	 * differences are determined at compile time. In the future a single
7341 	 * binary will be provided and the interconnect type will be used to
7342 	 * differentiate between fibre and parallel scsi behaviors. At that time
7343 	 * it will be necessary for all fibre channel HBAs to support this
7344 	 * property.
7345 	 *
7346 	 * set un_f_is_fiber to TRUE ( default fiber )
7347 	 */
7348 	un->un_f_is_fibre = TRUE;
7349 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
7350 	case INTERCONNECT_SSA:
7351 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
7352 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7353 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
7354 		break;
7355 	case INTERCONNECT_PARALLEL:
7356 		un->un_f_is_fibre = FALSE;
7357 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7358 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7359 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
7360 		break;
7361 	case INTERCONNECT_SAS:
7362 		un->un_f_is_fibre = FALSE;
7363 		un->un_interconnect_type = SD_INTERCONNECT_SAS;
7364 		un->un_node_type = DDI_NT_BLOCK_SAS;
7365 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7366 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SAS\n", un);
7367 		break;
7368 	case INTERCONNECT_SATA:
7369 		un->un_f_is_fibre = FALSE;
7370 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
7371 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7372 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
7373 		break;
7374 	case INTERCONNECT_FIBRE:
7375 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7376 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7377 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7378 		break;
7379 	case INTERCONNECT_FABRIC:
7380 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7381 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7382 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7383 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7384 		break;
7385 	default:
7386 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7387 		/*
7388 		 * The HBA does not support the "interconnect-type" property
7389 		 * (or did not provide a recognized type).
7390 		 *
7391 		 * Note: This will be obsoleted when a single fibre channel
7392 		 * and parallel scsi driver is delivered. In the meantime the
7393 		 * interconnect type will be set to the platform default.If that
7394 		 * type is not parallel SCSI, it means that we should be
7395 		 * assuming "ssd" semantics. However, here this also means that
7396 		 * the FC HBA is not supporting the "interconnect-type" property
7397 		 * like we expect it to, so log this occurrence.
7398 		 */
7399 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7400 		if (!SD_IS_PARALLEL_SCSI(un)) {
7401 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7402 			    "sd_unit_attach: un:0x%p Assuming "
7403 			    "INTERCONNECT_FIBRE\n", un);
7404 		} else {
7405 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7406 			    "sd_unit_attach: un:0x%p Assuming "
7407 			    "INTERCONNECT_PARALLEL\n", un);
7408 			un->un_f_is_fibre = FALSE;
7409 		}
7410 #else
7411 		/*
7412 		 * Note: This source will be implemented when a single fibre
7413 		 * channel and parallel scsi driver is delivered. The default
7414 		 * will be to assume that if a device does not support the
7415 		 * "interconnect-type" property it is a parallel SCSI HBA and
7416 		 * we will set the interconnect type for parallel scsi.
7417 		 */
7418 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7419 		un->un_f_is_fibre = FALSE;
7420 #endif
7421 		break;
7422 	}
7423 
7424 	if (un->un_f_is_fibre == TRUE) {
7425 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7426 		    SCSI_VERSION_3) {
7427 			switch (un->un_interconnect_type) {
7428 			case SD_INTERCONNECT_FIBRE:
7429 			case SD_INTERCONNECT_SSA:
7430 				un->un_node_type = DDI_NT_BLOCK_WWN;
7431 				break;
7432 			default:
7433 				break;
7434 			}
7435 		}
7436 	}
7437 
7438 	/*
7439 	 * Initialize the Request Sense command for the target
7440 	 */
7441 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7442 		goto alloc_rqs_failed;
7443 	}
7444 
7445 	/*
7446 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7447 	 * with separate binary for sd and ssd.
7448 	 *
7449 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7450 	 * The hardcoded values will go away when Sparc uses 1 binary
7451 	 * for sd and ssd.  This hardcoded values need to match
7452 	 * SD_RETRY_COUNT in sddef.h
7453 	 * The value used is base on interconnect type.
7454 	 * fibre = 3, parallel = 5
7455 	 */
7456 #if defined(__x86)
7457 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7458 #else
7459 	un->un_retry_count = SD_RETRY_COUNT;
7460 #endif
7461 
7462 	/*
7463 	 * Set the per disk retry count to the default number of retries
7464 	 * for disks and CDROMs. This value can be overridden by the
7465 	 * disk property list or an entry in sd.conf.
7466 	 */
7467 	un->un_notready_retry_count =
7468 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7469 	    : DISK_NOT_READY_RETRY_COUNT(un);
7470 
7471 	/*
7472 	 * Set the busy retry count to the default value of un_retry_count.
7473 	 * This can be overridden by entries in sd.conf or the device
7474 	 * config table.
7475 	 */
7476 	un->un_busy_retry_count = un->un_retry_count;
7477 
7478 	/*
7479 	 * Init the reset threshold for retries.  This number determines
7480 	 * how many retries must be performed before a reset can be issued
7481 	 * (for certain error conditions). This can be overridden by entries
7482 	 * in sd.conf or the device config table.
7483 	 */
7484 	un->un_reset_retry_count = (un->un_retry_count / 2);
7485 
7486 	/*
7487 	 * Set the victim_retry_count to the default un_retry_count
7488 	 */
7489 	un->un_victim_retry_count = (2 * un->un_retry_count);
7490 
7491 	/*
7492 	 * Set the reservation release timeout to the default value of
7493 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7494 	 * device config table.
7495 	 */
7496 	un->un_reserve_release_time = 5;
7497 
7498 	/*
7499 	 * Set up the default maximum transfer size. Note that this may
7500 	 * get updated later in the attach, when setting up default wide
7501 	 * operations for disks.
7502 	 */
7503 #if defined(__x86)
7504 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7505 	un->un_partial_dma_supported = 1;
7506 #else
7507 	un->un_max_xfer_size = (uint_t)maxphys;
7508 #endif
7509 
7510 	/*
7511 	 * Get "allow bus device reset" property (defaults to "enabled" if
7512 	 * the property was not defined). This is to disable bus resets for
7513 	 * certain kinds of error recovery. Note: In the future when a run-time
7514 	 * fibre check is available the soft state flag should default to
7515 	 * enabled.
7516 	 */
7517 	if (un->un_f_is_fibre == TRUE) {
7518 		un->un_f_allow_bus_device_reset = TRUE;
7519 	} else {
7520 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7521 		    "allow-bus-device-reset", 1) != 0) {
7522 			un->un_f_allow_bus_device_reset = TRUE;
7523 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7524 			    "sd_unit_attach: un:0x%p Bus device reset "
7525 			    "enabled\n", un);
7526 		} else {
7527 			un->un_f_allow_bus_device_reset = FALSE;
7528 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7529 			    "sd_unit_attach: un:0x%p Bus device reset "
7530 			    "disabled\n", un);
7531 		}
7532 	}
7533 
7534 	/*
7535 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7536 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7537 	 *
7538 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7539 	 * property. The new "variant" property with a value of "atapi" has been
7540 	 * introduced so that future 'variants' of standard SCSI behavior (like
7541 	 * atapi) could be specified by the underlying HBA drivers by supplying
7542 	 * a new value for the "variant" property, instead of having to define a
7543 	 * new property.
7544 	 */
7545 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7546 		un->un_f_cfg_is_atapi = TRUE;
7547 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7548 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7549 	}
7550 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7551 	    &variantp) == DDI_PROP_SUCCESS) {
7552 		if (strcmp(variantp, "atapi") == 0) {
7553 			un->un_f_cfg_is_atapi = TRUE;
7554 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7555 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7556 		}
7557 		ddi_prop_free(variantp);
7558 	}
7559 
7560 	un->un_cmd_timeout	= SD_IO_TIME;
7561 
7562 	un->un_busy_timeout  = SD_BSY_TIMEOUT;
7563 
7564 	/* Info on current states, statuses, etc. (Updated frequently) */
7565 	un->un_state		= SD_STATE_NORMAL;
7566 	un->un_last_state	= SD_STATE_NORMAL;
7567 
7568 	/* Control & status info for command throttling */
7569 	un->un_throttle		= sd_max_throttle;
7570 	un->un_saved_throttle	= sd_max_throttle;
7571 	un->un_min_throttle	= sd_min_throttle;
7572 
7573 	if (un->un_f_is_fibre == TRUE) {
7574 		un->un_f_use_adaptive_throttle = TRUE;
7575 	} else {
7576 		un->un_f_use_adaptive_throttle = FALSE;
7577 	}
7578 
7579 	/* Removable media support. */
7580 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7581 	un->un_mediastate		= DKIO_NONE;
7582 	un->un_specified_mediastate	= DKIO_NONE;
7583 
7584 	/* CVs for suspend/resume (PM or DR) */
7585 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7586 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7587 
7588 	/* Power management support. */
7589 	un->un_power_level = SD_SPINDLE_UNINIT;
7590 
7591 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
7592 	un->un_f_wcc_inprog = 0;
7593 
7594 	/*
7595 	 * The conf file entry and softstate variable is a forceful override,
7596 	 * meaning a non-zero value must be entered to change the default.
7597 	 */
7598 	un->un_f_disksort_disabled = FALSE;
7599 	un->un_f_rmw_type = SD_RMW_TYPE_DEFAULT;
7600 	un->un_f_enable_rmw = FALSE;
7601 
7602 	/*
7603 	 * GET EVENT STATUS NOTIFICATION media polling enabled by default, but
7604 	 * can be overridden via [s]sd-config-list "mmc-gesn-polling" property.
7605 	 */
7606 	un->un_f_mmc_gesn_polling = TRUE;
7607 
7608 	/*
7609 	 * physical sector size defaults to DEV_BSIZE currently. We can
7610 	 * override this value via the driver configuration file so we must
7611 	 * set it before calling sd_read_unit_properties().
7612 	 */
7613 	un->un_phy_blocksize = DEV_BSIZE;
7614 
7615 	/*
7616 	 * Retrieve the properties from the static driver table or the driver
7617 	 * configuration file (.conf) for this unit and update the soft state
7618 	 * for the device as needed for the indicated properties.
7619 	 * Note: the property configuration needs to occur here as some of the
7620 	 * following routines may have dependencies on soft state flags set
7621 	 * as part of the driver property configuration.
7622 	 */
7623 	sd_read_unit_properties(un);
7624 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7625 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
7626 
7627 	/*
7628 	 * Only if a device has "hotpluggable" property, it is
7629 	 * treated as hotpluggable device. Otherwise, it is
7630 	 * regarded as non-hotpluggable one.
7631 	 */
7632 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
7633 	    -1) != -1) {
7634 		un->un_f_is_hotpluggable = TRUE;
7635 	}
7636 
7637 	/*
7638 	 * set unit's attributes(flags) according to "hotpluggable" and
7639 	 * RMB bit in INQUIRY data.
7640 	 */
7641 	sd_set_unit_attributes(un, devi);
7642 
7643 	/*
7644 	 * By default, we mark the capacity, lbasize, and geometry
7645 	 * as invalid. Only if we successfully read a valid capacity
7646 	 * will we update the un_blockcount and un_tgt_blocksize with the
7647 	 * valid values (the geometry will be validated later).
7648 	 */
7649 	un->un_f_blockcount_is_valid	= FALSE;
7650 	un->un_f_tgt_blocksize_is_valid	= FALSE;
7651 
7652 	/*
7653 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
7654 	 * otherwise.
7655 	 */
7656 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
7657 	un->un_blockcount = 0;
7658 
7659 	/*
7660 	 * Set up the per-instance info needed to determine the correct
7661 	 * CDBs and other info for issuing commands to the target.
7662 	 */
7663 	sd_init_cdb_limits(un);
7664 
7665 	/*
7666 	 * Set up the IO chains to use, based upon the target type.
7667 	 */
7668 	if (un->un_f_non_devbsize_supported) {
7669 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7670 	} else {
7671 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7672 	}
7673 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7674 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
7675 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
7676 
7677 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
7678 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
7679 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
7680 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
7681 
7682 
7683 	if (ISCD(un)) {
7684 		un->un_additional_codes = sd_additional_codes;
7685 	} else {
7686 		un->un_additional_codes = NULL;
7687 	}
7688 
7689 	/*
7690 	 * Create the kstats here so they can be available for attach-time
7691 	 * routines that send commands to the unit (either polled or via
7692 	 * sd_send_scsi_cmd).
7693 	 *
7694 	 * Note: This is a critical sequence that needs to be maintained:
7695 	 *	1) Instantiate the kstats here, before any routines using the
7696 	 *	   iopath (i.e. sd_send_scsi_cmd).
7697 	 *	2) Instantiate and initialize the partition stats
7698 	 *	   (sd_set_pstats).
7699 	 *	3) Initialize the error stats (sd_set_errstats), following
7700 	 *	   sd_validate_geometry(),sd_register_devid(),
7701 	 *	   and sd_cache_control().
7702 	 */
7703 
7704 	un->un_stats = kstat_create(sd_label, instance,
7705 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
7706 	if (un->un_stats != NULL) {
7707 		un->un_stats->ks_lock = SD_MUTEX(un);
7708 		kstat_install(un->un_stats);
7709 	}
7710 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7711 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
7712 
7713 	un->un_unmapstats_ks = kstat_create(sd_label, instance, "unmapstats",
7714 	    "misc", KSTAT_TYPE_NAMED, sizeof (*un->un_unmapstats) /
7715 	    sizeof (kstat_named_t), 0);
7716 	if (un->un_unmapstats_ks) {
7717 		un->un_unmapstats = un->un_unmapstats_ks->ks_data;
7718 
7719 		kstat_named_init(&un->un_unmapstats->us_cmds,
7720 		    "commands", KSTAT_DATA_UINT64);
7721 		kstat_named_init(&un->un_unmapstats->us_errs,
7722 		    "errors", KSTAT_DATA_UINT64);
7723 		kstat_named_init(&un->un_unmapstats->us_extents,
7724 		    "extents", KSTAT_DATA_UINT64);
7725 		kstat_named_init(&un->un_unmapstats->us_bytes,
7726 		    "bytes", KSTAT_DATA_UINT64);
7727 
7728 		kstat_install(un->un_unmapstats_ks);
7729 	} else {
7730 		cmn_err(CE_NOTE, "!Cannot create unmap kstats for disk %d",
7731 		    instance);
7732 	}
7733 
7734 	sd_create_errstats(un, instance);
7735 	if (un->un_errstats == NULL) {
7736 		goto create_errstats_failed;
7737 	}
7738 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7739 	    "sd_unit_attach: un:0x%p errstats created\n", un);
7740 
7741 	/*
7742 	 * The following if/else code was relocated here from below as part
7743 	 * of the fix for bug (4430280). However with the default setup added
7744 	 * on entry to this routine, it's no longer absolutely necessary for
7745 	 * this to be before the call to sd_spin_up_unit.
7746 	 */
7747 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
7748 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
7749 		    (devp->sd_inq->inq_ansi == 5)) &&
7750 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
7751 
7752 		/*
7753 		 * If tagged queueing is supported by the target
7754 		 * and by the host adapter then we will enable it
7755 		 */
7756 		un->un_tagflags = 0;
7757 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
7758 		    (un->un_f_arq_enabled == TRUE)) {
7759 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
7760 			    1, 1) == 1) {
7761 				un->un_tagflags = FLAG_STAG;
7762 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7763 				    "sd_unit_attach: un:0x%p tag queueing "
7764 				    "enabled\n", un);
7765 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
7766 			    "untagged-qing", 0) == 1) {
7767 				un->un_f_opt_queueing = TRUE;
7768 				un->un_saved_throttle = un->un_throttle =
7769 				    min(un->un_throttle, 3);
7770 			} else {
7771 				un->un_f_opt_queueing = FALSE;
7772 				un->un_saved_throttle = un->un_throttle = 1;
7773 			}
7774 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
7775 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
7776 			/* The Host Adapter supports internal queueing. */
7777 			un->un_f_opt_queueing = TRUE;
7778 			un->un_saved_throttle = un->un_throttle =
7779 			    min(un->un_throttle, 3);
7780 		} else {
7781 			un->un_f_opt_queueing = FALSE;
7782 			un->un_saved_throttle = un->un_throttle = 1;
7783 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7784 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
7785 		}
7786 
7787 		/*
7788 		 * Enable large transfers for SATA/SAS drives
7789 		 */
7790 		if (SD_IS_SERIAL(un)) {
7791 			un->un_max_xfer_size =
7792 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7793 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7794 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7795 			    "sd_unit_attach: un:0x%p max transfer "
7796 			    "size=0x%x\n", un, un->un_max_xfer_size);
7797 
7798 		}
7799 
7800 		/* Setup or tear down default wide operations for disks */
7801 
7802 		/*
7803 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
7804 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
7805 		 * system and be set to different values. In the future this
7806 		 * code may need to be updated when the ssd module is
7807 		 * obsoleted and removed from the system. (4299588)
7808 		 */
7809 		if (SD_IS_PARALLEL_SCSI(un) &&
7810 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
7811 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
7812 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7813 			    1, 1) == 1) {
7814 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7815 				    "sd_unit_attach: un:0x%p Wide Transfer "
7816 				    "enabled\n", un);
7817 			}
7818 
7819 			/*
7820 			 * If tagged queuing has also been enabled, then
7821 			 * enable large xfers
7822 			 */
7823 			if (un->un_saved_throttle == sd_max_throttle) {
7824 				un->un_max_xfer_size =
7825 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7826 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7827 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7828 				    "sd_unit_attach: un:0x%p max transfer "
7829 				    "size=0x%x\n", un, un->un_max_xfer_size);
7830 			}
7831 		} else {
7832 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7833 			    0, 1) == 1) {
7834 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7835 				    "sd_unit_attach: un:0x%p "
7836 				    "Wide Transfer disabled\n", un);
7837 			}
7838 		}
7839 	} else {
7840 		un->un_tagflags = FLAG_STAG;
7841 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7842 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7843 	}
7844 
7845 	/*
7846 	 * If this target supports LUN reset, try to enable it.
7847 	 */
7848 	if (un->un_f_lun_reset_enabled) {
7849 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7850 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7851 			    "un:0x%p lun_reset capability set\n", un);
7852 		} else {
7853 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7854 			    "un:0x%p lun-reset capability not set\n", un);
7855 		}
7856 	}
7857 
7858 	/*
7859 	 * Adjust the maximum transfer size. This is to fix
7860 	 * the problem of partial DMA support on SPARC. Some
7861 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7862 	 * size, which requires partial DMA support on SPARC.
7863 	 * In the future the SPARC pci nexus driver may solve
7864 	 * the problem instead of this fix.
7865 	 */
7866 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7867 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7868 		/* We need DMA partial even on sparc to ensure sddump() works */
7869 		un->un_max_xfer_size = max_xfer_size;
7870 		if (un->un_partial_dma_supported == 0)
7871 			un->un_partial_dma_supported = 1;
7872 	}
7873 	if (ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7874 	    DDI_PROP_DONTPASS, "buf_break", 0) == 1) {
7875 		if (ddi_xbuf_attr_setup_brk(un->un_xbuf_attr,
7876 		    un->un_max_xfer_size) == 1) {
7877 			un->un_buf_breakup_supported = 1;
7878 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7879 			    "un:0x%p Buf breakup enabled\n", un);
7880 		}
7881 	}
7882 
7883 	/*
7884 	 * Set PKT_DMA_PARTIAL flag.
7885 	 */
7886 	if (un->un_partial_dma_supported == 1) {
7887 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7888 	} else {
7889 		un->un_pkt_flags = 0;
7890 	}
7891 
7892 	/* Initialize sd_ssc_t for internal uscsi commands */
7893 	ssc = sd_ssc_init(un);
7894 	scsi_fm_init(devp);
7895 
7896 	/*
7897 	 * Allocate memory for SCSI FMA stuffs.
7898 	 */
7899 	un->un_fm_private =
7900 	    kmem_zalloc(sizeof (struct sd_fm_internal), KM_SLEEP);
7901 	sfip = (struct sd_fm_internal *)un->un_fm_private;
7902 	sfip->fm_ssc.ssc_uscsi_cmd = &sfip->fm_ucmd;
7903 	sfip->fm_ssc.ssc_uscsi_info = &sfip->fm_uinfo;
7904 	sfip->fm_ssc.ssc_un = un;
7905 
7906 	if (ISCD(un) ||
7907 	    un->un_f_has_removable_media ||
7908 	    devp->sd_fm_capable == DDI_FM_NOT_CAPABLE) {
7909 		/*
7910 		 * We don't touch CDROM or the DDI_FM_NOT_CAPABLE device.
7911 		 * Their log are unchanged.
7912 		 */
7913 		sfip->fm_log_level = SD_FM_LOG_NSUP;
7914 	} else {
7915 		/*
7916 		 * If enter here, it should be non-CDROM and FM-capable
7917 		 * device, and it will not keep the old scsi_log as before
7918 		 * in /var/adm/messages. However, the property
7919 		 * "fm-scsi-log" will control whether the FM telemetry will
7920 		 * be logged in /var/adm/messages.
7921 		 */
7922 		int fm_scsi_log;
7923 		fm_scsi_log = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7924 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "fm-scsi-log", 0);
7925 
7926 		if (fm_scsi_log)
7927 			sfip->fm_log_level = SD_FM_LOG_EREPORT;
7928 		else
7929 			sfip->fm_log_level = SD_FM_LOG_SILENT;
7930 	}
7931 
7932 	/*
7933 	 * At this point in the attach, we have enough info in the
7934 	 * soft state to be able to issue commands to the target.
7935 	 *
7936 	 * All command paths used below MUST issue their commands as
7937 	 * SD_PATH_DIRECT. This is important as intermediate layers
7938 	 * are not all initialized yet (such as PM).
7939 	 */
7940 
7941 	/*
7942 	 * Send a TEST UNIT READY command to the device. This should clear
7943 	 * any outstanding UNIT ATTENTION that may be present.
7944 	 *
7945 	 * Note: Don't check for success, just track if there is a reservation,
7946 	 * this is a throw away command to clear any unit attentions.
7947 	 *
7948 	 * Note: This MUST be the first command issued to the target during
7949 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7950 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7951 	 * with attempts at spinning up a device with no media.
7952 	 */
7953 	status = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
7954 	if (status != 0) {
7955 		if (status == EACCES)
7956 			reservation_flag = SD_TARGET_IS_RESERVED;
7957 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7958 	}
7959 
7960 	/*
7961 	 * If the device is NOT a removable media device, attempt to spin
7962 	 * it up (using the START_STOP_UNIT command) and read its capacity
7963 	 * (using the READ CAPACITY command).  Note, however, that either
7964 	 * of these could fail and in some cases we would continue with
7965 	 * the attach despite the failure (see below).
7966 	 */
7967 	if (un->un_f_descr_format_supported) {
7968 
7969 		switch (sd_spin_up_unit(ssc)) {
7970 		case 0:
7971 			/*
7972 			 * Spin-up was successful; now try to read the
7973 			 * capacity.  If successful then save the results
7974 			 * and mark the capacity & lbasize as valid.
7975 			 */
7976 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7977 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7978 
7979 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
7980 			    &lbasize, SD_PATH_DIRECT);
7981 
7982 			switch (status) {
7983 			case 0: {
7984 				if (capacity > DK_MAX_BLOCKS) {
7985 #ifdef _LP64
7986 					if ((capacity + 1) >
7987 					    SD_GROUP1_MAX_ADDRESS) {
7988 						/*
7989 						 * Enable descriptor format
7990 						 * sense data so that we can
7991 						 * get 64 bit sense data
7992 						 * fields.
7993 						 */
7994 						sd_enable_descr_sense(ssc);
7995 					}
7996 #else
7997 					/* 32-bit kernels can't handle this */
7998 					scsi_log(SD_DEVINFO(un),
7999 					    sd_label, CE_WARN,
8000 					    "disk has %llu blocks, which "
8001 					    "is too large for a 32-bit "
8002 					    "kernel", capacity);
8003 
8004 #if defined(__x86)
8005 					/*
8006 					 * 1TB disk was treated as (1T - 512)B
8007 					 * in the past, so that it might have
8008 					 * valid VTOC and solaris partitions,
8009 					 * we have to allow it to continue to
8010 					 * work.
8011 					 */
8012 					if (capacity - 1 > DK_MAX_BLOCKS)
8013 #endif
8014 					goto spinup_failed;
8015 #endif
8016 				}
8017 
8018 				/*
8019 				 * Here it's not necessary to check the case:
8020 				 * the capacity of the device is bigger than
8021 				 * what the max hba cdb can support. Because
8022 				 * sd_send_scsi_READ_CAPACITY will retrieve
8023 				 * the capacity by sending USCSI command, which
8024 				 * is constrained by the max hba cdb. Actually,
8025 				 * sd_send_scsi_READ_CAPACITY will return
8026 				 * EINVAL when using bigger cdb than required
8027 				 * cdb length. Will handle this case in
8028 				 * "case EINVAL".
8029 				 */
8030 
8031 				/*
8032 				 * The following relies on
8033 				 * sd_send_scsi_READ_CAPACITY never
8034 				 * returning 0 for capacity and/or lbasize.
8035 				 */
8036 				sd_update_block_info(un, lbasize, capacity);
8037 
8038 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8039 				    "sd_unit_attach: un:0x%p capacity = %ld "
8040 				    "blocks; lbasize= %ld.\n", un,
8041 				    un->un_blockcount, un->un_tgt_blocksize);
8042 
8043 				break;
8044 			}
8045 			case EINVAL:
8046 				/*
8047 				 * In the case where the max-cdb-length property
8048 				 * is smaller than the required CDB length for
8049 				 * a SCSI device, a target driver can fail to
8050 				 * attach to that device.
8051 				 */
8052 				scsi_log(SD_DEVINFO(un),
8053 				    sd_label, CE_WARN,
8054 				    "disk capacity is too large "
8055 				    "for current cdb length");
8056 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8057 
8058 				goto spinup_failed;
8059 			case EACCES:
8060 				/*
8061 				 * Should never get here if the spin-up
8062 				 * succeeded, but code it in anyway.
8063 				 * From here, just continue with the attach...
8064 				 */
8065 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8066 				    "sd_unit_attach: un:0x%p "
8067 				    "sd_send_scsi_READ_CAPACITY "
8068 				    "returned reservation conflict\n", un);
8069 				reservation_flag = SD_TARGET_IS_RESERVED;
8070 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8071 				break;
8072 			default:
8073 				/*
8074 				 * Likewise, should never get here if the
8075 				 * spin-up succeeded. Just continue with
8076 				 * the attach...
8077 				 */
8078 				if (status == EIO)
8079 					sd_ssc_assessment(ssc,
8080 					    SD_FMT_STATUS_CHECK);
8081 				else
8082 					sd_ssc_assessment(ssc,
8083 					    SD_FMT_IGNORE);
8084 				break;
8085 			}
8086 			break;
8087 		case EACCES:
8088 			/*
8089 			 * Device is reserved by another host.  In this case
8090 			 * we could not spin it up or read the capacity, but
8091 			 * we continue with the attach anyway.
8092 			 */
8093 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8094 			    "sd_unit_attach: un:0x%p spin-up reservation "
8095 			    "conflict.\n", un);
8096 			reservation_flag = SD_TARGET_IS_RESERVED;
8097 			break;
8098 		default:
8099 			/* Fail the attach if the spin-up failed. */
8100 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8101 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
8102 			goto spinup_failed;
8103 		}
8104 
8105 	}
8106 
8107 	/*
8108 	 * Check to see if this is a MMC drive
8109 	 */
8110 	if (ISCD(un)) {
8111 		sd_set_mmc_caps(ssc);
8112 	}
8113 
8114 	/*
8115 	 * Add a zero-length attribute to tell the world we support
8116 	 * kernel ioctls (for layered drivers)
8117 	 */
8118 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8119 	    DDI_KERNEL_IOCTL, NULL, 0);
8120 
8121 	/*
8122 	 * Add a boolean property to tell the world we support
8123 	 * the B_FAILFAST flag (for layered drivers)
8124 	 */
8125 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8126 	    "ddi-failfast-supported", NULL, 0);
8127 
8128 	/*
8129 	 * Initialize power management
8130 	 */
8131 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
8132 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
8133 	sd_setup_pm(ssc, devi);
8134 	if (un->un_f_pm_is_enabled == FALSE) {
8135 		/*
8136 		 * For performance, point to a jump table that does
8137 		 * not include pm.
8138 		 * The direct and priority chains don't change with PM.
8139 		 *
8140 		 * Note: this is currently done based on individual device
8141 		 * capabilities. When an interface for determining system
8142 		 * power enabled state becomes available, or when additional
8143 		 * layers are added to the command chain, these values will
8144 		 * have to be re-evaluated for correctness.
8145 		 */
8146 		if (un->un_f_non_devbsize_supported) {
8147 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
8148 		} else {
8149 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
8150 		}
8151 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8152 	}
8153 
8154 	/*
8155 	 * This property is set to 0 by HA software to avoid retries
8156 	 * on a reserved disk. (The preferred property name is
8157 	 * "retry-on-reservation-conflict") (1189689)
8158 	 *
8159 	 * Note: The use of a global here can have unintended consequences. A
8160 	 * per instance variable is preferable to match the capabilities of
8161 	 * different underlying hba's (4402600)
8162 	 */
8163 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
8164 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
8165 	    sd_retry_on_reservation_conflict);
8166 	if (sd_retry_on_reservation_conflict != 0) {
8167 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
8168 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
8169 		    sd_retry_on_reservation_conflict);
8170 	}
8171 
8172 	/* Set up options for QFULL handling. */
8173 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8174 	    "qfull-retries", -1)) != -1) {
8175 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
8176 		    rval, 1);
8177 	}
8178 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8179 	    "qfull-retry-interval", -1)) != -1) {
8180 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
8181 		    rval, 1);
8182 	}
8183 
8184 	/*
8185 	 * This just prints a message that announces the existence of the
8186 	 * device. The message is always printed in the system logfile, but
8187 	 * only appears on the console if the system is booted with the
8188 	 * -v (verbose) argument.
8189 	 */
8190 	ddi_report_dev(devi);
8191 
8192 	un->un_mediastate = DKIO_NONE;
8193 
8194 	/*
8195 	 * Check Block Device Characteristics VPD.
8196 	 */
8197 	sd_check_bdc_vpd(ssc);
8198 
8199 	/*
8200 	 * Check whether the drive is in emulation mode.
8201 	 */
8202 	sd_check_emulation_mode(ssc);
8203 
8204 	cmlb_alloc_handle(&un->un_cmlbhandle);
8205 
8206 #if defined(__x86)
8207 	/*
8208 	 * On x86, compensate for off-by-1 legacy error
8209 	 */
8210 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
8211 	    (lbasize == un->un_sys_blocksize))
8212 		offbyone = CMLB_OFF_BY_ONE;
8213 #endif
8214 
8215 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
8216 	    VOID2BOOLEAN(un->un_f_has_removable_media != 0),
8217 	    VOID2BOOLEAN(un->un_f_is_hotpluggable != 0),
8218 	    un->un_node_type, offbyone, un->un_cmlbhandle,
8219 	    (void *)SD_PATH_DIRECT) != 0) {
8220 		goto cmlb_attach_failed;
8221 	}
8222 
8223 
8224 	/*
8225 	 * Read and validate the device's geometry (ie, disk label)
8226 	 * A new unformatted drive will not have a valid geometry, but
8227 	 * the driver needs to successfully attach to this device so
8228 	 * the drive can be formatted via ioctls.
8229 	 */
8230 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
8231 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
8232 
8233 	mutex_enter(SD_MUTEX(un));
8234 
8235 	/*
8236 	 * Read and initialize the devid for the unit.
8237 	 */
8238 	if (un->un_f_devid_supported) {
8239 		sd_register_devid(ssc, devi, reservation_flag);
8240 	}
8241 	mutex_exit(SD_MUTEX(un));
8242 
8243 #if (defined(__fibre))
8244 	/*
8245 	 * Register callbacks for fibre only.  You can't do this solely
8246 	 * on the basis of the devid_type because this is hba specific.
8247 	 * We need to query our hba capabilities to find out whether to
8248 	 * register or not.
8249 	 */
8250 	if (un->un_f_is_fibre) {
8251 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
8252 			sd_init_event_callbacks(un);
8253 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8254 			    "sd_unit_attach: un:0x%p event callbacks inserted",
8255 			    un);
8256 		}
8257 	}
8258 #endif
8259 
8260 	if (un->un_f_opt_disable_cache == TRUE) {
8261 		/*
8262 		 * Disable both read cache and write cache.  This is
8263 		 * the historic behavior of the keywords in the config file.
8264 		 */
8265 		if (sd_cache_control(ssc, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
8266 		    0) {
8267 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8268 			    "sd_unit_attach: un:0x%p Could not disable "
8269 			    "caching", un);
8270 			goto devid_failed;
8271 		}
8272 	}
8273 
8274 	/*
8275 	 * Check the value of the WCE bit and if it's allowed to be changed,
8276 	 * set un_f_write_cache_enabled and un_f_cache_mode_changeable
8277 	 * accordingly.
8278 	 */
8279 	(void) sd_get_write_cache_enabled(ssc, &wc_enabled);
8280 	sd_get_write_cache_changeable(ssc, &wc_changeable);
8281 	mutex_enter(SD_MUTEX(un));
8282 	un->un_f_write_cache_enabled = (wc_enabled != 0);
8283 	un->un_f_cache_mode_changeable = (wc_changeable != 0);
8284 	mutex_exit(SD_MUTEX(un));
8285 
8286 	if ((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR &&
8287 	    un->un_tgt_blocksize != DEV_BSIZE) ||
8288 	    un->un_f_enable_rmw) {
8289 		if (!(un->un_wm_cache)) {
8290 			(void) snprintf(name_str, sizeof (name_str),
8291 			    "%s%d_cache",
8292 			    ddi_driver_name(SD_DEVINFO(un)),
8293 			    ddi_get_instance(SD_DEVINFO(un)));
8294 			un->un_wm_cache = kmem_cache_create(
8295 			    name_str, sizeof (struct sd_w_map),
8296 			    8, sd_wm_cache_constructor,
8297 			    sd_wm_cache_destructor, NULL,
8298 			    (void *)un, NULL, 0);
8299 			if (!(un->un_wm_cache)) {
8300 				goto wm_cache_failed;
8301 			}
8302 		}
8303 	}
8304 
8305 	/*
8306 	 * Check the value of the NV_SUP bit and set
8307 	 * un_f_suppress_cache_flush accordingly.
8308 	 */
8309 	sd_get_nv_sup(ssc);
8310 
8311 	/*
8312 	 * Find out what type of reservation this disk supports.
8313 	 */
8314 	status = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS, 0, NULL);
8315 
8316 	switch (status) {
8317 	case 0:
8318 		/*
8319 		 * SCSI-3 reservations are supported.
8320 		 */
8321 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8322 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8323 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
8324 		break;
8325 	case ENOTSUP:
8326 		/*
8327 		 * The PERSISTENT RESERVE IN command would not be recognized by
8328 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
8329 		 */
8330 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8331 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
8332 		un->un_reservation_type = SD_SCSI2_RESERVATION;
8333 
8334 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8335 		break;
8336 	default:
8337 		/*
8338 		 * default to SCSI-3 reservations
8339 		 */
8340 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8341 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
8342 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8343 
8344 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8345 		break;
8346 	}
8347 
8348 	/*
8349 	 * Set the pstat and error stat values here, so data obtained during the
8350 	 * previous attach-time routines is available.
8351 	 *
8352 	 * Note: This is a critical sequence that needs to be maintained:
8353 	 *	1) Instantiate the kstats before any routines using the iopath
8354 	 *	   (i.e. sd_send_scsi_cmd).
8355 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8356 	 *	   stats (sd_set_pstats)here, following
8357 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
8358 	 *	   sd_cache_control().
8359 	 */
8360 
8361 	if (un->un_f_pkstats_enabled && geom_label_valid) {
8362 		sd_set_pstats(un);
8363 		SD_TRACE(SD_LOG_IO_PARTITION, un,
8364 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
8365 	}
8366 
8367 	sd_set_errstats(un);
8368 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8369 	    "sd_unit_attach: un:0x%p errstats set\n", un);
8370 
8371 	sd_setup_blk_limits(ssc);
8372 
8373 	/*
8374 	 * After successfully attaching an instance, we record the information
8375 	 * of how many luns have been attached on the relative target and
8376 	 * controller for parallel SCSI. This information is used when sd tries
8377 	 * to set the tagged queuing capability in HBA.
8378 	 */
8379 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8380 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
8381 	}
8382 
8383 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8384 	    "sd_unit_attach: un:0x%p exit success\n", un);
8385 
8386 	/* Uninitialize sd_ssc_t pointer */
8387 	sd_ssc_fini(ssc);
8388 
8389 	return (DDI_SUCCESS);
8390 
8391 	/*
8392 	 * An error occurred during the attach; clean up & return failure.
8393 	 */
8394 wm_cache_failed:
8395 devid_failed:
8396 	ddi_remove_minor_node(devi, NULL);
8397 
8398 cmlb_attach_failed:
8399 	/*
8400 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8401 	 */
8402 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8403 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8404 
8405 	/*
8406 	 * Refer to the comments of setting tagged-qing in the beginning of
8407 	 * sd_unit_attach. We can only disable tagged queuing when there is
8408 	 * no lun attached on the target.
8409 	 */
8410 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
8411 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8412 	}
8413 
8414 	if (un->un_f_is_fibre == FALSE) {
8415 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8416 	}
8417 
8418 spinup_failed:
8419 
8420 	/* Uninitialize sd_ssc_t pointer */
8421 	sd_ssc_fini(ssc);
8422 
8423 	mutex_enter(SD_MUTEX(un));
8424 
8425 	/* Deallocate SCSI FMA memory spaces */
8426 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8427 
8428 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
8429 	if (un->un_direct_priority_timeid != NULL) {
8430 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8431 		un->un_direct_priority_timeid = NULL;
8432 		mutex_exit(SD_MUTEX(un));
8433 		(void) untimeout(temp_id);
8434 		mutex_enter(SD_MUTEX(un));
8435 	}
8436 
8437 	/* Cancel any pending start/stop timeouts */
8438 	if (un->un_startstop_timeid != NULL) {
8439 		timeout_id_t temp_id = un->un_startstop_timeid;
8440 		un->un_startstop_timeid = NULL;
8441 		mutex_exit(SD_MUTEX(un));
8442 		(void) untimeout(temp_id);
8443 		mutex_enter(SD_MUTEX(un));
8444 	}
8445 
8446 	/* Cancel any pending reset-throttle timeouts */
8447 	if (un->un_reset_throttle_timeid != NULL) {
8448 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8449 		un->un_reset_throttle_timeid = NULL;
8450 		mutex_exit(SD_MUTEX(un));
8451 		(void) untimeout(temp_id);
8452 		mutex_enter(SD_MUTEX(un));
8453 	}
8454 
8455 	/* Cancel rmw warning message timeouts */
8456 	if (un->un_rmw_msg_timeid != NULL) {
8457 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8458 		un->un_rmw_msg_timeid = NULL;
8459 		mutex_exit(SD_MUTEX(un));
8460 		(void) untimeout(temp_id);
8461 		mutex_enter(SD_MUTEX(un));
8462 	}
8463 
8464 	/* Cancel any pending retry timeouts */
8465 	if (un->un_retry_timeid != NULL) {
8466 		timeout_id_t temp_id = un->un_retry_timeid;
8467 		un->un_retry_timeid = NULL;
8468 		mutex_exit(SD_MUTEX(un));
8469 		(void) untimeout(temp_id);
8470 		mutex_enter(SD_MUTEX(un));
8471 	}
8472 
8473 	/* Cancel any pending delayed cv broadcast timeouts */
8474 	if (un->un_dcvb_timeid != NULL) {
8475 		timeout_id_t temp_id = un->un_dcvb_timeid;
8476 		un->un_dcvb_timeid = NULL;
8477 		mutex_exit(SD_MUTEX(un));
8478 		(void) untimeout(temp_id);
8479 		mutex_enter(SD_MUTEX(un));
8480 	}
8481 
8482 	mutex_exit(SD_MUTEX(un));
8483 
8484 	/* There should not be any in-progress I/O so ASSERT this check */
8485 	ASSERT(un->un_ncmds_in_transport == 0);
8486 	ASSERT(un->un_ncmds_in_driver == 0);
8487 
8488 	/* Do not free the softstate if the callback routine is active */
8489 	sd_sync_with_callback(un);
8490 
8491 	/*
8492 	 * Partition stats apparently are not used with removables. These would
8493 	 * not have been created during attach, so no need to clean them up...
8494 	 */
8495 	if (un->un_errstats != NULL) {
8496 		kstat_delete(un->un_errstats);
8497 		un->un_errstats = NULL;
8498 	}
8499 
8500 create_errstats_failed:
8501 
8502 	if (un->un_stats != NULL) {
8503 		kstat_delete(un->un_stats);
8504 		un->un_stats = NULL;
8505 	}
8506 
8507 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8508 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8509 
8510 	ddi_prop_remove_all(devi);
8511 	cv_destroy(&un->un_state_cv);
8512 
8513 	sd_free_rqs(un);
8514 
8515 alloc_rqs_failed:
8516 
8517 	devp->sd_private = NULL;
8518 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8519 
8520 	/*
8521 	 * Note: the man pages are unclear as to whether or not doing a
8522 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8523 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8524 	 * ddi_get_soft_state() fails.  The implication seems to be
8525 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8526 	 */
8527 #ifndef XPV_HVM_DRIVER
8528 	ddi_soft_state_free(sd_state, instance);
8529 #endif /* !XPV_HVM_DRIVER */
8530 
8531 probe_failed:
8532 	scsi_unprobe(devp);
8533 
8534 	return (DDI_FAILURE);
8535 }
8536 
8537 
8538 /*
8539  *    Function: sd_unit_detach
8540  *
8541  * Description: Performs DDI_DETACH processing for sddetach().
8542  *
8543  * Return Code: DDI_SUCCESS
8544  *		DDI_FAILURE
8545  *
8546  *     Context: Kernel thread context
8547  */
8548 
8549 static int
8550 sd_unit_detach(dev_info_t *devi)
8551 {
8552 	struct scsi_device	*devp;
8553 	struct sd_lun		*un;
8554 	int			i;
8555 	int			tgt;
8556 	dev_t			dev;
8557 	dev_info_t		*pdip = ddi_get_parent(devi);
8558 	int			instance = ddi_get_instance(devi);
8559 
8560 	/*
8561 	 * Fail the detach for any of the following:
8562 	 *  - Unable to get the sd_lun struct for the instance
8563 	 *  - There is pending I/O
8564 	 */
8565 	devp = ddi_get_driver_private(devi);
8566 	if ((devp == NULL) ||
8567 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8568 	    (un->un_ncmds_in_driver != 0)) {
8569 		return (DDI_FAILURE);
8570 	}
8571 
8572 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8573 
8574 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
8575 	    SCSI_ADDR_PROP_TARGET, -1);
8576 
8577 	dev = sd_make_device(SD_DEVINFO(un));
8578 
8579 #ifndef lint
8580 	_NOTE(COMPETING_THREADS_NOW);
8581 #endif
8582 
8583 	mutex_enter(SD_MUTEX(un));
8584 
8585 	/*
8586 	 * Fail the detach if there are any outstanding layered
8587 	 * opens on this device.
8588 	 */
8589 	for (i = 0; i < NDKMAP; i++) {
8590 		if (un->un_ocmap.lyropen[i] != 0) {
8591 			goto err_notclosed;
8592 		}
8593 	}
8594 
8595 	/*
8596 	 * Verify there are NO outstanding commands issued to this device.
8597 	 * ie, un_ncmds_in_transport == 0.
8598 	 * It's possible to have outstanding commands through the physio
8599 	 * code path, even though everything's closed.
8600 	 */
8601 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8602 	    (un->un_direct_priority_timeid != NULL) ||
8603 	    (un->un_state == SD_STATE_RWAIT)) {
8604 		mutex_exit(SD_MUTEX(un));
8605 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8606 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8607 		goto err_stillbusy;
8608 	}
8609 
8610 	/*
8611 	 * If we have the device reserved, release the reservation.
8612 	 */
8613 	if ((un->un_resvd_status & SD_RESERVE) &&
8614 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8615 		mutex_exit(SD_MUTEX(un));
8616 		/*
8617 		 * Note: sd_reserve_release sends a command to the device
8618 		 * via the sd_ioctlcmd() path, and can sleep.
8619 		 */
8620 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8621 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8622 			    "sd_dr_detach: Cannot release reservation \n");
8623 		}
8624 	} else {
8625 		mutex_exit(SD_MUTEX(un));
8626 	}
8627 
8628 	/*
8629 	 * Untimeout any reserve recover, throttle reset, restart unit
8630 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8631 	 * from getting nulled by their callback functions.
8632 	 */
8633 	mutex_enter(SD_MUTEX(un));
8634 	if (un->un_resvd_timeid != NULL) {
8635 		timeout_id_t temp_id = un->un_resvd_timeid;
8636 		un->un_resvd_timeid = NULL;
8637 		mutex_exit(SD_MUTEX(un));
8638 		(void) untimeout(temp_id);
8639 		mutex_enter(SD_MUTEX(un));
8640 	}
8641 
8642 	if (un->un_reset_throttle_timeid != NULL) {
8643 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8644 		un->un_reset_throttle_timeid = NULL;
8645 		mutex_exit(SD_MUTEX(un));
8646 		(void) untimeout(temp_id);
8647 		mutex_enter(SD_MUTEX(un));
8648 	}
8649 
8650 	if (un->un_startstop_timeid != NULL) {
8651 		timeout_id_t temp_id = un->un_startstop_timeid;
8652 		un->un_startstop_timeid = NULL;
8653 		mutex_exit(SD_MUTEX(un));
8654 		(void) untimeout(temp_id);
8655 		mutex_enter(SD_MUTEX(un));
8656 	}
8657 
8658 	if (un->un_rmw_msg_timeid != NULL) {
8659 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8660 		un->un_rmw_msg_timeid = NULL;
8661 		mutex_exit(SD_MUTEX(un));
8662 		(void) untimeout(temp_id);
8663 		mutex_enter(SD_MUTEX(un));
8664 	}
8665 
8666 	if (un->un_dcvb_timeid != NULL) {
8667 		timeout_id_t temp_id = un->un_dcvb_timeid;
8668 		un->un_dcvb_timeid = NULL;
8669 		mutex_exit(SD_MUTEX(un));
8670 		(void) untimeout(temp_id);
8671 	} else {
8672 		mutex_exit(SD_MUTEX(un));
8673 	}
8674 
8675 	/* Remove any pending reservation reclaim requests for this device */
8676 	sd_rmv_resv_reclaim_req(dev);
8677 
8678 	mutex_enter(SD_MUTEX(un));
8679 
8680 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8681 	if (un->un_direct_priority_timeid != NULL) {
8682 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8683 		un->un_direct_priority_timeid = NULL;
8684 		mutex_exit(SD_MUTEX(un));
8685 		(void) untimeout(temp_id);
8686 		mutex_enter(SD_MUTEX(un));
8687 	}
8688 
8689 	/* Cancel any active multi-host disk watch thread requests */
8690 	if (un->un_mhd_token != NULL) {
8691 		mutex_exit(SD_MUTEX(un));
8692 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8693 		if (scsi_watch_request_terminate(un->un_mhd_token,
8694 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8695 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8696 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8697 			/*
8698 			 * Note: We are returning here after having removed
8699 			 * some driver timeouts above. This is consistent with
8700 			 * the legacy implementation but perhaps the watch
8701 			 * terminate call should be made with the wait flag set.
8702 			 */
8703 			goto err_stillbusy;
8704 		}
8705 		mutex_enter(SD_MUTEX(un));
8706 		un->un_mhd_token = NULL;
8707 	}
8708 
8709 	if (un->un_swr_token != NULL) {
8710 		mutex_exit(SD_MUTEX(un));
8711 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8712 		if (scsi_watch_request_terminate(un->un_swr_token,
8713 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8714 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8715 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8716 			/*
8717 			 * Note: We are returning here after having removed
8718 			 * some driver timeouts above. This is consistent with
8719 			 * the legacy implementation but perhaps the watch
8720 			 * terminate call should be made with the wait flag set.
8721 			 */
8722 			goto err_stillbusy;
8723 		}
8724 		mutex_enter(SD_MUTEX(un));
8725 		un->un_swr_token = NULL;
8726 	}
8727 
8728 	mutex_exit(SD_MUTEX(un));
8729 
8730 	/*
8731 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8732 	 * if we have not registered one.
8733 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8734 	 */
8735 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8736 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8737 
8738 	/*
8739 	 * protect the timeout pointers from getting nulled by
8740 	 * their callback functions during the cancellation process.
8741 	 * In such a scenario untimeout can be invoked with a null value.
8742 	 */
8743 	_NOTE(NO_COMPETING_THREADS_NOW);
8744 
8745 	mutex_enter(&un->un_pm_mutex);
8746 	if (un->un_pm_idle_timeid != NULL) {
8747 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8748 		un->un_pm_idle_timeid = NULL;
8749 		mutex_exit(&un->un_pm_mutex);
8750 
8751 		/*
8752 		 * Timeout is active; cancel it.
8753 		 * Note that it'll never be active on a device
8754 		 * that does not support PM therefore we don't
8755 		 * have to check before calling pm_idle_component.
8756 		 */
8757 		(void) untimeout(temp_id);
8758 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8759 		mutex_enter(&un->un_pm_mutex);
8760 	}
8761 
8762 	/*
8763 	 * Check whether there is already a timeout scheduled for power
8764 	 * management. If yes then don't lower the power here, that's.
8765 	 * the timeout handler's job.
8766 	 */
8767 	if (un->un_pm_timeid != NULL) {
8768 		timeout_id_t temp_id = un->un_pm_timeid;
8769 		un->un_pm_timeid = NULL;
8770 		mutex_exit(&un->un_pm_mutex);
8771 		/*
8772 		 * Timeout is active; cancel it.
8773 		 * Note that it'll never be active on a device
8774 		 * that does not support PM therefore we don't
8775 		 * have to check before calling pm_idle_component.
8776 		 */
8777 		(void) untimeout(temp_id);
8778 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8779 
8780 	} else {
8781 		mutex_exit(&un->un_pm_mutex);
8782 		if ((un->un_f_pm_is_enabled == TRUE) &&
8783 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_PM_STATE_STOPPED(un))
8784 		    != DDI_SUCCESS)) {
8785 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8786 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8787 			/*
8788 			 * Fix for bug: 4297749, item # 13
8789 			 * The above test now includes a check to see if PM is
8790 			 * supported by this device before call
8791 			 * pm_lower_power().
8792 			 * Note, the following is not dead code. The call to
8793 			 * pm_lower_power above will generate a call back into
8794 			 * our sdpower routine which might result in a timeout
8795 			 * handler getting activated. Therefore the following
8796 			 * code is valid and necessary.
8797 			 */
8798 			mutex_enter(&un->un_pm_mutex);
8799 			if (un->un_pm_timeid != NULL) {
8800 				timeout_id_t temp_id = un->un_pm_timeid;
8801 				un->un_pm_timeid = NULL;
8802 				mutex_exit(&un->un_pm_mutex);
8803 				(void) untimeout(temp_id);
8804 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8805 			} else {
8806 				mutex_exit(&un->un_pm_mutex);
8807 			}
8808 		}
8809 	}
8810 
8811 	/*
8812 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8813 	 * Relocated here from above to be after the call to
8814 	 * pm_lower_power, which was getting errors.
8815 	 */
8816 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8817 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8818 
8819 	/*
8820 	 * Currently, tagged queuing is supported per target based by HBA.
8821 	 * Setting this per lun instance actually sets the capability of this
8822 	 * target in HBA, which affects those luns already attached on the
8823 	 * same target. So during detach, we can only disable this capability
8824 	 * only when this is the only lun left on this target. By doing
8825 	 * this, we assume a target has the same tagged queuing capability
8826 	 * for every lun. The condition can be removed when HBA is changed to
8827 	 * support per lun based tagged queuing capability.
8828 	 */
8829 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
8830 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8831 	}
8832 
8833 	if (un->un_f_is_fibre == FALSE) {
8834 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8835 	}
8836 
8837 	/*
8838 	 * Remove any event callbacks, fibre only
8839 	 */
8840 	if (un->un_f_is_fibre == TRUE) {
8841 		if ((un->un_insert_event != NULL) &&
8842 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
8843 		    DDI_SUCCESS)) {
8844 			/*
8845 			 * Note: We are returning here after having done
8846 			 * substantial cleanup above. This is consistent
8847 			 * with the legacy implementation but this may not
8848 			 * be the right thing to do.
8849 			 */
8850 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8851 			    "sd_dr_detach: Cannot cancel insert event\n");
8852 			goto err_remove_event;
8853 		}
8854 		un->un_insert_event = NULL;
8855 
8856 		if ((un->un_remove_event != NULL) &&
8857 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
8858 		    DDI_SUCCESS)) {
8859 			/*
8860 			 * Note: We are returning here after having done
8861 			 * substantial cleanup above. This is consistent
8862 			 * with the legacy implementation but this may not
8863 			 * be the right thing to do.
8864 			 */
8865 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8866 			    "sd_dr_detach: Cannot cancel remove event\n");
8867 			goto err_remove_event;
8868 		}
8869 		un->un_remove_event = NULL;
8870 	}
8871 
8872 	/* Do not free the softstate if the callback routine is active */
8873 	sd_sync_with_callback(un);
8874 
8875 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
8876 	cmlb_free_handle(&un->un_cmlbhandle);
8877 
8878 	/*
8879 	 * Clean up the soft state struct.
8880 	 * Cleanup is done in reverse order of allocs/inits.
8881 	 * At this point there should be no competing threads anymore.
8882 	 */
8883 
8884 	scsi_fm_fini(devp);
8885 
8886 	/*
8887 	 * Deallocate memory for SCSI FMA.
8888 	 */
8889 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8890 
8891 	/*
8892 	 * Unregister and free device id if it was not registered
8893 	 * by the transport.
8894 	 */
8895 	if (un->un_f_devid_transport_defined == FALSE)
8896 		ddi_devid_unregister(devi);
8897 
8898 	/*
8899 	 * free the devid structure if allocated before (by ddi_devid_init()
8900 	 * or ddi_devid_get()).
8901 	 */
8902 	if (un->un_devid) {
8903 		ddi_devid_free(un->un_devid);
8904 		un->un_devid = NULL;
8905 	}
8906 
8907 	/*
8908 	 * Destroy wmap cache if it exists.
8909 	 */
8910 	if (un->un_wm_cache != NULL) {
8911 		kmem_cache_destroy(un->un_wm_cache);
8912 		un->un_wm_cache = NULL;
8913 	}
8914 
8915 	/*
8916 	 * kstat cleanup is done in detach for all device types (4363169).
8917 	 * We do not want to fail detach if the device kstats are not deleted
8918 	 * since there is a confusion about the devo_refcnt for the device.
8919 	 * We just delete the kstats and let detach complete successfully.
8920 	 */
8921 	if (un->un_stats != NULL) {
8922 		kstat_delete(un->un_stats);
8923 		un->un_stats = NULL;
8924 	}
8925 	if (un->un_unmapstats != NULL) {
8926 		kstat_delete(un->un_unmapstats_ks);
8927 		un->un_unmapstats_ks = NULL;
8928 		un->un_unmapstats = NULL;
8929 	}
8930 	if (un->un_errstats != NULL) {
8931 		kstat_delete(un->un_errstats);
8932 		un->un_errstats = NULL;
8933 	}
8934 
8935 	/* Remove partition stats */
8936 	if (un->un_f_pkstats_enabled) {
8937 		for (i = 0; i < NSDMAP; i++) {
8938 			if (un->un_pstats[i] != NULL) {
8939 				kstat_delete(un->un_pstats[i]);
8940 				un->un_pstats[i] = NULL;
8941 			}
8942 		}
8943 	}
8944 
8945 	/* Remove xbuf registration */
8946 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8947 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8948 
8949 	/* Remove driver properties */
8950 	ddi_prop_remove_all(devi);
8951 
8952 	mutex_destroy(&un->un_pm_mutex);
8953 	cv_destroy(&un->un_pm_busy_cv);
8954 
8955 	cv_destroy(&un->un_wcc_cv);
8956 
8957 	/* Removable media condvar. */
8958 	cv_destroy(&un->un_state_cv);
8959 
8960 	/* Suspend/resume condvar. */
8961 	cv_destroy(&un->un_suspend_cv);
8962 	cv_destroy(&un->un_disk_busy_cv);
8963 
8964 	sd_free_rqs(un);
8965 
8966 	/* Free up soft state */
8967 	devp->sd_private = NULL;
8968 
8969 	bzero(un, sizeof (struct sd_lun));
8970 
8971 	ddi_soft_state_free(sd_state, instance);
8972 
8973 	/* This frees up the INQUIRY data associated with the device. */
8974 	scsi_unprobe(devp);
8975 
8976 	/*
8977 	 * After successfully detaching an instance, we update the information
8978 	 * of how many luns have been attached in the relative target and
8979 	 * controller for parallel SCSI. This information is used when sd tries
8980 	 * to set the tagged queuing capability in HBA.
8981 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8982 	 * check if the device is parallel SCSI. However, we don't need to
8983 	 * check here because we've already checked during attach. No device
8984 	 * that is not parallel SCSI is in the chain.
8985 	 */
8986 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8987 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8988 	}
8989 
8990 	return (DDI_SUCCESS);
8991 
8992 err_notclosed:
8993 	mutex_exit(SD_MUTEX(un));
8994 
8995 err_stillbusy:
8996 	_NOTE(NO_COMPETING_THREADS_NOW);
8997 
8998 err_remove_event:
8999 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
9000 	return (DDI_FAILURE);
9001 }
9002 
9003 
9004 /*
9005  *    Function: sd_create_errstats
9006  *
9007  * Description: This routine instantiates the device error stats.
9008  *
9009  *		Note: During attach the stats are instantiated first so they are
9010  *		available for attach-time routines that utilize the driver
9011  *		iopath to send commands to the device. The stats are initialized
9012  *		separately so data obtained during some attach-time routines is
9013  *		available. (4362483)
9014  *
9015  *   Arguments: un - driver soft state (unit) structure
9016  *		instance - driver instance
9017  *
9018  *     Context: Kernel thread context
9019  */
9020 
9021 static void
9022 sd_create_errstats(struct sd_lun *un, int instance)
9023 {
9024 	struct	sd_errstats	*stp;
9025 	char	kstatmodule_err[KSTAT_STRLEN];
9026 	char	kstatname[KSTAT_STRLEN];
9027 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
9028 
9029 	ASSERT(un != NULL);
9030 
9031 	if (un->un_errstats != NULL) {
9032 		return;
9033 	}
9034 
9035 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
9036 	    "%serr", sd_label);
9037 	(void) snprintf(kstatname, sizeof (kstatname),
9038 	    "%s%d,err", sd_label, instance);
9039 
9040 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
9041 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
9042 
9043 	if (un->un_errstats == NULL) {
9044 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
9045 		    "sd_create_errstats: Failed kstat_create\n");
9046 		return;
9047 	}
9048 
9049 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9050 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
9051 	    KSTAT_DATA_UINT32);
9052 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
9053 	    KSTAT_DATA_UINT32);
9054 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
9055 	    KSTAT_DATA_UINT32);
9056 	kstat_named_init(&stp->sd_vid,		"Vendor",
9057 	    KSTAT_DATA_CHAR);
9058 	kstat_named_init(&stp->sd_pid,		"Product",
9059 	    KSTAT_DATA_CHAR);
9060 	kstat_named_init(&stp->sd_revision,	"Revision",
9061 	    KSTAT_DATA_CHAR);
9062 	kstat_named_init(&stp->sd_serial,	"Serial No",
9063 	    KSTAT_DATA_CHAR);
9064 	kstat_named_init(&stp->sd_capacity,	"Size",
9065 	    KSTAT_DATA_ULONGLONG);
9066 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
9067 	    KSTAT_DATA_UINT32);
9068 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
9069 	    KSTAT_DATA_UINT32);
9070 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
9071 	    KSTAT_DATA_UINT32);
9072 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
9073 	    KSTAT_DATA_UINT32);
9074 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
9075 	    KSTAT_DATA_UINT32);
9076 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
9077 	    KSTAT_DATA_UINT32);
9078 
9079 	un->un_errstats->ks_private = un;
9080 	un->un_errstats->ks_update  = nulldev;
9081 
9082 	kstat_install(un->un_errstats);
9083 }
9084 
9085 
9086 /*
9087  *    Function: sd_set_errstats
9088  *
9089  * Description: This routine sets the value of the vendor id, product id,
9090  *		revision, serial number, and capacity device error stats.
9091  *
9092  *		Note: During attach the stats are instantiated first so they are
9093  *		available for attach-time routines that utilize the driver
9094  *		iopath to send commands to the device. The stats are initialized
9095  *		separately so data obtained during some attach-time routines is
9096  *		available. (4362483)
9097  *
9098  *   Arguments: un - driver soft state (unit) structure
9099  *
9100  *     Context: Kernel thread context
9101  */
9102 
9103 static void
9104 sd_set_errstats(struct sd_lun *un)
9105 {
9106 	struct	sd_errstats	*stp;
9107 	char			*sn;
9108 
9109 	ASSERT(un != NULL);
9110 	ASSERT(un->un_errstats != NULL);
9111 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9112 	ASSERT(stp != NULL);
9113 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
9114 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
9115 	(void) strncpy(stp->sd_revision.value.c,
9116 	    un->un_sd->sd_inq->inq_revision, 4);
9117 
9118 	/*
9119 	 * All the errstats are persistent across detach/attach,
9120 	 * so reset all the errstats here in case of the hot
9121 	 * replacement of disk drives, except for not changed
9122 	 * Sun qualified drives.
9123 	 */
9124 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
9125 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9126 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
9127 		stp->sd_softerrs.value.ui32 = 0;
9128 		stp->sd_harderrs.value.ui32 = 0;
9129 		stp->sd_transerrs.value.ui32 = 0;
9130 		stp->sd_rq_media_err.value.ui32 = 0;
9131 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
9132 		stp->sd_rq_nodev_err.value.ui32 = 0;
9133 		stp->sd_rq_recov_err.value.ui32 = 0;
9134 		stp->sd_rq_illrq_err.value.ui32 = 0;
9135 		stp->sd_rq_pfa_err.value.ui32 = 0;
9136 	}
9137 
9138 	/*
9139 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
9140 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
9141 	 * (4376302))
9142 	 */
9143 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
9144 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9145 		    sizeof (SD_INQUIRY(un)->inq_serial));
9146 	} else {
9147 		/*
9148 		 * Set the "Serial No" kstat for non-Sun qualified drives
9149 		 */
9150 		if (ddi_prop_lookup_string(DDI_DEV_T_ANY, SD_DEVINFO(un),
9151 		    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
9152 		    INQUIRY_SERIAL_NO, &sn) == DDI_SUCCESS) {
9153 			(void) strlcpy(stp->sd_serial.value.c, sn,
9154 			    sizeof (stp->sd_serial.value.c));
9155 			ddi_prop_free(sn);
9156 		}
9157 	}
9158 
9159 	if (un->un_f_blockcount_is_valid != TRUE) {
9160 		/*
9161 		 * Set capacity error stat to 0 for no media. This ensures
9162 		 * a valid capacity is displayed in response to 'iostat -E'
9163 		 * when no media is present in the device.
9164 		 */
9165 		stp->sd_capacity.value.ui64 = 0;
9166 	} else {
9167 		/*
9168 		 * Multiply un_blockcount by un->un_sys_blocksize to get
9169 		 * capacity.
9170 		 *
9171 		 * Note: for non-512 blocksize devices "un_blockcount" has been
9172 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
9173 		 * (un_tgt_blocksize / un->un_sys_blocksize).
9174 		 */
9175 		stp->sd_capacity.value.ui64 = (uint64_t)
9176 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
9177 	}
9178 }
9179 
9180 
9181 /*
9182  *    Function: sd_set_pstats
9183  *
9184  * Description: This routine instantiates and initializes the partition
9185  *              stats for each partition with more than zero blocks.
9186  *		(4363169)
9187  *
9188  *   Arguments: un - driver soft state (unit) structure
9189  *
9190  *     Context: Kernel thread context
9191  */
9192 
9193 static void
9194 sd_set_pstats(struct sd_lun *un)
9195 {
9196 	char	kstatname[KSTAT_STRLEN];
9197 	int	instance;
9198 	int	i;
9199 	diskaddr_t	nblks = 0;
9200 	char	*partname = NULL;
9201 
9202 	ASSERT(un != NULL);
9203 
9204 	instance = ddi_get_instance(SD_DEVINFO(un));
9205 
9206 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
9207 	for (i = 0; i < NSDMAP; i++) {
9208 
9209 		if (cmlb_partinfo(un->un_cmlbhandle, i,
9210 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
9211 			continue;
9212 		mutex_enter(SD_MUTEX(un));
9213 
9214 		if ((un->un_pstats[i] == NULL) &&
9215 		    (nblks != 0)) {
9216 
9217 			(void) snprintf(kstatname, sizeof (kstatname),
9218 			    "%s%d,%s", sd_label, instance,
9219 			    partname);
9220 
9221 			un->un_pstats[i] = kstat_create(sd_label,
9222 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
9223 			    1, KSTAT_FLAG_PERSISTENT);
9224 			if (un->un_pstats[i] != NULL) {
9225 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
9226 				kstat_install(un->un_pstats[i]);
9227 			}
9228 		}
9229 		mutex_exit(SD_MUTEX(un));
9230 	}
9231 }
9232 
9233 
9234 #if (defined(__fibre))
9235 /*
9236  *    Function: sd_init_event_callbacks
9237  *
9238  * Description: This routine initializes the insertion and removal event
9239  *		callbacks. (fibre only)
9240  *
9241  *   Arguments: un - driver soft state (unit) structure
9242  *
9243  *     Context: Kernel thread context
9244  */
9245 
9246 static void
9247 sd_init_event_callbacks(struct sd_lun *un)
9248 {
9249 	ASSERT(un != NULL);
9250 
9251 	if ((un->un_insert_event == NULL) &&
9252 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
9253 	    &un->un_insert_event) == DDI_SUCCESS)) {
9254 		/*
9255 		 * Add the callback for an insertion event
9256 		 */
9257 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9258 		    un->un_insert_event, sd_event_callback, (void *)un,
9259 		    &(un->un_insert_cb_id));
9260 	}
9261 
9262 	if ((un->un_remove_event == NULL) &&
9263 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
9264 	    &un->un_remove_event) == DDI_SUCCESS)) {
9265 		/*
9266 		 * Add the callback for a removal event
9267 		 */
9268 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9269 		    un->un_remove_event, sd_event_callback, (void *)un,
9270 		    &(un->un_remove_cb_id));
9271 	}
9272 }
9273 
9274 
9275 /*
9276  *    Function: sd_event_callback
9277  *
9278  * Description: This routine handles insert/remove events (photon). The
9279  *		state is changed to OFFLINE which can be used to supress
9280  *		error msgs. (fibre only)
9281  *
9282  *   Arguments: un - driver soft state (unit) structure
9283  *
9284  *     Context: Callout thread context
9285  */
9286 /* ARGSUSED */
9287 static void
9288 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
9289     void *bus_impldata)
9290 {
9291 	struct sd_lun *un = (struct sd_lun *)arg;
9292 
9293 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
9294 	if (event == un->un_insert_event) {
9295 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
9296 		mutex_enter(SD_MUTEX(un));
9297 		if (un->un_state == SD_STATE_OFFLINE) {
9298 			if (un->un_last_state != SD_STATE_SUSPENDED) {
9299 				un->un_state = un->un_last_state;
9300 			} else {
9301 				/*
9302 				 * We have gone through SUSPEND/RESUME while
9303 				 * we were offline. Restore the last state
9304 				 */
9305 				un->un_state = un->un_save_state;
9306 			}
9307 		}
9308 		mutex_exit(SD_MUTEX(un));
9309 
9310 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
9311 	} else if (event == un->un_remove_event) {
9312 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
9313 		mutex_enter(SD_MUTEX(un));
9314 		/*
9315 		 * We need to handle an event callback that occurs during
9316 		 * the suspend operation, since we don't prevent it.
9317 		 */
9318 		if (un->un_state != SD_STATE_OFFLINE) {
9319 			if (un->un_state != SD_STATE_SUSPENDED) {
9320 				New_state(un, SD_STATE_OFFLINE);
9321 			} else {
9322 				un->un_last_state = SD_STATE_OFFLINE;
9323 			}
9324 		}
9325 		mutex_exit(SD_MUTEX(un));
9326 	} else {
9327 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
9328 		    "!Unknown event\n");
9329 	}
9330 
9331 }
9332 #endif
9333 
9334 /*
9335  * Values related to caching mode page depending on whether the unit is ATAPI.
9336  */
9337 #define	SDC_CDB_GROUP(un) ((un->un_f_cfg_is_atapi == TRUE) ? \
9338 	CDB_GROUP1 : CDB_GROUP0)
9339 #define	SDC_HDRLEN(un) ((un->un_f_cfg_is_atapi == TRUE) ? \
9340 	MODE_HEADER_LENGTH_GRP2 : MODE_HEADER_LENGTH)
9341 /*
9342  * Use mode_cache_scsi3 to ensure we get all of the mode sense data, otherwise
9343  * the mode select will fail (mode_cache_scsi3 is a superset of mode_caching).
9344  */
9345 #define	SDC_BUFLEN(un) (SDC_HDRLEN(un) + MODE_BLK_DESC_LENGTH + \
9346 	sizeof (struct mode_cache_scsi3))
9347 
9348 static int
9349 sd_get_caching_mode_page(sd_ssc_t *ssc, uchar_t page_control, uchar_t **header,
9350     int *bdlen)
9351 {
9352 	struct sd_lun	*un = ssc->ssc_un;
9353 	struct mode_caching *mode_caching_page;
9354 	size_t		buflen = SDC_BUFLEN(un);
9355 	int		hdrlen = SDC_HDRLEN(un);
9356 	int		rval;
9357 
9358 	/*
9359 	 * Do a test unit ready, otherwise a mode sense may not work if this
9360 	 * is the first command sent to the device after boot.
9361 	 */
9362 	if (sd_send_scsi_TEST_UNIT_READY(ssc, 0) != 0)
9363 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9364 
9365 	/*
9366 	 * Allocate memory for the retrieved mode page and its headers.  Set
9367 	 * a pointer to the page itself.
9368 	 */
9369 	*header = kmem_zalloc(buflen, KM_SLEEP);
9370 
9371 	/* Get the information from the device */
9372 	rval = sd_send_scsi_MODE_SENSE(ssc, SDC_CDB_GROUP(un), *header, buflen,
9373 	    page_control | MODEPAGE_CACHING, SD_PATH_DIRECT);
9374 	if (rval != 0) {
9375 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un, "%s: Mode Sense Failed\n",
9376 		    __func__);
9377 		goto mode_sense_failed;
9378 	}
9379 
9380 	/*
9381 	 * Determine size of Block Descriptors in order to locate
9382 	 * the mode page data. ATAPI devices return 0, SCSI devices
9383 	 * should return MODE_BLK_DESC_LENGTH.
9384 	 */
9385 	if (un->un_f_cfg_is_atapi == TRUE) {
9386 		struct mode_header_grp2 *mhp =
9387 		    (struct mode_header_grp2 *)(*header);
9388 		*bdlen = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9389 	} else {
9390 		*bdlen = ((struct mode_header *)(*header))->bdesc_length;
9391 	}
9392 
9393 	if (*bdlen > MODE_BLK_DESC_LENGTH) {
9394 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9395 		    "%s: Mode Sense returned invalid block descriptor length\n",
9396 		    __func__);
9397 		rval = EIO;
9398 		goto mode_sense_failed;
9399 	}
9400 
9401 	mode_caching_page = (struct mode_caching *)(*header + hdrlen + *bdlen);
9402 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9403 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9404 		    "%s: Mode Sense caching page code mismatch %d\n",
9405 		    __func__, mode_caching_page->mode_page.code);
9406 		rval = EIO;
9407 	}
9408 
9409 mode_sense_failed:
9410 	if (rval != 0) {
9411 		kmem_free(*header, buflen);
9412 		*header = NULL;
9413 		*bdlen = 0;
9414 	}
9415 	return (rval);
9416 }
9417 
9418 /*
9419  *    Function: sd_cache_control()
9420  *
9421  * Description: This routine is the driver entry point for setting
9422  *		read and write caching by modifying the WCE (write cache
9423  *		enable) and RCD (read cache disable) bits of mode
9424  *		page 8 (MODEPAGE_CACHING).
9425  *
9426  *   Arguments: ssc		- ssc contains pointer to driver soft state
9427  *				  (unit) structure for this target.
9428  *		rcd_flag	- flag for controlling the read cache
9429  *		wce_flag	- flag for controlling the write cache
9430  *
9431  * Return Code: EIO
9432  *		code returned by sd_send_scsi_MODE_SENSE and
9433  *		sd_send_scsi_MODE_SELECT
9434  *
9435  *     Context: Kernel Thread
9436  */
9437 
9438 static int
9439 sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag)
9440 {
9441 	struct sd_lun	*un = ssc->ssc_un;
9442 	struct mode_caching *mode_caching_page;
9443 	uchar_t		*header;
9444 	size_t		buflen = SDC_BUFLEN(un);
9445 	int		hdrlen = SDC_HDRLEN(un);
9446 	int		bdlen;
9447 	int		rval;
9448 
9449 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CURRENT, &header, &bdlen);
9450 	switch (rval) {
9451 	case 0:
9452 		/* Check the relevant bits on successful mode sense */
9453 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9454 		    bdlen);
9455 		if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
9456 		    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
9457 		    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
9458 		    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
9459 			size_t sbuflen;
9460 			uchar_t save_pg;
9461 
9462 			/*
9463 			 * Construct select buffer length based on the
9464 			 * length of the sense data returned.
9465 			 */
9466 			sbuflen = hdrlen + bdlen + sizeof (struct mode_page) +
9467 			    (int)mode_caching_page->mode_page.length;
9468 
9469 			/* Set the caching bits as requested */
9470 			if (rcd_flag == SD_CACHE_ENABLE)
9471 				mode_caching_page->rcd = 0;
9472 			else if (rcd_flag == SD_CACHE_DISABLE)
9473 				mode_caching_page->rcd = 1;
9474 
9475 			if (wce_flag == SD_CACHE_ENABLE)
9476 				mode_caching_page->wce = 1;
9477 			else if (wce_flag == SD_CACHE_DISABLE)
9478 				mode_caching_page->wce = 0;
9479 
9480 			/*
9481 			 * Save the page if the mode sense says the
9482 			 * drive supports it.
9483 			 */
9484 			save_pg = mode_caching_page->mode_page.ps ?
9485 			    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
9486 
9487 			/* Clear reserved bits before mode select */
9488 			mode_caching_page->mode_page.ps = 0;
9489 
9490 			/*
9491 			 * Clear out mode header for mode select.
9492 			 * The rest of the retrieved page will be reused.
9493 			 */
9494 			bzero(header, hdrlen);
9495 
9496 			if (un->un_f_cfg_is_atapi == TRUE) {
9497 				struct mode_header_grp2 *mhp =
9498 				    (struct mode_header_grp2 *)header;
9499 				mhp->bdesc_length_hi = bdlen >> 8;
9500 				mhp->bdesc_length_lo = (uchar_t)bdlen & 0xff;
9501 			} else {
9502 				((struct mode_header *)header)->bdesc_length =
9503 				    bdlen;
9504 			}
9505 
9506 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9507 
9508 			/* Issue mode select to change the cache settings */
9509 			rval = sd_send_scsi_MODE_SELECT(ssc, SDC_CDB_GROUP(un),
9510 			    header, sbuflen, save_pg, SD_PATH_DIRECT);
9511 		}
9512 		kmem_free(header, buflen);
9513 		break;
9514 	case EIO:
9515 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9516 		break;
9517 	default:
9518 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9519 		break;
9520 	}
9521 
9522 	return (rval);
9523 }
9524 
9525 
9526 /*
9527  *    Function: sd_get_write_cache_enabled()
9528  *
9529  * Description: This routine is the driver entry point for determining if write
9530  *		caching is enabled.  It examines the WCE (write cache enable)
9531  *		bits of mode page 8 (MODEPAGE_CACHING) with Page Control field
9532  *		bits set to MODEPAGE_CURRENT.
9533  *
9534  *   Arguments: ssc		- ssc contains pointer to driver soft state
9535  *				  (unit) structure for this target.
9536  *		is_enabled	- pointer to int where write cache enabled state
9537  *				  is returned (non-zero -> write cache enabled)
9538  *
9539  * Return Code: EIO
9540  *		code returned by sd_send_scsi_MODE_SENSE
9541  *
9542  *     Context: Kernel Thread
9543  *
9544  * NOTE: If ioctl is added to disable write cache, this sequence should
9545  * be followed so that no locking is required for accesses to
9546  * un->un_f_write_cache_enabled:
9547  *	do mode select to clear wce
9548  *	do synchronize cache to flush cache
9549  *	set un->un_f_write_cache_enabled = FALSE
9550  *
9551  * Conversely, an ioctl to enable the write cache should be done
9552  * in this order:
9553  *	set un->un_f_write_cache_enabled = TRUE
9554  *	do mode select to set wce
9555  */
9556 
9557 static int
9558 sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled)
9559 {
9560 	struct sd_lun	*un = ssc->ssc_un;
9561 	struct mode_caching *mode_caching_page;
9562 	uchar_t		*header;
9563 	size_t		buflen = SDC_BUFLEN(un);
9564 	int		hdrlen = SDC_HDRLEN(un);
9565 	int		bdlen;
9566 	int		rval;
9567 
9568 	/* In case of error, flag as enabled */
9569 	*is_enabled = TRUE;
9570 
9571 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CURRENT, &header, &bdlen);
9572 	switch (rval) {
9573 	case 0:
9574 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9575 		    bdlen);
9576 		*is_enabled = mode_caching_page->wce;
9577 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9578 		kmem_free(header, buflen);
9579 		break;
9580 	case EIO: {
9581 		/*
9582 		 * Some disks do not support Mode Sense(6), we
9583 		 * should ignore this kind of error (sense key is
9584 		 * 0x5 - illegal request).
9585 		 */
9586 		uint8_t *sensep;
9587 		int senlen;
9588 
9589 		sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
9590 		senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
9591 		    ssc->ssc_uscsi_cmd->uscsi_rqresid);
9592 
9593 		if (senlen > 0 &&
9594 		    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
9595 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
9596 		} else {
9597 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9598 		}
9599 		break;
9600 	}
9601 	default:
9602 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9603 		break;
9604 	}
9605 
9606 	return (rval);
9607 }
9608 
9609 /*
9610  *    Function: sd_get_write_cache_changeable()
9611  *
9612  * Description: This routine is the driver entry point for determining if write
9613  *		caching is changeable.  It examines the WCE (write cache enable)
9614  *		bits of mode page 8 (MODEPAGE_CACHING) with Page Control field
9615  *		bits set to MODEPAGE_CHANGEABLE.
9616  *
9617  *   Arguments: ssc		- ssc contains pointer to driver soft state
9618  *				  (unit) structure for this target.
9619  *		is_changeable	- pointer to int where write cache changeable
9620  *				  state is returned (non-zero -> write cache
9621  *				  changeable)
9622  *
9623  *     Context: Kernel Thread
9624  */
9625 
9626 static void
9627 sd_get_write_cache_changeable(sd_ssc_t *ssc, int *is_changeable)
9628 {
9629 	struct sd_lun	*un = ssc->ssc_un;
9630 	struct mode_caching *mode_caching_page;
9631 	uchar_t		*header;
9632 	size_t		buflen = SDC_BUFLEN(un);
9633 	int		hdrlen = SDC_HDRLEN(un);
9634 	int		bdlen;
9635 	int		rval;
9636 
9637 	/* In case of error, flag as enabled */
9638 	*is_changeable = TRUE;
9639 
9640 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CHANGEABLE, &header,
9641 	    &bdlen);
9642 	switch (rval) {
9643 	case 0:
9644 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9645 		    bdlen);
9646 		*is_changeable = mode_caching_page->wce;
9647 		kmem_free(header, buflen);
9648 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9649 		break;
9650 	case EIO:
9651 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9652 		break;
9653 	default:
9654 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9655 		break;
9656 	}
9657 }
9658 
9659 /*
9660  *    Function: sd_get_nv_sup()
9661  *
9662  * Description: This routine is the driver entry point for
9663  * determining whether non-volatile cache is supported. This
9664  * determination process works as follows:
9665  *
9666  * 1. sd first queries sd.conf on whether
9667  * suppress_cache_flush bit is set for this device.
9668  *
9669  * 2. if not there, then queries the internal disk table.
9670  *
9671  * 3. if either sd.conf or internal disk table specifies
9672  * cache flush be suppressed, we don't bother checking
9673  * NV_SUP bit.
9674  *
9675  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
9676  * the optional INQUIRY VPD page 0x86. If the device
9677  * supports VPD page 0x86, sd examines the NV_SUP
9678  * (non-volatile cache support) bit in the INQUIRY VPD page
9679  * 0x86:
9680  *   o If NV_SUP bit is set, sd assumes the device has a
9681  *   non-volatile cache and set the
9682  *   un_f_sync_nv_supported to TRUE.
9683  *   o Otherwise cache is not non-volatile,
9684  *   un_f_sync_nv_supported is set to FALSE.
9685  *
9686  * Arguments: un - driver soft state (unit) structure
9687  *
9688  * Return Code:
9689  *
9690  *     Context: Kernel Thread
9691  */
9692 
9693 static void
9694 sd_get_nv_sup(sd_ssc_t *ssc)
9695 {
9696 	int		rval		= 0;
9697 	uchar_t		*inq86		= NULL;
9698 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
9699 	size_t		inq86_resid	= 0;
9700 	struct		dk_callback *dkc;
9701 	struct sd_lun	*un;
9702 
9703 	ASSERT(ssc != NULL);
9704 	un = ssc->ssc_un;
9705 	ASSERT(un != NULL);
9706 
9707 	mutex_enter(SD_MUTEX(un));
9708 
9709 	/*
9710 	 * Be conservative on the device's support of
9711 	 * SYNC_NV bit: un_f_sync_nv_supported is
9712 	 * initialized to be false.
9713 	 */
9714 	un->un_f_sync_nv_supported = FALSE;
9715 
9716 	/*
9717 	 * If either sd.conf or internal disk table
9718 	 * specifies cache flush be suppressed, then
9719 	 * we don't bother checking NV_SUP bit.
9720 	 */
9721 	if (un->un_f_suppress_cache_flush == TRUE) {
9722 		mutex_exit(SD_MUTEX(un));
9723 		return;
9724 	}
9725 
9726 	if (sd_check_vpd_page_support(ssc) == 0 &&
9727 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
9728 		mutex_exit(SD_MUTEX(un));
9729 		/* collect page 86 data if available */
9730 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
9731 
9732 		rval = sd_send_scsi_INQUIRY(ssc, inq86, inq86_len,
9733 		    0x01, 0x86, &inq86_resid);
9734 
9735 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
9736 			SD_TRACE(SD_LOG_COMMON, un,
9737 			    "sd_get_nv_sup: \
9738 			    successfully get VPD page: %x \
9739 			    PAGE LENGTH: %x BYTE 6: %x\n",
9740 			    inq86[1], inq86[3], inq86[6]);
9741 
9742 			mutex_enter(SD_MUTEX(un));
9743 			/*
9744 			 * check the value of NV_SUP bit: only if the device
9745 			 * reports NV_SUP bit to be 1, the
9746 			 * un_f_sync_nv_supported bit will be set to true.
9747 			 */
9748 			if (inq86[6] & SD_VPD_NV_SUP) {
9749 				un->un_f_sync_nv_supported = TRUE;
9750 			}
9751 			mutex_exit(SD_MUTEX(un));
9752 		} else if (rval != 0) {
9753 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9754 		}
9755 
9756 		kmem_free(inq86, inq86_len);
9757 	} else {
9758 		mutex_exit(SD_MUTEX(un));
9759 	}
9760 
9761 	/*
9762 	 * Send a SYNC CACHE command to check whether
9763 	 * SYNC_NV bit is supported. This command should have
9764 	 * un_f_sync_nv_supported set to correct value.
9765 	 */
9766 	mutex_enter(SD_MUTEX(un));
9767 	if (un->un_f_sync_nv_supported) {
9768 		mutex_exit(SD_MUTEX(un));
9769 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
9770 		dkc->dkc_flag = FLUSH_VOLATILE;
9771 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
9772 
9773 		/*
9774 		 * Send a TEST UNIT READY command to the device. This should
9775 		 * clear any outstanding UNIT ATTENTION that may be present.
9776 		 */
9777 		rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
9778 		if (rval != 0)
9779 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9780 
9781 		kmem_free(dkc, sizeof (struct dk_callback));
9782 	} else {
9783 		mutex_exit(SD_MUTEX(un));
9784 	}
9785 
9786 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
9787 	    un_f_suppress_cache_flush is set to %d\n",
9788 	    un->un_f_suppress_cache_flush);
9789 }
9790 
9791 /*
9792  *    Function: sd_make_device
9793  *
9794  * Description: Utility routine to return the Solaris device number from
9795  *		the data in the device's dev_info structure.
9796  *
9797  * Return Code: The Solaris device number
9798  *
9799  *     Context: Any
9800  */
9801 
9802 static dev_t
9803 sd_make_device(dev_info_t *devi)
9804 {
9805 	return (makedevice(ddi_driver_major(devi),
9806 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9807 }
9808 
9809 
9810 /*
9811  *    Function: sd_pm_entry
9812  *
9813  * Description: Called at the start of a new command to manage power
9814  *		and busy status of a device. This includes determining whether
9815  *		the current power state of the device is sufficient for
9816  *		performing the command or whether it must be changed.
9817  *		The PM framework is notified appropriately.
9818  *		Only with a return status of DDI_SUCCESS will the
9819  *		component be busy to the framework.
9820  *
9821  *		All callers of sd_pm_entry must check the return status
9822  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9823  *		of DDI_FAILURE indicates the device failed to power up.
9824  *		In this case un_pm_count has been adjusted so the result
9825  *		on exit is still powered down, ie. count is less than 0.
9826  *		Calling sd_pm_exit with this count value hits an ASSERT.
9827  *
9828  * Return Code: DDI_SUCCESS or DDI_FAILURE
9829  *
9830  *     Context: Kernel thread context.
9831  */
9832 
9833 static int
9834 sd_pm_entry(struct sd_lun *un)
9835 {
9836 	int return_status = DDI_SUCCESS;
9837 
9838 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9839 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9840 
9841 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9842 
9843 	if (un->un_f_pm_is_enabled == FALSE) {
9844 		SD_TRACE(SD_LOG_IO_PM, un,
9845 		    "sd_pm_entry: exiting, PM not enabled\n");
9846 		return (return_status);
9847 	}
9848 
9849 	/*
9850 	 * Just increment a counter if PM is enabled. On the transition from
9851 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9852 	 * the count with each IO and mark the device as idle when the count
9853 	 * hits 0.
9854 	 *
9855 	 * If the count is less than 0 the device is powered down. If a powered
9856 	 * down device is successfully powered up then the count must be
9857 	 * incremented to reflect the power up. Note that it'll get incremented
9858 	 * a second time to become busy.
9859 	 *
9860 	 * Because the following has the potential to change the device state
9861 	 * and must release the un_pm_mutex to do so, only one thread can be
9862 	 * allowed through at a time.
9863 	 */
9864 
9865 	mutex_enter(&un->un_pm_mutex);
9866 	while (un->un_pm_busy == TRUE) {
9867 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9868 	}
9869 	un->un_pm_busy = TRUE;
9870 
9871 	if (un->un_pm_count < 1) {
9872 
9873 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9874 
9875 		/*
9876 		 * Indicate we are now busy so the framework won't attempt to
9877 		 * power down the device. This call will only fail if either
9878 		 * we passed a bad component number or the device has no
9879 		 * components. Neither of these should ever happen.
9880 		 */
9881 		mutex_exit(&un->un_pm_mutex);
9882 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9883 		ASSERT(return_status == DDI_SUCCESS);
9884 
9885 		mutex_enter(&un->un_pm_mutex);
9886 
9887 		if (un->un_pm_count < 0) {
9888 			mutex_exit(&un->un_pm_mutex);
9889 
9890 			SD_TRACE(SD_LOG_IO_PM, un,
9891 			    "sd_pm_entry: power up component\n");
9892 
9893 			/*
9894 			 * pm_raise_power will cause sdpower to be called
9895 			 * which brings the device power level to the
9896 			 * desired state, If successful, un_pm_count and
9897 			 * un_power_level will be updated appropriately.
9898 			 */
9899 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9900 			    SD_PM_STATE_ACTIVE(un));
9901 
9902 			mutex_enter(&un->un_pm_mutex);
9903 
9904 			if (return_status != DDI_SUCCESS) {
9905 				/*
9906 				 * Power up failed.
9907 				 * Idle the device and adjust the count
9908 				 * so the result on exit is that we're
9909 				 * still powered down, ie. count is less than 0.
9910 				 */
9911 				SD_TRACE(SD_LOG_IO_PM, un,
9912 				    "sd_pm_entry: power up failed,"
9913 				    " idle the component\n");
9914 
9915 				(void) pm_idle_component(SD_DEVINFO(un), 0);
9916 				un->un_pm_count--;
9917 			} else {
9918 				/*
9919 				 * Device is powered up, verify the
9920 				 * count is non-negative.
9921 				 * This is debug only.
9922 				 */
9923 				ASSERT(un->un_pm_count == 0);
9924 			}
9925 		}
9926 
9927 		if (return_status == DDI_SUCCESS) {
9928 			/*
9929 			 * For performance, now that the device has been tagged
9930 			 * as busy, and it's known to be powered up, update the
9931 			 * chain types to use jump tables that do not include
9932 			 * pm. This significantly lowers the overhead and
9933 			 * therefore improves performance.
9934 			 */
9935 
9936 			mutex_exit(&un->un_pm_mutex);
9937 			mutex_enter(SD_MUTEX(un));
9938 			SD_TRACE(SD_LOG_IO_PM, un,
9939 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
9940 			    un->un_uscsi_chain_type);
9941 
9942 			if (un->un_f_non_devbsize_supported) {
9943 				un->un_buf_chain_type =
9944 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
9945 			} else {
9946 				un->un_buf_chain_type =
9947 				    SD_CHAIN_INFO_DISK_NO_PM;
9948 			}
9949 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
9950 
9951 			SD_TRACE(SD_LOG_IO_PM, un,
9952 			    "             changed  uscsi_chain_type to   %d\n",
9953 			    un->un_uscsi_chain_type);
9954 			mutex_exit(SD_MUTEX(un));
9955 			mutex_enter(&un->un_pm_mutex);
9956 
9957 			if (un->un_pm_idle_timeid == NULL) {
9958 				/* 300 ms. */
9959 				un->un_pm_idle_timeid =
9960 				    timeout(sd_pm_idletimeout_handler, un,
9961 				    (drv_usectohz((clock_t)300000)));
9962 				/*
9963 				 * Include an extra call to busy which keeps the
9964 				 * device busy with-respect-to the PM layer
9965 				 * until the timer fires, at which time it'll
9966 				 * get the extra idle call.
9967 				 */
9968 				(void) pm_busy_component(SD_DEVINFO(un), 0);
9969 			}
9970 		}
9971 	}
9972 	un->un_pm_busy = FALSE;
9973 	/* Next... */
9974 	cv_signal(&un->un_pm_busy_cv);
9975 
9976 	un->un_pm_count++;
9977 
9978 	SD_TRACE(SD_LOG_IO_PM, un,
9979 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
9980 
9981 	mutex_exit(&un->un_pm_mutex);
9982 
9983 	return (return_status);
9984 }
9985 
9986 
9987 /*
9988  *    Function: sd_pm_exit
9989  *
9990  * Description: Called at the completion of a command to manage busy
9991  *		status for the device. If the device becomes idle the
9992  *		PM framework is notified.
9993  *
9994  *     Context: Kernel thread context
9995  */
9996 
9997 static void
9998 sd_pm_exit(struct sd_lun *un)
9999 {
10000 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10001 	ASSERT(!mutex_owned(&un->un_pm_mutex));
10002 
10003 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
10004 
10005 	/*
10006 	 * After attach the following flag is only read, so don't
10007 	 * take the penalty of acquiring a mutex for it.
10008 	 */
10009 	if (un->un_f_pm_is_enabled == TRUE) {
10010 
10011 		mutex_enter(&un->un_pm_mutex);
10012 		un->un_pm_count--;
10013 
10014 		SD_TRACE(SD_LOG_IO_PM, un,
10015 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
10016 
10017 		ASSERT(un->un_pm_count >= 0);
10018 		if (un->un_pm_count == 0) {
10019 			mutex_exit(&un->un_pm_mutex);
10020 
10021 			SD_TRACE(SD_LOG_IO_PM, un,
10022 			    "sd_pm_exit: idle component\n");
10023 
10024 			(void) pm_idle_component(SD_DEVINFO(un), 0);
10025 
10026 		} else {
10027 			mutex_exit(&un->un_pm_mutex);
10028 		}
10029 	}
10030 
10031 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
10032 }
10033 
10034 
10035 /*
10036  *    Function: sdopen
10037  *
10038  * Description: Driver's open(9e) entry point function.
10039  *
10040  *   Arguments: dev_i   - pointer to device number
10041  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
10042  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10043  *		cred_p  - user credential pointer
10044  *
10045  * Return Code: EINVAL
10046  *		ENXIO
10047  *		EIO
10048  *		EROFS
10049  *		EBUSY
10050  *
10051  *     Context: Kernel thread context
10052  */
10053 /* ARGSUSED */
10054 static int
10055 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
10056 {
10057 	struct sd_lun	*un;
10058 	int		nodelay;
10059 	int		part;
10060 	uint64_t	partmask;
10061 	int		instance;
10062 	dev_t		dev;
10063 	int		rval = EIO;
10064 	diskaddr_t	nblks = 0;
10065 	diskaddr_t	label_cap;
10066 
10067 	/* Validate the open type */
10068 	if (otyp >= OTYPCNT) {
10069 		return (EINVAL);
10070 	}
10071 
10072 	dev = *dev_p;
10073 	instance = SDUNIT(dev);
10074 
10075 	/*
10076 	 * Fail the open if there is no softstate for the instance.
10077 	 */
10078 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
10079 		/*
10080 		 * The probe cache only needs to be cleared when open (9e) fails
10081 		 * with ENXIO (4238046).
10082 		 */
10083 		/*
10084 		 * un-conditionally clearing probe cache is ok with
10085 		 * separate sd/ssd binaries
10086 		 * x86 platform can be an issue with both parallel
10087 		 * and fibre in 1 binary
10088 		 */
10089 		sd_scsi_clear_probe_cache();
10090 		return (ENXIO);
10091 	}
10092 
10093 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
10094 	part	 = SDPART(dev);
10095 	partmask = 1 << part;
10096 
10097 	mutex_enter(SD_MUTEX(un));
10098 
10099 	/*
10100 	 * All device accesses go thru sdstrategy() where we check
10101 	 * on suspend status but there could be a scsi_poll command,
10102 	 * which bypasses sdstrategy(), so we need to check pm
10103 	 * status.
10104 	 */
10105 
10106 	if (!nodelay) {
10107 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10108 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10109 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10110 		}
10111 
10112 		mutex_exit(SD_MUTEX(un));
10113 		if (sd_pm_entry(un) != DDI_SUCCESS) {
10114 			rval = EIO;
10115 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
10116 			    "sdopen: sd_pm_entry failed\n");
10117 			goto open_failed_with_pm;
10118 		}
10119 		mutex_enter(SD_MUTEX(un));
10120 	}
10121 
10122 	/* check for previous exclusive open */
10123 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
10124 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10125 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
10126 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
10127 
10128 	if (un->un_exclopen & (partmask)) {
10129 		goto excl_open_fail;
10130 	}
10131 
10132 	if (flag & FEXCL) {
10133 		int i;
10134 		if (un->un_ocmap.lyropen[part]) {
10135 			goto excl_open_fail;
10136 		}
10137 		for (i = 0; i < (OTYPCNT - 1); i++) {
10138 			if (un->un_ocmap.regopen[i] & (partmask)) {
10139 				goto excl_open_fail;
10140 			}
10141 		}
10142 	}
10143 
10144 	/*
10145 	 * Check the write permission if this is a removable media device,
10146 	 * NDELAY has not been set, and writable permission is requested.
10147 	 *
10148 	 * Note: If NDELAY was set and this is write-protected media the WRITE
10149 	 * attempt will fail with EIO as part of the I/O processing. This is a
10150 	 * more permissive implementation that allows the open to succeed and
10151 	 * WRITE attempts to fail when appropriate.
10152 	 */
10153 	if (un->un_f_chk_wp_open) {
10154 		if ((flag & FWRITE) && (!nodelay)) {
10155 			mutex_exit(SD_MUTEX(un));
10156 			/*
10157 			 * Defer the check for write permission on writable
10158 			 * DVD drive till sdstrategy and will not fail open even
10159 			 * if FWRITE is set as the device can be writable
10160 			 * depending upon the media and the media can change
10161 			 * after the call to open().
10162 			 */
10163 			if (un->un_f_dvdram_writable_device == FALSE) {
10164 				if (ISCD(un) || sr_check_wp(dev)) {
10165 				rval = EROFS;
10166 				mutex_enter(SD_MUTEX(un));
10167 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10168 				    "write to cd or write protected media\n");
10169 				goto open_fail;
10170 				}
10171 			}
10172 			mutex_enter(SD_MUTEX(un));
10173 		}
10174 	}
10175 
10176 	/*
10177 	 * If opening in NDELAY/NONBLOCK mode, just return.
10178 	 * Check if disk is ready and has a valid geometry later.
10179 	 */
10180 	if (!nodelay) {
10181 		sd_ssc_t	*ssc;
10182 
10183 		mutex_exit(SD_MUTEX(un));
10184 		ssc = sd_ssc_init(un);
10185 		rval = sd_ready_and_valid(ssc, part);
10186 		sd_ssc_fini(ssc);
10187 		mutex_enter(SD_MUTEX(un));
10188 		/*
10189 		 * Fail if device is not ready or if the number of disk
10190 		 * blocks is zero or negative for non CD devices.
10191 		 */
10192 
10193 		nblks = 0;
10194 
10195 		if (rval == SD_READY_VALID && (!ISCD(un))) {
10196 			/* if cmlb_partinfo fails, nblks remains 0 */
10197 			mutex_exit(SD_MUTEX(un));
10198 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
10199 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
10200 			mutex_enter(SD_MUTEX(un));
10201 		}
10202 
10203 		if ((rval != SD_READY_VALID) ||
10204 		    (!ISCD(un) && nblks <= 0)) {
10205 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
10206 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10207 			    "device not ready or invalid disk block value\n");
10208 			goto open_fail;
10209 		}
10210 #if defined(__x86)
10211 	} else {
10212 		uchar_t *cp;
10213 		/*
10214 		 * x86 requires special nodelay handling, so that p0 is
10215 		 * always defined and accessible.
10216 		 * Invalidate geometry only if device is not already open.
10217 		 */
10218 		cp = &un->un_ocmap.chkd[0];
10219 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10220 			if (*cp != (uchar_t)0) {
10221 				break;
10222 			}
10223 			cp++;
10224 		}
10225 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10226 			mutex_exit(SD_MUTEX(un));
10227 			cmlb_invalidate(un->un_cmlbhandle,
10228 			    (void *)SD_PATH_DIRECT);
10229 			mutex_enter(SD_MUTEX(un));
10230 		}
10231 
10232 #endif
10233 	}
10234 
10235 	if (otyp == OTYP_LYR) {
10236 		un->un_ocmap.lyropen[part]++;
10237 	} else {
10238 		un->un_ocmap.regopen[otyp] |= partmask;
10239 	}
10240 
10241 	/* Set up open and exclusive open flags */
10242 	if (flag & FEXCL) {
10243 		un->un_exclopen |= (partmask);
10244 	}
10245 
10246 	/*
10247 	 * If the lun is EFI labeled and lun capacity is greater than the
10248 	 * capacity contained in the label, log a sys-event to notify the
10249 	 * interested module.
10250 	 * To avoid an infinite loop of logging sys-event, we only log the
10251 	 * event when the lun is not opened in NDELAY mode. The event handler
10252 	 * should open the lun in NDELAY mode.
10253 	 */
10254 	if (!nodelay) {
10255 		mutex_exit(SD_MUTEX(un));
10256 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
10257 		    (void*)SD_PATH_DIRECT) == 0) {
10258 			mutex_enter(SD_MUTEX(un));
10259 			if (un->un_f_blockcount_is_valid &&
10260 			    un->un_blockcount > label_cap &&
10261 			    un->un_f_expnevent == B_FALSE) {
10262 				un->un_f_expnevent = B_TRUE;
10263 				mutex_exit(SD_MUTEX(un));
10264 				sd_log_lun_expansion_event(un,
10265 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
10266 				mutex_enter(SD_MUTEX(un));
10267 			}
10268 		} else {
10269 			mutex_enter(SD_MUTEX(un));
10270 		}
10271 	}
10272 
10273 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10274 	    "open of part %d type %d\n", part, otyp);
10275 
10276 	mutex_exit(SD_MUTEX(un));
10277 	if (!nodelay) {
10278 		sd_pm_exit(un);
10279 	}
10280 
10281 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
10282 	return (DDI_SUCCESS);
10283 
10284 excl_open_fail:
10285 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
10286 	rval = EBUSY;
10287 
10288 open_fail:
10289 	mutex_exit(SD_MUTEX(un));
10290 
10291 	/*
10292 	 * On a failed open we must exit the pm management.
10293 	 */
10294 	if (!nodelay) {
10295 		sd_pm_exit(un);
10296 	}
10297 open_failed_with_pm:
10298 
10299 	return (rval);
10300 }
10301 
10302 
10303 /*
10304  *    Function: sdclose
10305  *
10306  * Description: Driver's close(9e) entry point function.
10307  *
10308  *   Arguments: dev    - device number
10309  *		flag   - file status flag, informational only
10310  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10311  *		cred_p - user credential pointer
10312  *
10313  * Return Code: ENXIO
10314  *
10315  *     Context: Kernel thread context
10316  */
10317 /* ARGSUSED */
10318 static int
10319 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
10320 {
10321 	struct sd_lun	*un;
10322 	uchar_t		*cp;
10323 	int		part;
10324 	int		nodelay;
10325 	int		rval = 0;
10326 
10327 	/* Validate the open type */
10328 	if (otyp >= OTYPCNT) {
10329 		return (ENXIO);
10330 	}
10331 
10332 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10333 		return (ENXIO);
10334 	}
10335 
10336 	part = SDPART(dev);
10337 	nodelay = flag & (FNDELAY | FNONBLOCK);
10338 
10339 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10340 	    "sdclose: close of part %d type %d\n", part, otyp);
10341 
10342 	mutex_enter(SD_MUTEX(un));
10343 
10344 	/* Don't proceed if power is being changed. */
10345 	while (un->un_state == SD_STATE_PM_CHANGING) {
10346 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10347 	}
10348 
10349 	if (un->un_exclopen & (1 << part)) {
10350 		un->un_exclopen &= ~(1 << part);
10351 	}
10352 
10353 	/* Update the open partition map */
10354 	if (otyp == OTYP_LYR) {
10355 		un->un_ocmap.lyropen[part] -= 1;
10356 	} else {
10357 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
10358 	}
10359 
10360 	cp = &un->un_ocmap.chkd[0];
10361 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10362 		if (*cp != '\0') {
10363 			break;
10364 		}
10365 		cp++;
10366 	}
10367 
10368 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10369 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
10370 
10371 		/*
10372 		 * We avoid persistance upon the last close, and set
10373 		 * the throttle back to the maximum.
10374 		 */
10375 		un->un_throttle = un->un_saved_throttle;
10376 
10377 		if (un->un_state == SD_STATE_OFFLINE) {
10378 			if (un->un_f_is_fibre == FALSE) {
10379 				scsi_log(SD_DEVINFO(un), sd_label,
10380 				    CE_WARN, "offline\n");
10381 			}
10382 			mutex_exit(SD_MUTEX(un));
10383 			cmlb_invalidate(un->un_cmlbhandle,
10384 			    (void *)SD_PATH_DIRECT);
10385 			mutex_enter(SD_MUTEX(un));
10386 
10387 		} else {
10388 			/*
10389 			 * Flush any outstanding writes in NVRAM cache.
10390 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10391 			 * cmd, it may not work for non-Pluto devices.
10392 			 * SYNCHRONIZE CACHE is not required for removables,
10393 			 * except DVD-RAM drives.
10394 			 *
10395 			 * Also note: because SYNCHRONIZE CACHE is currently
10396 			 * the only command issued here that requires the
10397 			 * drive be powered up, only do the power up before
10398 			 * sending the Sync Cache command. If additional
10399 			 * commands are added which require a powered up
10400 			 * drive, the following sequence may have to change.
10401 			 *
10402 			 * And finally, note that parallel SCSI on SPARC
10403 			 * only issues a Sync Cache to DVD-RAM, a newly
10404 			 * supported device.
10405 			 */
10406 #if defined(__x86)
10407 			if ((un->un_f_sync_cache_supported &&
10408 			    un->un_f_sync_cache_required) ||
10409 			    un->un_f_dvdram_writable_device == TRUE) {
10410 #else
10411 			if (un->un_f_dvdram_writable_device == TRUE) {
10412 #endif
10413 				mutex_exit(SD_MUTEX(un));
10414 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10415 					rval =
10416 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10417 					    NULL);
10418 					/* ignore error if not supported */
10419 					if (rval == ENOTSUP) {
10420 						rval = 0;
10421 					} else if (rval != 0) {
10422 						rval = EIO;
10423 					}
10424 					sd_pm_exit(un);
10425 				} else {
10426 					rval = EIO;
10427 				}
10428 				mutex_enter(SD_MUTEX(un));
10429 			}
10430 
10431 			/*
10432 			 * For devices which supports DOOR_LOCK, send an ALLOW
10433 			 * MEDIA REMOVAL command, but don't get upset if it
10434 			 * fails. We need to raise the power of the drive before
10435 			 * we can call sd_send_scsi_DOORLOCK()
10436 			 */
10437 			if (un->un_f_doorlock_supported) {
10438 				mutex_exit(SD_MUTEX(un));
10439 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10440 					sd_ssc_t	*ssc;
10441 
10442 					ssc = sd_ssc_init(un);
10443 					rval = sd_send_scsi_DOORLOCK(ssc,
10444 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10445 					if (rval != 0)
10446 						sd_ssc_assessment(ssc,
10447 						    SD_FMT_IGNORE);
10448 					sd_ssc_fini(ssc);
10449 
10450 					sd_pm_exit(un);
10451 					if (ISCD(un) && (rval != 0) &&
10452 					    (nodelay != 0)) {
10453 						rval = ENXIO;
10454 					}
10455 				} else {
10456 					rval = EIO;
10457 				}
10458 				mutex_enter(SD_MUTEX(un));
10459 			}
10460 
10461 			/*
10462 			 * If a device has removable media, invalidate all
10463 			 * parameters related to media, such as geometry,
10464 			 * blocksize, and blockcount.
10465 			 */
10466 			if (un->un_f_has_removable_media) {
10467 				sr_ejected(un);
10468 			}
10469 
10470 			/*
10471 			 * Destroy the cache (if it exists) which was
10472 			 * allocated for the write maps since this is
10473 			 * the last close for this media.
10474 			 */
10475 			if (un->un_wm_cache) {
10476 				/*
10477 				 * Check if there are pending commands.
10478 				 * and if there are give a warning and
10479 				 * do not destroy the cache.
10480 				 */
10481 				if (un->un_ncmds_in_driver > 0) {
10482 					scsi_log(SD_DEVINFO(un),
10483 					    sd_label, CE_WARN,
10484 					    "Unable to clean up memory "
10485 					    "because of pending I/O\n");
10486 				} else {
10487 					kmem_cache_destroy(
10488 					    un->un_wm_cache);
10489 					un->un_wm_cache = NULL;
10490 				}
10491 			}
10492 		}
10493 	}
10494 
10495 	mutex_exit(SD_MUTEX(un));
10496 
10497 	return (rval);
10498 }
10499 
10500 
10501 /*
10502  *    Function: sd_ready_and_valid
10503  *
10504  * Description: Test if device is ready and has a valid geometry.
10505  *
10506  *   Arguments: ssc - sd_ssc_t will contain un
10507  *		un  - driver soft state (unit) structure
10508  *
10509  * Return Code: SD_READY_VALID		ready and valid label
10510  *		SD_NOT_READY_VALID	not ready, no label
10511  *		SD_RESERVED_BY_OTHERS	reservation conflict
10512  *
10513  *     Context: Never called at interrupt context.
10514  */
10515 
10516 static int
10517 sd_ready_and_valid(sd_ssc_t *ssc, int part)
10518 {
10519 	struct sd_errstats	*stp;
10520 	uint64_t		capacity;
10521 	uint_t			lbasize;
10522 	int			rval = SD_READY_VALID;
10523 	char			name_str[48];
10524 	boolean_t		is_valid;
10525 	struct sd_lun		*un;
10526 	int			status;
10527 
10528 	ASSERT(ssc != NULL);
10529 	un = ssc->ssc_un;
10530 	ASSERT(un != NULL);
10531 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10532 
10533 	mutex_enter(SD_MUTEX(un));
10534 	/*
10535 	 * If a device has removable media, we must check if media is
10536 	 * ready when checking if this device is ready and valid.
10537 	 */
10538 	if (un->un_f_has_removable_media) {
10539 		mutex_exit(SD_MUTEX(un));
10540 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10541 
10542 		if (status != 0) {
10543 			rval = SD_NOT_READY_VALID;
10544 			mutex_enter(SD_MUTEX(un));
10545 
10546 			/* Ignore all failed status for removalbe media */
10547 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10548 
10549 			goto done;
10550 		}
10551 
10552 		is_valid = SD_IS_VALID_LABEL(un);
10553 		mutex_enter(SD_MUTEX(un));
10554 		if (!is_valid ||
10555 		    (un->un_f_blockcount_is_valid == FALSE) ||
10556 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10557 
10558 			/* capacity has to be read every open. */
10559 			mutex_exit(SD_MUTEX(un));
10560 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
10561 			    &lbasize, SD_PATH_DIRECT);
10562 
10563 			if (status != 0) {
10564 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10565 
10566 				cmlb_invalidate(un->un_cmlbhandle,
10567 				    (void *)SD_PATH_DIRECT);
10568 				mutex_enter(SD_MUTEX(un));
10569 				rval = SD_NOT_READY_VALID;
10570 
10571 				goto done;
10572 			} else {
10573 				mutex_enter(SD_MUTEX(un));
10574 				sd_update_block_info(un, lbasize, capacity);
10575 			}
10576 		}
10577 
10578 		/*
10579 		 * Check if the media in the device is writable or not.
10580 		 */
10581 		if (!is_valid && ISCD(un)) {
10582 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
10583 		}
10584 
10585 	} else {
10586 		/*
10587 		 * Do a test unit ready to clear any unit attention from non-cd
10588 		 * devices.
10589 		 */
10590 		mutex_exit(SD_MUTEX(un));
10591 
10592 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10593 		if (status != 0) {
10594 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10595 		}
10596 
10597 		mutex_enter(SD_MUTEX(un));
10598 	}
10599 
10600 
10601 	/*
10602 	 * If this is a non 512 block device, allocate space for
10603 	 * the wmap cache. This is being done here since every time
10604 	 * a media is changed this routine will be called and the
10605 	 * block size is a function of media rather than device.
10606 	 */
10607 	if (((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR ||
10608 	    un->un_f_non_devbsize_supported) &&
10609 	    un->un_tgt_blocksize != DEV_BSIZE) ||
10610 	    un->un_f_enable_rmw) {
10611 		if (!(un->un_wm_cache)) {
10612 			(void) snprintf(name_str, sizeof (name_str),
10613 			    "%s%d_cache",
10614 			    ddi_driver_name(SD_DEVINFO(un)),
10615 			    ddi_get_instance(SD_DEVINFO(un)));
10616 			un->un_wm_cache = kmem_cache_create(
10617 			    name_str, sizeof (struct sd_w_map),
10618 			    8, sd_wm_cache_constructor,
10619 			    sd_wm_cache_destructor, NULL,
10620 			    (void *)un, NULL, 0);
10621 			if (!(un->un_wm_cache)) {
10622 				rval = ENOMEM;
10623 				goto done;
10624 			}
10625 		}
10626 	}
10627 
10628 	if (un->un_state == SD_STATE_NORMAL) {
10629 		/*
10630 		 * If the target is not yet ready here (defined by a TUR
10631 		 * failure), invalidate the geometry and print an 'offline'
10632 		 * message. This is a legacy message, as the state of the
10633 		 * target is not actually changed to SD_STATE_OFFLINE.
10634 		 *
10635 		 * If the TUR fails for EACCES (Reservation Conflict),
10636 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
10637 		 * reservation conflict. If the TUR fails for other
10638 		 * reasons, SD_NOT_READY_VALID will be returned.
10639 		 */
10640 		int err;
10641 
10642 		mutex_exit(SD_MUTEX(un));
10643 		err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10644 		mutex_enter(SD_MUTEX(un));
10645 
10646 		if (err != 0) {
10647 			mutex_exit(SD_MUTEX(un));
10648 			cmlb_invalidate(un->un_cmlbhandle,
10649 			    (void *)SD_PATH_DIRECT);
10650 			mutex_enter(SD_MUTEX(un));
10651 			if (err == EACCES) {
10652 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10653 				    "reservation conflict\n");
10654 				rval = SD_RESERVED_BY_OTHERS;
10655 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10656 			} else {
10657 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10658 				    "drive offline\n");
10659 				rval = SD_NOT_READY_VALID;
10660 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
10661 			}
10662 			goto done;
10663 		}
10664 	}
10665 
10666 	if (un->un_f_format_in_progress == FALSE) {
10667 		mutex_exit(SD_MUTEX(un));
10668 
10669 		(void) cmlb_validate(un->un_cmlbhandle, 0,
10670 		    (void *)SD_PATH_DIRECT);
10671 		if (cmlb_partinfo(un->un_cmlbhandle, part, NULL, NULL, NULL,
10672 		    NULL, (void *) SD_PATH_DIRECT) != 0) {
10673 			rval = SD_NOT_READY_VALID;
10674 			mutex_enter(SD_MUTEX(un));
10675 
10676 			goto done;
10677 		}
10678 		if (un->un_f_pkstats_enabled) {
10679 			sd_set_pstats(un);
10680 			SD_TRACE(SD_LOG_IO_PARTITION, un,
10681 			    "sd_ready_and_valid: un:0x%p pstats created and "
10682 			    "set\n", un);
10683 		}
10684 		mutex_enter(SD_MUTEX(un));
10685 	}
10686 
10687 	/*
10688 	 * If this device supports DOOR_LOCK command, try and send
10689 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10690 	 * if it fails. For a CD, however, it is an error
10691 	 */
10692 	if (un->un_f_doorlock_supported) {
10693 		mutex_exit(SD_MUTEX(un));
10694 		status = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
10695 		    SD_PATH_DIRECT);
10696 
10697 		if ((status != 0) && ISCD(un)) {
10698 			rval = SD_NOT_READY_VALID;
10699 			mutex_enter(SD_MUTEX(un));
10700 
10701 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10702 
10703 			goto done;
10704 		} else if (status != 0)
10705 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10706 		mutex_enter(SD_MUTEX(un));
10707 	}
10708 
10709 	/* The state has changed, inform the media watch routines */
10710 	un->un_mediastate = DKIO_INSERTED;
10711 	cv_broadcast(&un->un_state_cv);
10712 	rval = SD_READY_VALID;
10713 
10714 done:
10715 
10716 	/*
10717 	 * Initialize the capacity kstat value, if no media previously
10718 	 * (capacity kstat is 0) and a media has been inserted
10719 	 * (un_blockcount > 0).
10720 	 */
10721 	if (un->un_errstats != NULL) {
10722 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10723 		if ((stp->sd_capacity.value.ui64 == 0) &&
10724 		    (un->un_f_blockcount_is_valid == TRUE)) {
10725 			stp->sd_capacity.value.ui64 =
10726 			    (uint64_t)((uint64_t)un->un_blockcount *
10727 			    un->un_sys_blocksize);
10728 		}
10729 	}
10730 
10731 	mutex_exit(SD_MUTEX(un));
10732 	return (rval);
10733 }
10734 
10735 
10736 /*
10737  *    Function: sdmin
10738  *
10739  * Description: Routine to limit the size of a data transfer. Used in
10740  *		conjunction with physio(9F).
10741  *
10742  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10743  *
10744  *     Context: Kernel thread context.
10745  */
10746 
10747 static void
10748 sdmin(struct buf *bp)
10749 {
10750 	struct sd_lun	*un;
10751 	int		instance;
10752 
10753 	instance = SDUNIT(bp->b_edev);
10754 
10755 	un = ddi_get_soft_state(sd_state, instance);
10756 	ASSERT(un != NULL);
10757 
10758 	/*
10759 	 * We depend on buf breakup to restrict
10760 	 * IO size if it is enabled.
10761 	 */
10762 	if (un->un_buf_breakup_supported) {
10763 		return;
10764 	}
10765 
10766 	if (bp->b_bcount > un->un_max_xfer_size) {
10767 		bp->b_bcount = un->un_max_xfer_size;
10768 	}
10769 }
10770 
10771 
10772 /*
10773  *    Function: sdread
10774  *
10775  * Description: Driver's read(9e) entry point function.
10776  *
10777  *   Arguments: dev   - device number
10778  *		uio   - structure pointer describing where data is to be stored
10779  *			in user's space
10780  *		cred_p  - user credential pointer
10781  *
10782  * Return Code: ENXIO
10783  *		EIO
10784  *		EINVAL
10785  *		value returned by physio
10786  *
10787  *     Context: Kernel thread context.
10788  */
10789 /* ARGSUSED */
10790 static int
10791 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10792 {
10793 	struct sd_lun	*un = NULL;
10794 	int		secmask;
10795 	int		err = 0;
10796 	sd_ssc_t	*ssc;
10797 
10798 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10799 		return (ENXIO);
10800 	}
10801 
10802 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10803 
10804 
10805 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10806 		mutex_enter(SD_MUTEX(un));
10807 		/*
10808 		 * Because the call to sd_ready_and_valid will issue I/O we
10809 		 * must wait here if either the device is suspended or
10810 		 * if it's power level is changing.
10811 		 */
10812 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10813 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10814 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10815 		}
10816 		un->un_ncmds_in_driver++;
10817 		mutex_exit(SD_MUTEX(un));
10818 
10819 		/* Initialize sd_ssc_t for internal uscsi commands */
10820 		ssc = sd_ssc_init(un);
10821 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10822 			err = EIO;
10823 		} else {
10824 			err = 0;
10825 		}
10826 		sd_ssc_fini(ssc);
10827 
10828 		mutex_enter(SD_MUTEX(un));
10829 		un->un_ncmds_in_driver--;
10830 		ASSERT(un->un_ncmds_in_driver >= 0);
10831 		mutex_exit(SD_MUTEX(un));
10832 		if (err != 0)
10833 			return (err);
10834 	}
10835 
10836 	/*
10837 	 * Read requests are restricted to multiples of the system block size.
10838 	 */
10839 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
10840 	    !un->un_f_enable_rmw)
10841 		secmask = un->un_tgt_blocksize - 1;
10842 	else
10843 		secmask = DEV_BSIZE - 1;
10844 
10845 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10846 		SD_ERROR(SD_LOG_READ_WRITE, un,
10847 		    "sdread: file offset not modulo %d\n",
10848 		    secmask + 1);
10849 		err = EINVAL;
10850 	} else if (uio->uio_iov->iov_len & (secmask)) {
10851 		SD_ERROR(SD_LOG_READ_WRITE, un,
10852 		    "sdread: transfer length not modulo %d\n",
10853 		    secmask + 1);
10854 		err = EINVAL;
10855 	} else {
10856 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
10857 	}
10858 
10859 	return (err);
10860 }
10861 
10862 
10863 /*
10864  *    Function: sdwrite
10865  *
10866  * Description: Driver's write(9e) entry point function.
10867  *
10868  *   Arguments: dev   - device number
10869  *		uio   - structure pointer describing where data is stored in
10870  *			user's space
10871  *		cred_p  - user credential pointer
10872  *
10873  * Return Code: ENXIO
10874  *		EIO
10875  *		EINVAL
10876  *		value returned by physio
10877  *
10878  *     Context: Kernel thread context.
10879  */
10880 /* ARGSUSED */
10881 static int
10882 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
10883 {
10884 	struct sd_lun	*un = NULL;
10885 	int		secmask;
10886 	int		err = 0;
10887 	sd_ssc_t	*ssc;
10888 
10889 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10890 		return (ENXIO);
10891 	}
10892 
10893 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10894 
10895 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10896 		mutex_enter(SD_MUTEX(un));
10897 		/*
10898 		 * Because the call to sd_ready_and_valid will issue I/O we
10899 		 * must wait here if either the device is suspended or
10900 		 * if it's power level is changing.
10901 		 */
10902 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10903 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10904 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10905 		}
10906 		un->un_ncmds_in_driver++;
10907 		mutex_exit(SD_MUTEX(un));
10908 
10909 		/* Initialize sd_ssc_t for internal uscsi commands */
10910 		ssc = sd_ssc_init(un);
10911 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10912 			err = EIO;
10913 		} else {
10914 			err = 0;
10915 		}
10916 		sd_ssc_fini(ssc);
10917 
10918 		mutex_enter(SD_MUTEX(un));
10919 		un->un_ncmds_in_driver--;
10920 		ASSERT(un->un_ncmds_in_driver >= 0);
10921 		mutex_exit(SD_MUTEX(un));
10922 		if (err != 0)
10923 			return (err);
10924 	}
10925 
10926 	/*
10927 	 * Write requests are restricted to multiples of the system block size.
10928 	 */
10929 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
10930 	    !un->un_f_enable_rmw)
10931 		secmask = un->un_tgt_blocksize - 1;
10932 	else
10933 		secmask = DEV_BSIZE - 1;
10934 
10935 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10936 		SD_ERROR(SD_LOG_READ_WRITE, un,
10937 		    "sdwrite: file offset not modulo %d\n",
10938 		    secmask + 1);
10939 		err = EINVAL;
10940 	} else if (uio->uio_iov->iov_len & (secmask)) {
10941 		SD_ERROR(SD_LOG_READ_WRITE, un,
10942 		    "sdwrite: transfer length not modulo %d\n",
10943 		    secmask + 1);
10944 		err = EINVAL;
10945 	} else {
10946 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
10947 	}
10948 
10949 	return (err);
10950 }
10951 
10952 
10953 /*
10954  *    Function: sdaread
10955  *
10956  * Description: Driver's aread(9e) entry point function.
10957  *
10958  *   Arguments: dev   - device number
10959  *		aio   - structure pointer describing where data is to be stored
10960  *		cred_p  - user credential pointer
10961  *
10962  * Return Code: ENXIO
10963  *		EIO
10964  *		EINVAL
10965  *		value returned by aphysio
10966  *
10967  *     Context: Kernel thread context.
10968  */
10969 /* ARGSUSED */
10970 static int
10971 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10972 {
10973 	struct sd_lun	*un = NULL;
10974 	struct uio	*uio = aio->aio_uio;
10975 	int		secmask;
10976 	int		err = 0;
10977 	sd_ssc_t	*ssc;
10978 
10979 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10980 		return (ENXIO);
10981 	}
10982 
10983 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10984 
10985 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10986 		mutex_enter(SD_MUTEX(un));
10987 		/*
10988 		 * Because the call to sd_ready_and_valid will issue I/O we
10989 		 * must wait here if either the device is suspended or
10990 		 * if it's power level is changing.
10991 		 */
10992 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10993 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10994 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10995 		}
10996 		un->un_ncmds_in_driver++;
10997 		mutex_exit(SD_MUTEX(un));
10998 
10999 		/* Initialize sd_ssc_t for internal uscsi commands */
11000 		ssc = sd_ssc_init(un);
11001 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11002 			err = EIO;
11003 		} else {
11004 			err = 0;
11005 		}
11006 		sd_ssc_fini(ssc);
11007 
11008 		mutex_enter(SD_MUTEX(un));
11009 		un->un_ncmds_in_driver--;
11010 		ASSERT(un->un_ncmds_in_driver >= 0);
11011 		mutex_exit(SD_MUTEX(un));
11012 		if (err != 0)
11013 			return (err);
11014 	}
11015 
11016 	/*
11017 	 * Read requests are restricted to multiples of the system block size.
11018 	 */
11019 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11020 	    !un->un_f_enable_rmw)
11021 		secmask = un->un_tgt_blocksize - 1;
11022 	else
11023 		secmask = DEV_BSIZE - 1;
11024 
11025 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11026 		SD_ERROR(SD_LOG_READ_WRITE, un,
11027 		    "sdaread: file offset not modulo %d\n",
11028 		    secmask + 1);
11029 		err = EINVAL;
11030 	} else if (uio->uio_iov->iov_len & (secmask)) {
11031 		SD_ERROR(SD_LOG_READ_WRITE, un,
11032 		    "sdaread: transfer length not modulo %d\n",
11033 		    secmask + 1);
11034 		err = EINVAL;
11035 	} else {
11036 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
11037 	}
11038 
11039 	return (err);
11040 }
11041 
11042 
11043 /*
11044  *    Function: sdawrite
11045  *
11046  * Description: Driver's awrite(9e) entry point function.
11047  *
11048  *   Arguments: dev   - device number
11049  *		aio   - structure pointer describing where data is stored
11050  *		cred_p  - user credential pointer
11051  *
11052  * Return Code: ENXIO
11053  *		EIO
11054  *		EINVAL
11055  *		value returned by aphysio
11056  *
11057  *     Context: Kernel thread context.
11058  */
11059 /* ARGSUSED */
11060 static int
11061 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11062 {
11063 	struct sd_lun	*un = NULL;
11064 	struct uio	*uio = aio->aio_uio;
11065 	int		secmask;
11066 	int		err = 0;
11067 	sd_ssc_t	*ssc;
11068 
11069 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11070 		return (ENXIO);
11071 	}
11072 
11073 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11074 
11075 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11076 		mutex_enter(SD_MUTEX(un));
11077 		/*
11078 		 * Because the call to sd_ready_and_valid will issue I/O we
11079 		 * must wait here if either the device is suspended or
11080 		 * if it's power level is changing.
11081 		 */
11082 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11083 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11084 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11085 		}
11086 		un->un_ncmds_in_driver++;
11087 		mutex_exit(SD_MUTEX(un));
11088 
11089 		/* Initialize sd_ssc_t for internal uscsi commands */
11090 		ssc = sd_ssc_init(un);
11091 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11092 			err = EIO;
11093 		} else {
11094 			err = 0;
11095 		}
11096 		sd_ssc_fini(ssc);
11097 
11098 		mutex_enter(SD_MUTEX(un));
11099 		un->un_ncmds_in_driver--;
11100 		ASSERT(un->un_ncmds_in_driver >= 0);
11101 		mutex_exit(SD_MUTEX(un));
11102 		if (err != 0)
11103 			return (err);
11104 	}
11105 
11106 	/*
11107 	 * Write requests are restricted to multiples of the system block size.
11108 	 */
11109 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11110 	    !un->un_f_enable_rmw)
11111 		secmask = un->un_tgt_blocksize - 1;
11112 	else
11113 		secmask = DEV_BSIZE - 1;
11114 
11115 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11116 		SD_ERROR(SD_LOG_READ_WRITE, un,
11117 		    "sdawrite: file offset not modulo %d\n",
11118 		    secmask + 1);
11119 		err = EINVAL;
11120 	} else if (uio->uio_iov->iov_len & (secmask)) {
11121 		SD_ERROR(SD_LOG_READ_WRITE, un,
11122 		    "sdawrite: transfer length not modulo %d\n",
11123 		    secmask + 1);
11124 		err = EINVAL;
11125 	} else {
11126 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
11127 	}
11128 
11129 	return (err);
11130 }
11131 
11132 
11133 
11134 
11135 
11136 /*
11137  * Driver IO processing follows the following sequence:
11138  *
11139  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
11140  *         |                |                     ^
11141  *         v                v                     |
11142  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
11143  *         |                |                     |                   |
11144  *         v                |                     |                   |
11145  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
11146  *         |                |                     ^                   ^
11147  *         v                v                     |                   |
11148  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
11149  *         |                |                     |                   |
11150  *     +---+                |                     +------------+      +-------+
11151  *     |                    |                                  |              |
11152  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11153  *     |                    v                                  |              |
11154  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
11155  *     |                    |                                  ^              |
11156  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11157  *     |                    v                                  |              |
11158  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
11159  *     |                    |                                  ^              |
11160  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11161  *     |                    v                                  |              |
11162  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
11163  *     |                    |                                  ^              |
11164  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
11165  *     |                    v                                  |              |
11166  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
11167  *     |                    |                                  ^              |
11168  *     |                    |                                  |              |
11169  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
11170  *                          |                           ^
11171  *                          v                           |
11172  *                   sd_core_iostart()                  |
11173  *                          |                           |
11174  *                          |                           +------>(*destroypkt)()
11175  *                          +-> sd_start_cmds() <-+     |           |
11176  *                          |                     |     |           v
11177  *                          |                     |     |  scsi_destroy_pkt(9F)
11178  *                          |                     |     |
11179  *                          +->(*initpkt)()       +- sdintr()
11180  *                          |  |                        |  |
11181  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
11182  *                          |  +-> scsi_setup_cdb(9F)   |
11183  *                          |                           |
11184  *                          +--> scsi_transport(9F)     |
11185  *                                     |                |
11186  *                                     +----> SCSA ---->+
11187  *
11188  *
11189  * This code is based upon the following presumptions:
11190  *
11191  *   - iostart and iodone functions operate on buf(9S) structures. These
11192  *     functions perform the necessary operations on the buf(9S) and pass
11193  *     them along to the next function in the chain by using the macros
11194  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
11195  *     (for iodone side functions).
11196  *
11197  *   - The iostart side functions may sleep. The iodone side functions
11198  *     are called under interrupt context and may NOT sleep. Therefore
11199  *     iodone side functions also may not call iostart side functions.
11200  *     (NOTE: iostart side functions should NOT sleep for memory, as
11201  *     this could result in deadlock.)
11202  *
11203  *   - An iostart side function may call its corresponding iodone side
11204  *     function directly (if necessary).
11205  *
11206  *   - In the event of an error, an iostart side function can return a buf(9S)
11207  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
11208  *     b_error in the usual way of course).
11209  *
11210  *   - The taskq mechanism may be used by the iodone side functions to dispatch
11211  *     requests to the iostart side functions.  The iostart side functions in
11212  *     this case would be called under the context of a taskq thread, so it's
11213  *     OK for them to block/sleep/spin in this case.
11214  *
11215  *   - iostart side functions may allocate "shadow" buf(9S) structs and
11216  *     pass them along to the next function in the chain.  The corresponding
11217  *     iodone side functions must coalesce the "shadow" bufs and return
11218  *     the "original" buf to the next higher layer.
11219  *
11220  *   - The b_private field of the buf(9S) struct holds a pointer to
11221  *     an sd_xbuf struct, which contains information needed to
11222  *     construct the scsi_pkt for the command.
11223  *
11224  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
11225  *     layer must acquire & release the SD_MUTEX(un) as needed.
11226  */
11227 
11228 
11229 /*
11230  * Create taskq for all targets in the system. This is created at
11231  * _init(9E) and destroyed at _fini(9E).
11232  *
11233  * Note: here we set the minalloc to a reasonably high number to ensure that
11234  * we will have an adequate supply of task entries available at interrupt time.
11235  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
11236  * sd_create_taskq().  Since we do not want to sleep for allocations at
11237  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
11238  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
11239  * requests any one instant in time.
11240  */
11241 #define	SD_TASKQ_NUMTHREADS	8
11242 #define	SD_TASKQ_MINALLOC	256
11243 #define	SD_TASKQ_MAXALLOC	256
11244 
11245 static taskq_t	*sd_tq = NULL;
11246 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
11247 
11248 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
11249 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
11250 
11251 /*
11252  * The following task queue is being created for the write part of
11253  * read-modify-write of non-512 block size devices.
11254  * Limit the number of threads to 1 for now. This number has been chosen
11255  * considering the fact that it applies only to dvd ram drives/MO drives
11256  * currently. Performance for which is not main criteria at this stage.
11257  * Note: It needs to be explored if we can use a single taskq in future
11258  */
11259 #define	SD_WMR_TASKQ_NUMTHREADS	1
11260 static taskq_t	*sd_wmr_tq = NULL;
11261 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
11262 
11263 /*
11264  *    Function: sd_taskq_create
11265  *
11266  * Description: Create taskq thread(s) and preallocate task entries
11267  *
11268  * Return Code: Returns a pointer to the allocated taskq_t.
11269  *
11270  *     Context: Can sleep. Requires blockable context.
11271  *
11272  *       Notes: - The taskq() facility currently is NOT part of the DDI.
11273  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
11274  *		- taskq_create() will block for memory, also it will panic
11275  *		  if it cannot create the requested number of threads.
11276  *		- Currently taskq_create() creates threads that cannot be
11277  *		  swapped.
11278  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
11279  *		  supply of taskq entries at interrupt time (ie, so that we
11280  *		  do not have to sleep for memory)
11281  */
11282 
11283 static void
11284 sd_taskq_create(void)
11285 {
11286 	char	taskq_name[TASKQ_NAMELEN];
11287 
11288 	ASSERT(sd_tq == NULL);
11289 	ASSERT(sd_wmr_tq == NULL);
11290 
11291 	(void) snprintf(taskq_name, sizeof (taskq_name),
11292 	    "%s_drv_taskq", sd_label);
11293 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
11294 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11295 	    TASKQ_PREPOPULATE));
11296 
11297 	(void) snprintf(taskq_name, sizeof (taskq_name),
11298 	    "%s_rmw_taskq", sd_label);
11299 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
11300 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11301 	    TASKQ_PREPOPULATE));
11302 }
11303 
11304 
11305 /*
11306  *    Function: sd_taskq_delete
11307  *
11308  * Description: Complementary cleanup routine for sd_taskq_create().
11309  *
11310  *     Context: Kernel thread context.
11311  */
11312 
11313 static void
11314 sd_taskq_delete(void)
11315 {
11316 	ASSERT(sd_tq != NULL);
11317 	ASSERT(sd_wmr_tq != NULL);
11318 	taskq_destroy(sd_tq);
11319 	taskq_destroy(sd_wmr_tq);
11320 	sd_tq = NULL;
11321 	sd_wmr_tq = NULL;
11322 }
11323 
11324 
11325 /*
11326  *    Function: sdstrategy
11327  *
11328  * Description: Driver's strategy (9E) entry point function.
11329  *
11330  *   Arguments: bp - pointer to buf(9S)
11331  *
11332  * Return Code: Always returns zero
11333  *
11334  *     Context: Kernel thread context.
11335  */
11336 
11337 static int
11338 sdstrategy(struct buf *bp)
11339 {
11340 	struct sd_lun *un;
11341 
11342 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11343 	if (un == NULL) {
11344 		bioerror(bp, EIO);
11345 		bp->b_resid = bp->b_bcount;
11346 		biodone(bp);
11347 		return (0);
11348 	}
11349 
11350 	/* As was done in the past, fail new cmds. if state is dumping. */
11351 	if (un->un_state == SD_STATE_DUMPING) {
11352 		bioerror(bp, ENXIO);
11353 		bp->b_resid = bp->b_bcount;
11354 		biodone(bp);
11355 		return (0);
11356 	}
11357 
11358 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11359 
11360 	/*
11361 	 * Commands may sneak in while we released the mutex in
11362 	 * DDI_SUSPEND, we should block new commands. However, old
11363 	 * commands that are still in the driver at this point should
11364 	 * still be allowed to drain.
11365 	 */
11366 	mutex_enter(SD_MUTEX(un));
11367 	/*
11368 	 * Must wait here if either the device is suspended or
11369 	 * if it's power level is changing.
11370 	 */
11371 	while ((un->un_state == SD_STATE_SUSPENDED) ||
11372 	    (un->un_state == SD_STATE_PM_CHANGING)) {
11373 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11374 	}
11375 
11376 	un->un_ncmds_in_driver++;
11377 
11378 	/*
11379 	 * atapi: Since we are running the CD for now in PIO mode we need to
11380 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11381 	 * the HBA's init_pkt routine.
11382 	 */
11383 	if (un->un_f_cfg_is_atapi == TRUE) {
11384 		mutex_exit(SD_MUTEX(un));
11385 		bp_mapin(bp);
11386 		mutex_enter(SD_MUTEX(un));
11387 	}
11388 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
11389 	    un->un_ncmds_in_driver);
11390 
11391 	if (bp->b_flags & B_WRITE)
11392 		un->un_f_sync_cache_required = TRUE;
11393 
11394 	mutex_exit(SD_MUTEX(un));
11395 
11396 	/*
11397 	 * This will (eventually) allocate the sd_xbuf area and
11398 	 * call sd_xbuf_strategy().  We just want to return the
11399 	 * result of ddi_xbuf_qstrategy so that we have an opt-
11400 	 * imized tail call which saves us a stack frame.
11401 	 */
11402 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
11403 }
11404 
11405 
11406 /*
11407  *    Function: sd_xbuf_strategy
11408  *
11409  * Description: Function for initiating IO operations via the
11410  *		ddi_xbuf_qstrategy() mechanism.
11411  *
11412  *     Context: Kernel thread context.
11413  */
11414 
11415 static void
11416 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11417 {
11418 	struct sd_lun *un = arg;
11419 
11420 	ASSERT(bp != NULL);
11421 	ASSERT(xp != NULL);
11422 	ASSERT(un != NULL);
11423 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11424 
11425 	/*
11426 	 * Initialize the fields in the xbuf and save a pointer to the
11427 	 * xbuf in bp->b_private.
11428 	 */
11429 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11430 
11431 	/* Send the buf down the iostart chain */
11432 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11433 }
11434 
11435 
11436 /*
11437  *    Function: sd_xbuf_init
11438  *
11439  * Description: Prepare the given sd_xbuf struct for use.
11440  *
11441  *   Arguments: un - ptr to softstate
11442  *		bp - ptr to associated buf(9S)
11443  *		xp - ptr to associated sd_xbuf
11444  *		chain_type - IO chain type to use:
11445  *			SD_CHAIN_NULL
11446  *			SD_CHAIN_BUFIO
11447  *			SD_CHAIN_USCSI
11448  *			SD_CHAIN_DIRECT
11449  *			SD_CHAIN_DIRECT_PRIORITY
11450  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11451  *			initialization; may be NULL if none.
11452  *
11453  *     Context: Kernel thread context
11454  */
11455 
11456 static void
11457 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11458     uchar_t chain_type, void *pktinfop)
11459 {
11460 	int index;
11461 
11462 	ASSERT(un != NULL);
11463 	ASSERT(bp != NULL);
11464 	ASSERT(xp != NULL);
11465 
11466 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11467 	    bp, chain_type);
11468 
11469 	xp->xb_un	= un;
11470 	xp->xb_pktp	= NULL;
11471 	xp->xb_pktinfo	= pktinfop;
11472 	xp->xb_private	= bp->b_private;
11473 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11474 
11475 	/*
11476 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11477 	 * upon the specified chain type to use.
11478 	 */
11479 	switch (chain_type) {
11480 	case SD_CHAIN_NULL:
11481 		/*
11482 		 * Fall thru to just use the values for the buf type, even
11483 		 * tho for the NULL chain these values will never be used.
11484 		 */
11485 		/* FALLTHRU */
11486 	case SD_CHAIN_BUFIO:
11487 		index = un->un_buf_chain_type;
11488 		if ((!un->un_f_has_removable_media) &&
11489 		    (un->un_tgt_blocksize != 0) &&
11490 		    (un->un_tgt_blocksize != DEV_BSIZE ||
11491 		    un->un_f_enable_rmw)) {
11492 			int secmask = 0, blknomask = 0;
11493 			if (un->un_f_enable_rmw) {
11494 				blknomask =
11495 				    (un->un_phy_blocksize / DEV_BSIZE) - 1;
11496 				secmask = un->un_phy_blocksize - 1;
11497 			} else {
11498 				blknomask =
11499 				    (un->un_tgt_blocksize / DEV_BSIZE) - 1;
11500 				secmask = un->un_tgt_blocksize - 1;
11501 			}
11502 
11503 			if ((bp->b_lblkno & (blknomask)) ||
11504 			    (bp->b_bcount & (secmask))) {
11505 				if ((un->un_f_rmw_type !=
11506 				    SD_RMW_TYPE_RETURN_ERROR) ||
11507 				    un->un_f_enable_rmw) {
11508 					if (un->un_f_pm_is_enabled == FALSE)
11509 						index =
11510 						    SD_CHAIN_INFO_MSS_DSK_NO_PM;
11511 					else
11512 						index =
11513 						    SD_CHAIN_INFO_MSS_DISK;
11514 				}
11515 			}
11516 		}
11517 		break;
11518 	case SD_CHAIN_USCSI:
11519 		index = un->un_uscsi_chain_type;
11520 		break;
11521 	case SD_CHAIN_DIRECT:
11522 		index = un->un_direct_chain_type;
11523 		break;
11524 	case SD_CHAIN_DIRECT_PRIORITY:
11525 		index = un->un_priority_chain_type;
11526 		break;
11527 	default:
11528 		/* We're really broken if we ever get here... */
11529 		panic("sd_xbuf_init: illegal chain type!");
11530 		/*NOTREACHED*/
11531 	}
11532 
11533 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11534 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11535 
11536 	/*
11537 	 * It might be a bit easier to simply bzero the entire xbuf above,
11538 	 * but it turns out that since we init a fair number of members anyway,
11539 	 * we save a fair number cycles by doing explicit assignment of zero.
11540 	 */
11541 	xp->xb_pkt_flags	= 0;
11542 	xp->xb_dma_resid	= 0;
11543 	xp->xb_retry_count	= 0;
11544 	xp->xb_victim_retry_count = 0;
11545 	xp->xb_ua_retry_count	= 0;
11546 	xp->xb_nr_retry_count	= 0;
11547 	xp->xb_sense_bp		= NULL;
11548 	xp->xb_sense_status	= 0;
11549 	xp->xb_sense_state	= 0;
11550 	xp->xb_sense_resid	= 0;
11551 	xp->xb_ena		= 0;
11552 
11553 	bp->b_private	= xp;
11554 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11555 	bp->b_resid	= 0;
11556 	bp->av_forw	= NULL;
11557 	bp->av_back	= NULL;
11558 	bioerror(bp, 0);
11559 
11560 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11561 }
11562 
11563 
11564 /*
11565  *    Function: sd_uscsi_strategy
11566  *
11567  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11568  *
11569  *   Arguments: bp - buf struct ptr
11570  *
11571  * Return Code: Always returns 0
11572  *
11573  *     Context: Kernel thread context
11574  */
11575 
11576 static int
11577 sd_uscsi_strategy(struct buf *bp)
11578 {
11579 	struct sd_lun		*un;
11580 	struct sd_uscsi_info	*uip;
11581 	struct sd_xbuf		*xp;
11582 	uchar_t			chain_type;
11583 	uchar_t			cmd;
11584 
11585 	ASSERT(bp != NULL);
11586 
11587 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11588 	if (un == NULL) {
11589 		bioerror(bp, EIO);
11590 		bp->b_resid = bp->b_bcount;
11591 		biodone(bp);
11592 		return (0);
11593 	}
11594 
11595 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11596 
11597 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11598 
11599 	/*
11600 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11601 	 */
11602 	ASSERT(bp->b_private != NULL);
11603 	uip = (struct sd_uscsi_info *)bp->b_private;
11604 	cmd = ((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_cdb[0];
11605 
11606 	mutex_enter(SD_MUTEX(un));
11607 	/*
11608 	 * atapi: Since we are running the CD for now in PIO mode we need to
11609 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11610 	 * the HBA's init_pkt routine.
11611 	 */
11612 	if (un->un_f_cfg_is_atapi == TRUE) {
11613 		mutex_exit(SD_MUTEX(un));
11614 		bp_mapin(bp);
11615 		mutex_enter(SD_MUTEX(un));
11616 	}
11617 	un->un_ncmds_in_driver++;
11618 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11619 	    un->un_ncmds_in_driver);
11620 
11621 	if ((bp->b_flags & B_WRITE) && (bp->b_bcount != 0) &&
11622 	    (cmd != SCMD_MODE_SELECT) && (cmd != SCMD_MODE_SELECT_G1))
11623 		un->un_f_sync_cache_required = TRUE;
11624 
11625 	mutex_exit(SD_MUTEX(un));
11626 
11627 	switch (uip->ui_flags) {
11628 	case SD_PATH_DIRECT:
11629 		chain_type = SD_CHAIN_DIRECT;
11630 		break;
11631 	case SD_PATH_DIRECT_PRIORITY:
11632 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11633 		break;
11634 	default:
11635 		chain_type = SD_CHAIN_USCSI;
11636 		break;
11637 	}
11638 
11639 	/*
11640 	 * We may allocate extra buf for external USCSI commands. If the
11641 	 * application asks for bigger than 20-byte sense data via USCSI,
11642 	 * SCSA layer will allocate 252 bytes sense buf for that command.
11643 	 */
11644 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
11645 	    SENSE_LENGTH) {
11646 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
11647 		    MAX_SENSE_LENGTH, KM_SLEEP);
11648 	} else {
11649 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
11650 	}
11651 
11652 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11653 
11654 	/* Use the index obtained within xbuf_init */
11655 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11656 
11657 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11658 
11659 	return (0);
11660 }
11661 
11662 /*
11663  *    Function: sd_send_scsi_cmd
11664  *
11665  * Description: Runs a USCSI command for user (when called thru sdioctl),
11666  *		or for the driver
11667  *
11668  *   Arguments: dev - the dev_t for the device
11669  *		incmd - ptr to a valid uscsi_cmd struct
11670  *		flag - bit flag, indicating open settings, 32/64 bit type
11671  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11672  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11673  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11674  *			to use the USCSI "direct" chain and bypass the normal
11675  *			command waitq.
11676  *
11677  * Return Code: 0 -  successful completion of the given command
11678  *		EIO - scsi_uscsi_handle_command() failed
11679  *		ENXIO  - soft state not found for specified dev
11680  *		EINVAL
11681  *		EFAULT - copyin/copyout error
11682  *		return code of scsi_uscsi_handle_command():
11683  *			EIO
11684  *			ENXIO
11685  *			EACCES
11686  *
11687  *     Context: Waits for command to complete. Can sleep.
11688  */
11689 
11690 static int
11691 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
11692     enum uio_seg dataspace, int path_flag)
11693 {
11694 	struct sd_lun	*un;
11695 	sd_ssc_t	*ssc;
11696 	int		rval;
11697 
11698 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11699 	if (un == NULL) {
11700 		return (ENXIO);
11701 	}
11702 
11703 	/*
11704 	 * Using sd_ssc_send to handle uscsi cmd
11705 	 */
11706 	ssc = sd_ssc_init(un);
11707 	rval = sd_ssc_send(ssc, incmd, flag, dataspace, path_flag);
11708 	sd_ssc_fini(ssc);
11709 
11710 	return (rval);
11711 }
11712 
11713 /*
11714  *    Function: sd_ssc_init
11715  *
11716  * Description: Uscsi end-user call this function to initialize necessary
11717  *              fields, such as uscsi_cmd and sd_uscsi_info struct.
11718  *
11719  *              The return value of sd_send_scsi_cmd will be treated as a
11720  *              fault in various conditions. Even it is not Zero, some
11721  *              callers may ignore the return value. That is to say, we can
11722  *              not make an accurate assessment in sdintr, since if a
11723  *              command is failed in sdintr it does not mean the caller of
11724  *              sd_send_scsi_cmd will treat it as a real failure.
11725  *
11726  *              To avoid printing too many error logs for a failed uscsi
11727  *              packet that the caller may not treat it as a failure, the
11728  *              sd will keep silent for handling all uscsi commands.
11729  *
11730  *              During detach->attach and attach-open, for some types of
11731  *              problems, the driver should be providing information about
11732  *              the problem encountered. Device use USCSI_SILENT, which
11733  *              suppresses all driver information. The result is that no
11734  *              information about the problem is available. Being
11735  *              completely silent during this time is inappropriate. The
11736  *              driver needs a more selective filter than USCSI_SILENT, so
11737  *              that information related to faults is provided.
11738  *
11739  *              To make the accurate accessment, the caller  of
11740  *              sd_send_scsi_USCSI_CMD should take the ownership and
11741  *              get necessary information to print error messages.
11742  *
11743  *              If we want to print necessary info of uscsi command, we need to
11744  *              keep the uscsi_cmd and sd_uscsi_info till we can make the
11745  *              assessment. We use sd_ssc_init to alloc necessary
11746  *              structs for sending an uscsi command and we are also
11747  *              responsible for free the memory by calling
11748  *              sd_ssc_fini.
11749  *
11750  *              The calling secquences will look like:
11751  *              sd_ssc_init->
11752  *
11753  *                  ...
11754  *
11755  *                  sd_send_scsi_USCSI_CMD->
11756  *                      sd_ssc_send-> - - - sdintr
11757  *                  ...
11758  *
11759  *                  if we think the return value should be treated as a
11760  *                  failure, we make the accessment here and print out
11761  *                  necessary by retrieving uscsi_cmd and sd_uscsi_info'
11762  *
11763  *                  ...
11764  *
11765  *              sd_ssc_fini
11766  *
11767  *
11768  *   Arguments: un - pointer to driver soft state (unit) structure for this
11769  *                   target.
11770  *
11771  * Return code: sd_ssc_t - pointer to allocated sd_ssc_t struct, it contains
11772  *                         uscsi_cmd and sd_uscsi_info.
11773  *                  NULL - if can not alloc memory for sd_ssc_t struct
11774  *
11775  *     Context: Kernel Thread.
11776  */
11777 static sd_ssc_t *
11778 sd_ssc_init(struct sd_lun *un)
11779 {
11780 	sd_ssc_t		*ssc;
11781 	struct uscsi_cmd	*ucmdp;
11782 	struct sd_uscsi_info	*uip;
11783 
11784 	ASSERT(un != NULL);
11785 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11786 
11787 	/*
11788 	 * Allocate sd_ssc_t structure
11789 	 */
11790 	ssc = kmem_zalloc(sizeof (sd_ssc_t), KM_SLEEP);
11791 
11792 	/*
11793 	 * Allocate uscsi_cmd by calling scsi_uscsi_alloc common routine
11794 	 */
11795 	ucmdp = scsi_uscsi_alloc();
11796 
11797 	/*
11798 	 * Allocate sd_uscsi_info structure
11799 	 */
11800 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11801 
11802 	ssc->ssc_uscsi_cmd = ucmdp;
11803 	ssc->ssc_uscsi_info = uip;
11804 	ssc->ssc_un = un;
11805 
11806 	return (ssc);
11807 }
11808 
11809 /*
11810  * Function: sd_ssc_fini
11811  *
11812  * Description: To free sd_ssc_t and it's hanging off
11813  *
11814  * Arguments: ssc - struct pointer of sd_ssc_t.
11815  */
11816 static void
11817 sd_ssc_fini(sd_ssc_t *ssc)
11818 {
11819 	scsi_uscsi_free(ssc->ssc_uscsi_cmd);
11820 
11821 	if (ssc->ssc_uscsi_info != NULL) {
11822 		kmem_free(ssc->ssc_uscsi_info, sizeof (struct sd_uscsi_info));
11823 		ssc->ssc_uscsi_info = NULL;
11824 	}
11825 
11826 	kmem_free(ssc, sizeof (sd_ssc_t));
11827 	ssc = NULL;
11828 }
11829 
11830 /*
11831  * Function: sd_ssc_send
11832  *
11833  * Description: Runs a USCSI command for user when called through sdioctl,
11834  *              or for the driver.
11835  *
11836  *   Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11837  *                    sd_uscsi_info in.
11838  *		incmd - ptr to a valid uscsi_cmd struct
11839  *		flag - bit flag, indicating open settings, 32/64 bit type
11840  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11841  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11842  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11843  *			to use the USCSI "direct" chain and bypass the normal
11844  *			command waitq.
11845  *
11846  * Return Code: 0 -  successful completion of the given command
11847  *		EIO - scsi_uscsi_handle_command() failed
11848  *		ENXIO  - soft state not found for specified dev
11849  *		ECANCELED - command cancelled due to low power
11850  *		EINVAL
11851  *		EFAULT - copyin/copyout error
11852  *		return code of scsi_uscsi_handle_command():
11853  *			EIO
11854  *			ENXIO
11855  *			EACCES
11856  *
11857  *     Context: Kernel Thread;
11858  *              Waits for command to complete. Can sleep.
11859  */
11860 static int
11861 sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd, int flag,
11862     enum uio_seg dataspace, int path_flag)
11863 {
11864 	struct sd_uscsi_info	*uip;
11865 	struct uscsi_cmd	*uscmd;
11866 	struct sd_lun		*un;
11867 	dev_t			dev;
11868 
11869 	int	format = 0;
11870 	int	rval;
11871 
11872 	ASSERT(ssc != NULL);
11873 	un = ssc->ssc_un;
11874 	ASSERT(un != NULL);
11875 	uscmd = ssc->ssc_uscsi_cmd;
11876 	ASSERT(uscmd != NULL);
11877 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11878 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
11879 		/*
11880 		 * If enter here, it indicates that the previous uscsi
11881 		 * command has not been processed by sd_ssc_assessment.
11882 		 * This is violating our rules of FMA telemetry processing.
11883 		 * We should print out this message and the last undisposed
11884 		 * uscsi command.
11885 		 */
11886 		if (uscmd->uscsi_cdb != NULL) {
11887 			SD_INFO(SD_LOG_SDTEST, un,
11888 			    "sd_ssc_send is missing the alternative "
11889 			    "sd_ssc_assessment when running command 0x%x.\n",
11890 			    uscmd->uscsi_cdb[0]);
11891 		}
11892 		/*
11893 		 * Set the ssc_flags to SSC_FLAGS_UNKNOWN, which should be
11894 		 * the initial status.
11895 		 */
11896 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11897 	}
11898 
11899 	/*
11900 	 * We need to make sure sd_ssc_send will have sd_ssc_assessment
11901 	 * followed to avoid missing FMA telemetries.
11902 	 */
11903 	ssc->ssc_flags |= SSC_FLAGS_NEED_ASSESSMENT;
11904 
11905 	/*
11906 	 * if USCSI_PMFAILFAST is set and un is in low power, fail the
11907 	 * command immediately.
11908 	 */
11909 	mutex_enter(SD_MUTEX(un));
11910 	mutex_enter(&un->un_pm_mutex);
11911 	if ((uscmd->uscsi_flags & USCSI_PMFAILFAST) &&
11912 	    SD_DEVICE_IS_IN_LOW_POWER(un)) {
11913 		SD_TRACE(SD_LOG_IO, un, "sd_ssc_send:"
11914 		    "un:0x%p is in low power\n", un);
11915 		mutex_exit(&un->un_pm_mutex);
11916 		mutex_exit(SD_MUTEX(un));
11917 		return (ECANCELED);
11918 	}
11919 	mutex_exit(&un->un_pm_mutex);
11920 	mutex_exit(SD_MUTEX(un));
11921 
11922 #ifdef SDDEBUG
11923 	switch (dataspace) {
11924 	case UIO_USERSPACE:
11925 		SD_TRACE(SD_LOG_IO, un,
11926 		    "sd_ssc_send: entry: un:0x%p UIO_USERSPACE\n", un);
11927 		break;
11928 	case UIO_SYSSPACE:
11929 		SD_TRACE(SD_LOG_IO, un,
11930 		    "sd_ssc_send: entry: un:0x%p UIO_SYSSPACE\n", un);
11931 		break;
11932 	default:
11933 		SD_TRACE(SD_LOG_IO, un,
11934 		    "sd_ssc_send: entry: un:0x%p UNEXPECTED SPACE\n", un);
11935 		break;
11936 	}
11937 #endif
11938 
11939 	rval = scsi_uscsi_copyin((intptr_t)incmd, flag,
11940 	    SD_ADDRESS(un), &uscmd);
11941 	if (rval != 0) {
11942 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
11943 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
11944 		return (rval);
11945 	}
11946 
11947 	if ((uscmd->uscsi_cdb != NULL) &&
11948 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
11949 		mutex_enter(SD_MUTEX(un));
11950 		un->un_f_format_in_progress = TRUE;
11951 		mutex_exit(SD_MUTEX(un));
11952 		format = 1;
11953 	}
11954 
11955 	/*
11956 	 * Allocate an sd_uscsi_info struct and fill it with the info
11957 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
11958 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
11959 	 * since we allocate the buf here in this function, we do not
11960 	 * need to preserve the prior contents of b_private.
11961 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
11962 	 */
11963 	uip = ssc->ssc_uscsi_info;
11964 	uip->ui_flags = path_flag;
11965 	uip->ui_cmdp = uscmd;
11966 
11967 	/*
11968 	 * Commands sent with priority are intended for error recovery
11969 	 * situations, and do not have retries performed.
11970 	 */
11971 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
11972 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
11973 	}
11974 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
11975 
11976 	dev = SD_GET_DEV(un);
11977 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
11978 	    sd_uscsi_strategy, NULL, uip);
11979 
11980 	/*
11981 	 * mark ssc_flags right after handle_cmd to make sure
11982 	 * the uscsi has been sent
11983 	 */
11984 	ssc->ssc_flags |= SSC_FLAGS_CMD_ISSUED;
11985 
11986 #ifdef SDDEBUG
11987 	SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11988 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
11989 	    uscmd->uscsi_status, uscmd->uscsi_resid);
11990 	if (uscmd->uscsi_bufaddr != NULL) {
11991 		SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11992 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
11993 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
11994 		if (dataspace == UIO_SYSSPACE) {
11995 			SD_DUMP_MEMORY(un, SD_LOG_IO,
11996 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
11997 			    uscmd->uscsi_buflen, SD_LOG_HEX);
11998 		}
11999 	}
12000 #endif
12001 
12002 	if (format == 1) {
12003 		mutex_enter(SD_MUTEX(un));
12004 		un->un_f_format_in_progress = FALSE;
12005 		mutex_exit(SD_MUTEX(un));
12006 	}
12007 
12008 	(void) scsi_uscsi_copyout((intptr_t)incmd, uscmd);
12009 
12010 	return (rval);
12011 }
12012 
12013 /*
12014  *     Function: sd_ssc_print
12015  *
12016  * Description: Print information available to the console.
12017  *
12018  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12019  *                    sd_uscsi_info in.
12020  *            sd_severity - log level.
12021  *     Context: Kernel thread or interrupt context.
12022  */
12023 static void
12024 sd_ssc_print(sd_ssc_t *ssc, int sd_severity)
12025 {
12026 	struct uscsi_cmd	*ucmdp;
12027 	struct scsi_device	*devp;
12028 	dev_info_t		*devinfo;
12029 	uchar_t			*sensep;
12030 	int			senlen;
12031 	union scsi_cdb		*cdbp;
12032 	uchar_t			com;
12033 	extern struct scsi_key_strings scsi_cmds[];
12034 
12035 	ASSERT(ssc != NULL);
12036 	ASSERT(ssc->ssc_un != NULL);
12037 
12038 	if (SD_FM_LOG(ssc->ssc_un) != SD_FM_LOG_EREPORT)
12039 		return;
12040 	ucmdp = ssc->ssc_uscsi_cmd;
12041 	devp = SD_SCSI_DEVP(ssc->ssc_un);
12042 	devinfo = SD_DEVINFO(ssc->ssc_un);
12043 	ASSERT(ucmdp != NULL);
12044 	ASSERT(devp != NULL);
12045 	ASSERT(devinfo != NULL);
12046 	sensep = (uint8_t *)ucmdp->uscsi_rqbuf;
12047 	senlen = ucmdp->uscsi_rqlen - ucmdp->uscsi_rqresid;
12048 	cdbp = (union scsi_cdb *)ucmdp->uscsi_cdb;
12049 
12050 	/* In certain case (like DOORLOCK), the cdb could be NULL. */
12051 	if (cdbp == NULL)
12052 		return;
12053 	/* We don't print log if no sense data available. */
12054 	if (senlen == 0)
12055 		sensep = NULL;
12056 	com = cdbp->scc_cmd;
12057 	scsi_generic_errmsg(devp, sd_label, sd_severity, 0, 0, com,
12058 	    scsi_cmds, sensep, ssc->ssc_un->un_additional_codes, NULL);
12059 }
12060 
12061 /*
12062  *     Function: sd_ssc_assessment
12063  *
12064  * Description: We use this function to make an assessment at the point
12065  *              where SD driver may encounter a potential error.
12066  *
12067  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12068  *                  sd_uscsi_info in.
12069  *            tp_assess - a hint of strategy for ereport posting.
12070  *            Possible values of tp_assess include:
12071  *                SD_FMT_IGNORE - we don't post any ereport because we're
12072  *                sure that it is ok to ignore the underlying problems.
12073  *                SD_FMT_IGNORE_COMPROMISE - we don't post any ereport for now
12074  *                but it might be not correct to ignore the underlying hardware
12075  *                error.
12076  *                SD_FMT_STATUS_CHECK - we will post an ereport with the
12077  *                payload driver-assessment of value "fail" or
12078  *                "fatal"(depending on what information we have here). This
12079  *                assessment value is usually set when SD driver think there
12080  *                is a potential error occurred(Typically, when return value
12081  *                of the SCSI command is EIO).
12082  *                SD_FMT_STANDARD - we will post an ereport with the payload
12083  *                driver-assessment of value "info". This assessment value is
12084  *                set when the SCSI command returned successfully and with
12085  *                sense data sent back.
12086  *
12087  *     Context: Kernel thread.
12088  */
12089 static void
12090 sd_ssc_assessment(sd_ssc_t *ssc, enum sd_type_assessment tp_assess)
12091 {
12092 	int senlen = 0;
12093 	struct uscsi_cmd *ucmdp = NULL;
12094 	struct sd_lun *un;
12095 
12096 	ASSERT(ssc != NULL);
12097 	un = ssc->ssc_un;
12098 	ASSERT(un != NULL);
12099 	ucmdp = ssc->ssc_uscsi_cmd;
12100 	ASSERT(ucmdp != NULL);
12101 
12102 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
12103 		ssc->ssc_flags &= ~SSC_FLAGS_NEED_ASSESSMENT;
12104 	} else {
12105 		/*
12106 		 * If enter here, it indicates that we have a wrong
12107 		 * calling sequence of sd_ssc_send and sd_ssc_assessment,
12108 		 * both of which should be called in a pair in case of
12109 		 * loss of FMA telemetries.
12110 		 */
12111 		if (ucmdp->uscsi_cdb != NULL) {
12112 			SD_INFO(SD_LOG_SDTEST, un,
12113 			    "sd_ssc_assessment is missing the "
12114 			    "alternative sd_ssc_send when running 0x%x, "
12115 			    "or there are superfluous sd_ssc_assessment for "
12116 			    "the same sd_ssc_send.\n",
12117 			    ucmdp->uscsi_cdb[0]);
12118 		}
12119 		/*
12120 		 * Set the ssc_flags to the initial value to avoid passing
12121 		 * down dirty flags to the following sd_ssc_send function.
12122 		 */
12123 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12124 		return;
12125 	}
12126 
12127 	/*
12128 	 * Only handle an issued command which is waiting for assessment.
12129 	 * A command which is not issued will not have
12130 	 * SSC_FLAGS_INVALID_DATA set, so it'ok we just return here.
12131 	 */
12132 	if (!(ssc->ssc_flags & SSC_FLAGS_CMD_ISSUED)) {
12133 		sd_ssc_print(ssc, SCSI_ERR_INFO);
12134 		return;
12135 	} else {
12136 		/*
12137 		 * For an issued command, we should clear this flag in
12138 		 * order to make the sd_ssc_t structure be used off
12139 		 * multiple uscsi commands.
12140 		 */
12141 		ssc->ssc_flags &= ~SSC_FLAGS_CMD_ISSUED;
12142 	}
12143 
12144 	/*
12145 	 * We will not deal with non-retryable(flag USCSI_DIAGNOSE set)
12146 	 * commands here. And we should clear the ssc_flags before return.
12147 	 */
12148 	if (ucmdp->uscsi_flags & USCSI_DIAGNOSE) {
12149 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12150 		return;
12151 	}
12152 
12153 	switch (tp_assess) {
12154 	case SD_FMT_IGNORE:
12155 	case SD_FMT_IGNORE_COMPROMISE:
12156 		break;
12157 	case SD_FMT_STATUS_CHECK:
12158 		/*
12159 		 * For a failed command(including the succeeded command
12160 		 * with invalid data sent back).
12161 		 */
12162 		sd_ssc_post(ssc, SD_FM_DRV_FATAL);
12163 		break;
12164 	case SD_FMT_STANDARD:
12165 		/*
12166 		 * Always for the succeeded commands probably with sense
12167 		 * data sent back.
12168 		 * Limitation:
12169 		 *	We can only handle a succeeded command with sense
12170 		 *	data sent back when auto-request-sense is enabled.
12171 		 */
12172 		senlen = ssc->ssc_uscsi_cmd->uscsi_rqlen -
12173 		    ssc->ssc_uscsi_cmd->uscsi_rqresid;
12174 		if ((ssc->ssc_uscsi_info->ui_pkt_state & STATE_ARQ_DONE) &&
12175 		    (un->un_f_arq_enabled == TRUE) &&
12176 		    senlen > 0 &&
12177 		    ssc->ssc_uscsi_cmd->uscsi_rqbuf != NULL) {
12178 			sd_ssc_post(ssc, SD_FM_DRV_NOTICE);
12179 		}
12180 		break;
12181 	default:
12182 		/*
12183 		 * Should not have other type of assessment.
12184 		 */
12185 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
12186 		    "sd_ssc_assessment got wrong "
12187 		    "sd_type_assessment %d.\n", tp_assess);
12188 		break;
12189 	}
12190 	/*
12191 	 * Clear up the ssc_flags before return.
12192 	 */
12193 	ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12194 }
12195 
12196 /*
12197  *    Function: sd_ssc_post
12198  *
12199  * Description: 1. read the driver property to get fm-scsi-log flag.
12200  *              2. print log if fm_log_capable is non-zero.
12201  *              3. call sd_ssc_ereport_post to post ereport if possible.
12202  *
12203  *    Context: May be called from kernel thread or interrupt context.
12204  */
12205 static void
12206 sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess)
12207 {
12208 	struct sd_lun	*un;
12209 	int		sd_severity;
12210 
12211 	ASSERT(ssc != NULL);
12212 	un = ssc->ssc_un;
12213 	ASSERT(un != NULL);
12214 
12215 	/*
12216 	 * We may enter here from sd_ssc_assessment(for USCSI command) or
12217 	 * by directly called from sdintr context.
12218 	 * We don't handle a non-disk drive(CD-ROM, removable media).
12219 	 * Clear the ssc_flags before return in case we've set
12220 	 * SSC_FLAGS_INVALID_XXX which should be skipped for a non-disk
12221 	 * driver.
12222 	 */
12223 	if (ISCD(un) || un->un_f_has_removable_media) {
12224 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12225 		return;
12226 	}
12227 
12228 	switch (sd_assess) {
12229 		case SD_FM_DRV_FATAL:
12230 			sd_severity = SCSI_ERR_FATAL;
12231 			break;
12232 		case SD_FM_DRV_RECOVERY:
12233 			sd_severity = SCSI_ERR_RECOVERED;
12234 			break;
12235 		case SD_FM_DRV_RETRY:
12236 			sd_severity = SCSI_ERR_RETRYABLE;
12237 			break;
12238 		case SD_FM_DRV_NOTICE:
12239 			sd_severity = SCSI_ERR_INFO;
12240 			break;
12241 		default:
12242 			sd_severity = SCSI_ERR_UNKNOWN;
12243 	}
12244 	/* print log */
12245 	sd_ssc_print(ssc, sd_severity);
12246 
12247 	/* always post ereport */
12248 	sd_ssc_ereport_post(ssc, sd_assess);
12249 }
12250 
12251 /*
12252  *    Function: sd_ssc_set_info
12253  *
12254  * Description: Mark ssc_flags and set ssc_info which would be the
12255  *              payload of uderr ereport. This function will cause
12256  *              sd_ssc_ereport_post to post uderr ereport only.
12257  *              Besides, when ssc_flags == SSC_FLAGS_INVALID_DATA(USCSI),
12258  *              the function will also call SD_ERROR or scsi_log for a
12259  *              CDROM/removable-media/DDI_FM_NOT_CAPABLE device.
12260  *
12261  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12262  *                  sd_uscsi_info in.
12263  *            ssc_flags - indicate the sub-category of a uderr.
12264  *            comp - this argument is meaningful only when
12265  *                   ssc_flags == SSC_FLAGS_INVALID_DATA, and its possible
12266  *                   values include:
12267  *                   > 0, SD_ERROR is used with comp as the driver logging
12268  *                   component;
12269  *                   = 0, scsi-log is used to log error telemetries;
12270  *                   < 0, no log available for this telemetry.
12271  *
12272  *    Context: Kernel thread or interrupt context
12273  */
12274 static void
12275 sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp, const char *fmt, ...)
12276 {
12277 	va_list	ap;
12278 
12279 	ASSERT(ssc != NULL);
12280 	ASSERT(ssc->ssc_un != NULL);
12281 
12282 	ssc->ssc_flags |= ssc_flags;
12283 	va_start(ap, fmt);
12284 	(void) vsnprintf(ssc->ssc_info, sizeof (ssc->ssc_info), fmt, ap);
12285 	va_end(ap);
12286 
12287 	/*
12288 	 * If SSC_FLAGS_INVALID_DATA is set, it should be a uscsi command
12289 	 * with invalid data sent back. For non-uscsi command, the
12290 	 * following code will be bypassed.
12291 	 */
12292 	if (ssc_flags & SSC_FLAGS_INVALID_DATA) {
12293 		if (SD_FM_LOG(ssc->ssc_un) == SD_FM_LOG_NSUP) {
12294 			/*
12295 			 * If the error belong to certain component and we
12296 			 * do not want it to show up on the console, we
12297 			 * will use SD_ERROR, otherwise scsi_log is
12298 			 * preferred.
12299 			 */
12300 			if (comp > 0) {
12301 				SD_ERROR(comp, ssc->ssc_un, ssc->ssc_info);
12302 			} else if (comp == 0) {
12303 				scsi_log(SD_DEVINFO(ssc->ssc_un), sd_label,
12304 				    CE_WARN, ssc->ssc_info);
12305 			}
12306 		}
12307 	}
12308 }
12309 
12310 /*
12311  *    Function: sd_buf_iodone
12312  *
12313  * Description: Frees the sd_xbuf & returns the buf to its originator.
12314  *
12315  *     Context: May be called from interrupt context.
12316  */
12317 /* ARGSUSED */
12318 static void
12319 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
12320 {
12321 	struct sd_xbuf *xp;
12322 
12323 	ASSERT(un != NULL);
12324 	ASSERT(bp != NULL);
12325 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12326 
12327 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
12328 
12329 	xp = SD_GET_XBUF(bp);
12330 	ASSERT(xp != NULL);
12331 
12332 	/* xbuf is gone after this */
12333 	if (ddi_xbuf_done(bp, un->un_xbuf_attr)) {
12334 		mutex_enter(SD_MUTEX(un));
12335 
12336 		/*
12337 		 * Grab time when the cmd completed.
12338 		 * This is used for determining if the system has been
12339 		 * idle long enough to make it idle to the PM framework.
12340 		 * This is for lowering the overhead, and therefore improving
12341 		 * performance per I/O operation.
12342 		 */
12343 		un->un_pm_idle_time = gethrtime();
12344 
12345 		un->un_ncmds_in_driver--;
12346 		ASSERT(un->un_ncmds_in_driver >= 0);
12347 		SD_INFO(SD_LOG_IO, un,
12348 		    "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
12349 		    un->un_ncmds_in_driver);
12350 
12351 		mutex_exit(SD_MUTEX(un));
12352 	}
12353 
12354 	biodone(bp);				/* bp is gone after this */
12355 
12356 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
12357 }
12358 
12359 
12360 /*
12361  *    Function: sd_uscsi_iodone
12362  *
12363  * Description: Frees the sd_xbuf & returns the buf to its originator.
12364  *
12365  *     Context: May be called from interrupt context.
12366  */
12367 /* ARGSUSED */
12368 static void
12369 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12370 {
12371 	struct sd_xbuf *xp;
12372 
12373 	ASSERT(un != NULL);
12374 	ASSERT(bp != NULL);
12375 
12376 	xp = SD_GET_XBUF(bp);
12377 	ASSERT(xp != NULL);
12378 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12379 
12380 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
12381 
12382 	bp->b_private = xp->xb_private;
12383 
12384 	mutex_enter(SD_MUTEX(un));
12385 
12386 	/*
12387 	 * Grab time when the cmd completed.
12388 	 * This is used for determining if the system has been
12389 	 * idle long enough to make it idle to the PM framework.
12390 	 * This is for lowering the overhead, and therefore improving
12391 	 * performance per I/O operation.
12392 	 */
12393 	un->un_pm_idle_time = gethrtime();
12394 
12395 	un->un_ncmds_in_driver--;
12396 	ASSERT(un->un_ncmds_in_driver >= 0);
12397 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
12398 	    un->un_ncmds_in_driver);
12399 
12400 	mutex_exit(SD_MUTEX(un));
12401 
12402 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
12403 	    SENSE_LENGTH) {
12404 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
12405 		    MAX_SENSE_LENGTH);
12406 	} else {
12407 		kmem_free(xp, sizeof (struct sd_xbuf));
12408 	}
12409 
12410 	biodone(bp);
12411 
12412 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
12413 }
12414 
12415 
12416 /*
12417  *    Function: sd_mapblockaddr_iostart
12418  *
12419  * Description: Verify request lies within the partition limits for
12420  *		the indicated minor device.  Issue "overrun" buf if
12421  *		request would exceed partition range.  Converts
12422  *		partition-relative block address to absolute.
12423  *
12424  *              Upon exit of this function:
12425  *              1.I/O is aligned
12426  *                 xp->xb_blkno represents the absolute sector address
12427  *              2.I/O is misaligned
12428  *                 xp->xb_blkno represents the absolute logical block address
12429  *                 based on DEV_BSIZE. The logical block address will be
12430  *                 converted to physical sector address in sd_mapblocksize_\
12431  *                 iostart.
12432  *              3.I/O is misaligned but is aligned in "overrun" buf
12433  *                 xp->xb_blkno represents the absolute logical block address
12434  *                 based on DEV_BSIZE. The logical block address will be
12435  *                 converted to physical sector address in sd_mapblocksize_\
12436  *                 iostart. But no RMW will be issued in this case.
12437  *
12438  *     Context: Can sleep
12439  *
12440  *      Issues: This follows what the old code did, in terms of accessing
12441  *		some of the partition info in the unit struct without holding
12442  *		the mutext.  This is a general issue, if the partition info
12443  *		can be altered while IO is in progress... as soon as we send
12444  *		a buf, its partitioning can be invalid before it gets to the
12445  *		device.  Probably the right fix is to move partitioning out
12446  *		of the driver entirely.
12447  */
12448 
12449 static void
12450 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
12451 {
12452 	diskaddr_t	nblocks;	/* #blocks in the given partition */
12453 	daddr_t	blocknum;	/* Block number specified by the buf */
12454 	size_t	requested_nblocks;
12455 	size_t	available_nblocks;
12456 	int	partition;
12457 	diskaddr_t	partition_offset;
12458 	struct sd_xbuf *xp;
12459 	int secmask = 0, blknomask = 0;
12460 	ushort_t is_aligned = TRUE;
12461 
12462 	ASSERT(un != NULL);
12463 	ASSERT(bp != NULL);
12464 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12465 
12466 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12467 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
12468 
12469 	xp = SD_GET_XBUF(bp);
12470 	ASSERT(xp != NULL);
12471 
12472 	/*
12473 	 * If the geometry is not indicated as valid, attempt to access
12474 	 * the unit & verify the geometry/label. This can be the case for
12475 	 * removable-media devices, of if the device was opened in
12476 	 * NDELAY/NONBLOCK mode.
12477 	 */
12478 	partition = SDPART(bp->b_edev);
12479 
12480 	if (!SD_IS_VALID_LABEL(un)) {
12481 		sd_ssc_t *ssc;
12482 		/*
12483 		 * Initialize sd_ssc_t for internal uscsi commands
12484 		 * In case of potential porformance issue, we need
12485 		 * to alloc memory only if there is invalid label
12486 		 */
12487 		ssc = sd_ssc_init(un);
12488 
12489 		if (sd_ready_and_valid(ssc, partition) != SD_READY_VALID) {
12490 			/*
12491 			 * For removable devices it is possible to start an
12492 			 * I/O without a media by opening the device in nodelay
12493 			 * mode. Also for writable CDs there can be many
12494 			 * scenarios where there is no geometry yet but volume
12495 			 * manager is trying to issue a read() just because
12496 			 * it can see TOC on the CD. So do not print a message
12497 			 * for removables.
12498 			 */
12499 			if (!un->un_f_has_removable_media) {
12500 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12501 				    "i/o to invalid geometry\n");
12502 			}
12503 			bioerror(bp, EIO);
12504 			bp->b_resid = bp->b_bcount;
12505 			SD_BEGIN_IODONE(index, un, bp);
12506 
12507 			sd_ssc_fini(ssc);
12508 			return;
12509 		}
12510 		sd_ssc_fini(ssc);
12511 	}
12512 
12513 	nblocks = 0;
12514 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
12515 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
12516 
12517 	if (un->un_f_enable_rmw) {
12518 		blknomask = (un->un_phy_blocksize / DEV_BSIZE) - 1;
12519 		secmask = un->un_phy_blocksize - 1;
12520 	} else {
12521 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
12522 		secmask = un->un_tgt_blocksize - 1;
12523 	}
12524 
12525 	if ((bp->b_lblkno & (blknomask)) || (bp->b_bcount & (secmask))) {
12526 		is_aligned = FALSE;
12527 	}
12528 
12529 	if (!(NOT_DEVBSIZE(un)) || un->un_f_enable_rmw) {
12530 		/*
12531 		 * If I/O is aligned, no need to involve RMW(Read Modify Write)
12532 		 * Convert the logical block number to target's physical sector
12533 		 * number.
12534 		 */
12535 		if (is_aligned) {
12536 			xp->xb_blkno = SD_SYS2TGTBLOCK(un, xp->xb_blkno);
12537 		} else {
12538 			/*
12539 			 * There is no RMW if we're just reading, so don't
12540 			 * warn or error out because of it.
12541 			 */
12542 			if (bp->b_flags & B_READ) {
12543 				/*EMPTY*/
12544 			} else if (!un->un_f_enable_rmw &&
12545 			    un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR) {
12546 				bp->b_flags |= B_ERROR;
12547 				goto error_exit;
12548 			} else if (un->un_f_rmw_type == SD_RMW_TYPE_DEFAULT) {
12549 				mutex_enter(SD_MUTEX(un));
12550 				if (!un->un_f_enable_rmw &&
12551 				    un->un_rmw_msg_timeid == NULL) {
12552 					scsi_log(SD_DEVINFO(un), sd_label,
12553 					    CE_WARN, "I/O request is not "
12554 					    "aligned with %d disk sector size. "
12555 					    "It is handled through Read Modify "
12556 					    "Write but the performance is "
12557 					    "very low.\n",
12558 					    un->un_tgt_blocksize);
12559 					un->un_rmw_msg_timeid =
12560 					    timeout(sd_rmw_msg_print_handler,
12561 					    un, SD_RMW_MSG_PRINT_TIMEOUT);
12562 				} else {
12563 					un->un_rmw_incre_count ++;
12564 				}
12565 				mutex_exit(SD_MUTEX(un));
12566 			}
12567 
12568 			nblocks = SD_TGT2SYSBLOCK(un, nblocks);
12569 			partition_offset = SD_TGT2SYSBLOCK(un,
12570 			    partition_offset);
12571 		}
12572 	}
12573 
12574 	/*
12575 	 * blocknum is the starting block number of the request. At this
12576 	 * point it is still relative to the start of the minor device.
12577 	 */
12578 	blocknum = xp->xb_blkno;
12579 
12580 	/*
12581 	 * Legacy: If the starting block number is one past the last block
12582 	 * in the partition, do not set B_ERROR in the buf.
12583 	 */
12584 	if (blocknum == nblocks)  {
12585 		goto error_exit;
12586 	}
12587 
12588 	/*
12589 	 * Confirm that the first block of the request lies within the
12590 	 * partition limits. Also the requested number of bytes must be
12591 	 * a multiple of the system block size.
12592 	 */
12593 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12594 	    ((bp->b_bcount & (DEV_BSIZE - 1)) != 0)) {
12595 		bp->b_flags |= B_ERROR;
12596 		goto error_exit;
12597 	}
12598 
12599 	/*
12600 	 * If the requsted # blocks exceeds the available # blocks, that
12601 	 * is an overrun of the partition.
12602 	 */
12603 	if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12604 		requested_nblocks = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
12605 	} else {
12606 		requested_nblocks = SD_BYTES2SYSBLOCKS(bp->b_bcount);
12607 	}
12608 
12609 	available_nblocks = (size_t)(nblocks - blocknum);
12610 	ASSERT(nblocks >= blocknum);
12611 
12612 	if (requested_nblocks > available_nblocks) {
12613 		size_t resid;
12614 
12615 		/*
12616 		 * Allocate an "overrun" buf to allow the request to proceed
12617 		 * for the amount of space available in the partition. The
12618 		 * amount not transferred will be added into the b_resid
12619 		 * when the operation is complete. The overrun buf
12620 		 * replaces the original buf here, and the original buf
12621 		 * is saved inside the overrun buf, for later use.
12622 		 */
12623 		if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12624 			resid = SD_TGTBLOCKS2BYTES(un,
12625 			    (offset_t)(requested_nblocks - available_nblocks));
12626 		} else {
12627 			resid = SD_SYSBLOCKS2BYTES(
12628 			    (offset_t)(requested_nblocks - available_nblocks));
12629 		}
12630 
12631 		size_t count = bp->b_bcount - resid;
12632 		/*
12633 		 * Note: count is an unsigned entity thus it'll NEVER
12634 		 * be less than 0 so ASSERT the original values are
12635 		 * correct.
12636 		 */
12637 		ASSERT(bp->b_bcount >= resid);
12638 
12639 		bp = sd_bioclone_alloc(bp, count, blocknum,
12640 		    (int (*)(struct buf *))(uintptr_t)sd_mapblockaddr_iodone);
12641 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12642 		ASSERT(xp != NULL);
12643 	}
12644 
12645 	/* At this point there should be no residual for this buf. */
12646 	ASSERT(bp->b_resid == 0);
12647 
12648 	/* Convert the block number to an absolute address. */
12649 	xp->xb_blkno += partition_offset;
12650 
12651 	SD_NEXT_IOSTART(index, un, bp);
12652 
12653 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12654 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12655 
12656 	return;
12657 
12658 error_exit:
12659 	bp->b_resid = bp->b_bcount;
12660 	SD_BEGIN_IODONE(index, un, bp);
12661 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12662 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12663 }
12664 
12665 
12666 /*
12667  *    Function: sd_mapblockaddr_iodone
12668  *
12669  * Description: Completion-side processing for partition management.
12670  *
12671  *     Context: May be called under interrupt context
12672  */
12673 
12674 static void
12675 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12676 {
12677 	/* int	partition; */	/* Not used, see below. */
12678 	ASSERT(un != NULL);
12679 	ASSERT(bp != NULL);
12680 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12681 
12682 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12683 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12684 
12685 	if ((uintptr_t)bp->b_iodone == (uintptr_t)sd_mapblockaddr_iodone) {
12686 		/*
12687 		 * We have an "overrun" buf to deal with...
12688 		 */
12689 		struct sd_xbuf	*xp;
12690 		struct buf	*obp;	/* ptr to the original buf */
12691 
12692 		xp = SD_GET_XBUF(bp);
12693 		ASSERT(xp != NULL);
12694 
12695 		/* Retrieve the pointer to the original buf */
12696 		obp = (struct buf *)xp->xb_private;
12697 		ASSERT(obp != NULL);
12698 
12699 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12700 		bioerror(obp, bp->b_error);
12701 
12702 		sd_bioclone_free(bp);
12703 
12704 		/*
12705 		 * Get back the original buf.
12706 		 * Note that since the restoration of xb_blkno below
12707 		 * was removed, the sd_xbuf is not needed.
12708 		 */
12709 		bp = obp;
12710 		/*
12711 		 * xp = SD_GET_XBUF(bp);
12712 		 * ASSERT(xp != NULL);
12713 		 */
12714 	}
12715 
12716 	/*
12717 	 * Convert sd->xb_blkno back to a minor-device relative value.
12718 	 * Note: this has been commented out, as it is not needed in the
12719 	 * current implementation of the driver (ie, since this function
12720 	 * is at the top of the layering chains, so the info will be
12721 	 * discarded) and it is in the "hot" IO path.
12722 	 *
12723 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12724 	 * xp->xb_blkno -= un->un_offset[partition];
12725 	 */
12726 
12727 	SD_NEXT_IODONE(index, un, bp);
12728 
12729 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12730 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12731 }
12732 
12733 
12734 /*
12735  *    Function: sd_mapblocksize_iostart
12736  *
12737  * Description: Convert between system block size (un->un_sys_blocksize)
12738  *		and target block size (un->un_tgt_blocksize).
12739  *
12740  *     Context: Can sleep to allocate resources.
12741  *
12742  * Assumptions: A higher layer has already performed any partition validation,
12743  *		and converted the xp->xb_blkno to an absolute value relative
12744  *		to the start of the device.
12745  *
12746  *		It is also assumed that the higher layer has implemented
12747  *		an "overrun" mechanism for the case where the request would
12748  *		read/write beyond the end of a partition.  In this case we
12749  *		assume (and ASSERT) that bp->b_resid == 0.
12750  *
12751  *		Note: The implementation for this routine assumes the target
12752  *		block size remains constant between allocation and transport.
12753  */
12754 
12755 static void
12756 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12757 {
12758 	struct sd_mapblocksize_info	*bsp;
12759 	struct sd_xbuf			*xp;
12760 	offset_t first_byte;
12761 	daddr_t	start_block, end_block;
12762 	daddr_t	request_bytes;
12763 	ushort_t is_aligned = FALSE;
12764 
12765 	ASSERT(un != NULL);
12766 	ASSERT(bp != NULL);
12767 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12768 	ASSERT(bp->b_resid == 0);
12769 
12770 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12771 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12772 
12773 	/*
12774 	 * For a non-writable CD, a write request is an error
12775 	 */
12776 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12777 	    (un->un_f_mmc_writable_media == FALSE)) {
12778 		bioerror(bp, EIO);
12779 		bp->b_resid = bp->b_bcount;
12780 		SD_BEGIN_IODONE(index, un, bp);
12781 		return;
12782 	}
12783 
12784 	/*
12785 	 * We do not need a shadow buf if the device is using
12786 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12787 	 * In this case there is no layer-private data block allocated.
12788 	 */
12789 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
12790 	    (bp->b_bcount == 0)) {
12791 		goto done;
12792 	}
12793 
12794 #if defined(__x86)
12795 	/* We do not support non-block-aligned transfers for ROD devices */
12796 	ASSERT(!ISROD(un));
12797 #endif
12798 
12799 	xp = SD_GET_XBUF(bp);
12800 	ASSERT(xp != NULL);
12801 
12802 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12803 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12804 	    un->un_tgt_blocksize, DEV_BSIZE);
12805 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12806 	    "request start block:0x%x\n", xp->xb_blkno);
12807 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12808 	    "request len:0x%x\n", bp->b_bcount);
12809 
12810 	/*
12811 	 * Allocate the layer-private data area for the mapblocksize layer.
12812 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12813 	 * struct to store the pointer to their layer-private data block, but
12814 	 * each layer also has the responsibility of restoring the prior
12815 	 * contents of xb_private before returning the buf/xbuf to the
12816 	 * higher layer that sent it.
12817 	 *
12818 	 * Here we save the prior contents of xp->xb_private into the
12819 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12820 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12821 	 * the layer-private area and returning the buf/xbuf to the layer
12822 	 * that sent it.
12823 	 *
12824 	 * Note that here we use kmem_zalloc for the allocation as there are
12825 	 * parts of the mapblocksize code that expect certain fields to be
12826 	 * zero unless explicitly set to a required value.
12827 	 */
12828 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12829 	bsp->mbs_oprivate = xp->xb_private;
12830 	xp->xb_private = bsp;
12831 
12832 	/*
12833 	 * This treats the data on the disk (target) as an array of bytes.
12834 	 * first_byte is the byte offset, from the beginning of the device,
12835 	 * to the location of the request. This is converted from a
12836 	 * un->un_sys_blocksize block address to a byte offset, and then back
12837 	 * to a block address based upon a un->un_tgt_blocksize block size.
12838 	 *
12839 	 * xp->xb_blkno should be absolute upon entry into this function,
12840 	 * but, but it is based upon partitions that use the "system"
12841 	 * block size. It must be adjusted to reflect the block size of
12842 	 * the target.
12843 	 *
12844 	 * Note that end_block is actually the block that follows the last
12845 	 * block of the request, but that's what is needed for the computation.
12846 	 */
12847 	first_byte  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
12848 	if (un->un_f_enable_rmw) {
12849 		start_block = xp->xb_blkno =
12850 		    (first_byte / un->un_phy_blocksize) *
12851 		    (un->un_phy_blocksize / DEV_BSIZE);
12852 		end_block   = ((first_byte + bp->b_bcount +
12853 		    un->un_phy_blocksize - 1) / un->un_phy_blocksize) *
12854 		    (un->un_phy_blocksize / DEV_BSIZE);
12855 	} else {
12856 		start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
12857 		end_block   = (first_byte + bp->b_bcount +
12858 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
12859 	}
12860 
12861 	/* request_bytes is rounded up to a multiple of the target block size */
12862 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
12863 
12864 	/*
12865 	 * See if the starting address of the request and the request
12866 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
12867 	 * then we do not need to allocate a shadow buf to handle the request.
12868 	 */
12869 	if (un->un_f_enable_rmw) {
12870 		if (((first_byte % un->un_phy_blocksize) == 0) &&
12871 		    ((bp->b_bcount % un->un_phy_blocksize) == 0)) {
12872 			is_aligned = TRUE;
12873 		}
12874 	} else {
12875 		if (((first_byte % un->un_tgt_blocksize) == 0) &&
12876 		    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
12877 			is_aligned = TRUE;
12878 		}
12879 	}
12880 
12881 	if ((bp->b_flags & B_READ) == 0) {
12882 		/*
12883 		 * Lock the range for a write operation. An aligned request is
12884 		 * considered a simple write; otherwise the request must be a
12885 		 * read-modify-write.
12886 		 */
12887 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
12888 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
12889 	}
12890 
12891 	/*
12892 	 * Alloc a shadow buf if the request is not aligned. Also, this is
12893 	 * where the READ command is generated for a read-modify-write. (The
12894 	 * write phase is deferred until after the read completes.)
12895 	 */
12896 	if (is_aligned == FALSE) {
12897 
12898 		struct sd_mapblocksize_info	*shadow_bsp;
12899 		struct sd_xbuf	*shadow_xp;
12900 		struct buf	*shadow_bp;
12901 
12902 		/*
12903 		 * Allocate the shadow buf and it associated xbuf. Note that
12904 		 * after this call the xb_blkno value in both the original
12905 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
12906 		 * same: absolute relative to the start of the device, and
12907 		 * adjusted for the target block size. The b_blkno in the
12908 		 * shadow buf will also be set to this value. We should never
12909 		 * change b_blkno in the original bp however.
12910 		 *
12911 		 * Note also that the shadow buf will always need to be a
12912 		 * READ command, regardless of whether the incoming command
12913 		 * is a READ or a WRITE.
12914 		 */
12915 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
12916 		    xp->xb_blkno,
12917 		    (int (*)(struct buf *))(uintptr_t)sd_mapblocksize_iodone);
12918 
12919 		shadow_xp = SD_GET_XBUF(shadow_bp);
12920 
12921 		/*
12922 		 * Allocate the layer-private data for the shadow buf.
12923 		 * (No need to preserve xb_private in the shadow xbuf.)
12924 		 */
12925 		shadow_xp->xb_private = shadow_bsp =
12926 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12927 
12928 		/*
12929 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
12930 		 * to figure out where the start of the user data is (based upon
12931 		 * the system block size) in the data returned by the READ
12932 		 * command (which will be based upon the target blocksize). Note
12933 		 * that this is only really used if the request is unaligned.
12934 		 */
12935 		if (un->un_f_enable_rmw) {
12936 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
12937 			    ((offset_t)xp->xb_blkno * un->un_sys_blocksize));
12938 			ASSERT((bsp->mbs_copy_offset >= 0) &&
12939 			    (bsp->mbs_copy_offset < un->un_phy_blocksize));
12940 		} else {
12941 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
12942 			    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
12943 			ASSERT((bsp->mbs_copy_offset >= 0) &&
12944 			    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
12945 		}
12946 
12947 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
12948 
12949 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
12950 
12951 		/* Transfer the wmap (if any) to the shadow buf */
12952 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
12953 		bsp->mbs_wmp = NULL;
12954 
12955 		/*
12956 		 * The shadow buf goes on from here in place of the
12957 		 * original buf.
12958 		 */
12959 		shadow_bsp->mbs_orig_bp = bp;
12960 		bp = shadow_bp;
12961 	}
12962 
12963 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12964 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
12965 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12966 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
12967 	    request_bytes);
12968 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12969 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
12970 
12971 done:
12972 	SD_NEXT_IOSTART(index, un, bp);
12973 
12974 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12975 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
12976 }
12977 
12978 
12979 /*
12980  *    Function: sd_mapblocksize_iodone
12981  *
12982  * Description: Completion side processing for block-size mapping.
12983  *
12984  *     Context: May be called under interrupt context
12985  */
12986 
12987 static void
12988 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
12989 {
12990 	struct sd_mapblocksize_info	*bsp;
12991 	struct sd_xbuf	*xp;
12992 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
12993 	struct buf	*orig_bp;	/* ptr to the original buf */
12994 	offset_t	shadow_end;
12995 	offset_t	request_end;
12996 	offset_t	shadow_start;
12997 	ssize_t		copy_offset;
12998 	size_t		copy_length;
12999 	size_t		shortfall;
13000 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
13001 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
13002 
13003 	ASSERT(un != NULL);
13004 	ASSERT(bp != NULL);
13005 
13006 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
13007 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
13008 
13009 	/*
13010 	 * There is no shadow buf or layer-private data if the target is
13011 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
13012 	 */
13013 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
13014 	    (bp->b_bcount == 0)) {
13015 		goto exit;
13016 	}
13017 
13018 	xp = SD_GET_XBUF(bp);
13019 	ASSERT(xp != NULL);
13020 
13021 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
13022 	bsp = xp->xb_private;
13023 
13024 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
13025 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
13026 
13027 	if (is_write) {
13028 		/*
13029 		 * For a WRITE request we must free up the block range that
13030 		 * we have locked up.  This holds regardless of whether this is
13031 		 * an aligned write request or a read-modify-write request.
13032 		 */
13033 		sd_range_unlock(un, bsp->mbs_wmp);
13034 		bsp->mbs_wmp = NULL;
13035 	}
13036 
13037 	if ((uintptr_t)bp->b_iodone != (uintptr_t)sd_mapblocksize_iodone) {
13038 		/*
13039 		 * An aligned read or write command will have no shadow buf;
13040 		 * there is not much else to do with it.
13041 		 */
13042 		goto done;
13043 	}
13044 
13045 	orig_bp = bsp->mbs_orig_bp;
13046 	ASSERT(orig_bp != NULL);
13047 	orig_xp = SD_GET_XBUF(orig_bp);
13048 	ASSERT(orig_xp != NULL);
13049 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13050 
13051 	if (!is_write && has_wmap) {
13052 		/*
13053 		 * A READ with a wmap means this is the READ phase of a
13054 		 * read-modify-write. If an error occurred on the READ then
13055 		 * we do not proceed with the WRITE phase or copy any data.
13056 		 * Just release the write maps and return with an error.
13057 		 */
13058 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
13059 			orig_bp->b_resid = orig_bp->b_bcount;
13060 			bioerror(orig_bp, bp->b_error);
13061 			sd_range_unlock(un, bsp->mbs_wmp);
13062 			goto freebuf_done;
13063 		}
13064 	}
13065 
13066 	/*
13067 	 * Here is where we set up to copy the data from the shadow buf
13068 	 * into the space associated with the original buf.
13069 	 *
13070 	 * To deal with the conversion between block sizes, these
13071 	 * computations treat the data as an array of bytes, with the
13072 	 * first byte (byte 0) corresponding to the first byte in the
13073 	 * first block on the disk.
13074 	 */
13075 
13076 	/*
13077 	 * shadow_start and shadow_len indicate the location and size of
13078 	 * the data returned with the shadow IO request.
13079 	 */
13080 	if (un->un_f_enable_rmw) {
13081 		shadow_start  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
13082 	} else {
13083 		shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
13084 	}
13085 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
13086 
13087 	/*
13088 	 * copy_offset gives the offset (in bytes) from the start of the first
13089 	 * block of the READ request to the beginning of the data.  We retrieve
13090 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
13091 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
13092 	 * data to be copied (in bytes).
13093 	 */
13094 	copy_offset  = bsp->mbs_copy_offset;
13095 	if (un->un_f_enable_rmw) {
13096 		ASSERT((copy_offset >= 0) &&
13097 		    (copy_offset < un->un_phy_blocksize));
13098 	} else {
13099 		ASSERT((copy_offset >= 0) &&
13100 		    (copy_offset < un->un_tgt_blocksize));
13101 	}
13102 
13103 	copy_length  = orig_bp->b_bcount;
13104 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
13105 
13106 	/*
13107 	 * Set up the resid and error fields of orig_bp as appropriate.
13108 	 */
13109 	if (shadow_end >= request_end) {
13110 		/* We got all the requested data; set resid to zero */
13111 		orig_bp->b_resid = 0;
13112 	} else {
13113 		/*
13114 		 * We failed to get enough data to fully satisfy the original
13115 		 * request. Just copy back whatever data we got and set
13116 		 * up the residual and error code as required.
13117 		 *
13118 		 * 'shortfall' is the amount by which the data received with the
13119 		 * shadow buf has "fallen short" of the requested amount.
13120 		 */
13121 		shortfall = (size_t)(request_end - shadow_end);
13122 
13123 		if (shortfall > orig_bp->b_bcount) {
13124 			/*
13125 			 * We did not get enough data to even partially
13126 			 * fulfill the original request.  The residual is
13127 			 * equal to the amount requested.
13128 			 */
13129 			orig_bp->b_resid = orig_bp->b_bcount;
13130 		} else {
13131 			/*
13132 			 * We did not get all the data that we requested
13133 			 * from the device, but we will try to return what
13134 			 * portion we did get.
13135 			 */
13136 			orig_bp->b_resid = shortfall;
13137 		}
13138 		ASSERT(copy_length >= orig_bp->b_resid);
13139 		copy_length  -= orig_bp->b_resid;
13140 	}
13141 
13142 	/* Propagate the error code from the shadow buf to the original buf */
13143 	bioerror(orig_bp, bp->b_error);
13144 
13145 	if (is_write) {
13146 		goto freebuf_done;	/* No data copying for a WRITE */
13147 	}
13148 
13149 	if (has_wmap) {
13150 		/*
13151 		 * This is a READ command from the READ phase of a
13152 		 * read-modify-write request. We have to copy the data given
13153 		 * by the user OVER the data returned by the READ command,
13154 		 * then convert the command from a READ to a WRITE and send
13155 		 * it back to the target.
13156 		 */
13157 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
13158 		    copy_length);
13159 
13160 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
13161 
13162 		/*
13163 		 * Dispatch the WRITE command to the taskq thread, which
13164 		 * will in turn send the command to the target. When the
13165 		 * WRITE command completes, we (sd_mapblocksize_iodone())
13166 		 * will get called again as part of the iodone chain
13167 		 * processing for it. Note that we will still be dealing
13168 		 * with the shadow buf at that point.
13169 		 */
13170 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
13171 		    KM_NOSLEEP) != TASKQID_INVALID) {
13172 			/*
13173 			 * Dispatch was successful so we are done. Return
13174 			 * without going any higher up the iodone chain. Do
13175 			 * not free up any layer-private data until after the
13176 			 * WRITE completes.
13177 			 */
13178 			return;
13179 		}
13180 
13181 		/*
13182 		 * Dispatch of the WRITE command failed; set up the error
13183 		 * condition and send this IO back up the iodone chain.
13184 		 */
13185 		bioerror(orig_bp, EIO);
13186 		orig_bp->b_resid = orig_bp->b_bcount;
13187 
13188 	} else {
13189 		/*
13190 		 * This is a regular READ request (ie, not a RMW). Copy the
13191 		 * data from the shadow buf into the original buf. The
13192 		 * copy_offset compensates for any "misalignment" between the
13193 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
13194 		 * original buf (with its un->un_sys_blocksize blocks).
13195 		 */
13196 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
13197 		    copy_length);
13198 	}
13199 
13200 freebuf_done:
13201 
13202 	/*
13203 	 * At this point we still have both the shadow buf AND the original
13204 	 * buf to deal with, as well as the layer-private data area in each.
13205 	 * Local variables are as follows:
13206 	 *
13207 	 * bp -- points to shadow buf
13208 	 * xp -- points to xbuf of shadow buf
13209 	 * bsp -- points to layer-private data area of shadow buf
13210 	 * orig_bp -- points to original buf
13211 	 *
13212 	 * First free the shadow buf and its associated xbuf, then free the
13213 	 * layer-private data area from the shadow buf. There is no need to
13214 	 * restore xb_private in the shadow xbuf.
13215 	 */
13216 	sd_shadow_buf_free(bp);
13217 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13218 
13219 	/*
13220 	 * Now update the local variables to point to the original buf, xbuf,
13221 	 * and layer-private area.
13222 	 */
13223 	bp = orig_bp;
13224 	xp = SD_GET_XBUF(bp);
13225 	ASSERT(xp != NULL);
13226 	ASSERT(xp == orig_xp);
13227 	bsp = xp->xb_private;
13228 	ASSERT(bsp != NULL);
13229 
13230 done:
13231 	/*
13232 	 * Restore xb_private to whatever it was set to by the next higher
13233 	 * layer in the chain, then free the layer-private data area.
13234 	 */
13235 	xp->xb_private = bsp->mbs_oprivate;
13236 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13237 
13238 exit:
13239 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
13240 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
13241 
13242 	SD_NEXT_IODONE(index, un, bp);
13243 }
13244 
13245 
13246 /*
13247  *    Function: sd_checksum_iostart
13248  *
13249  * Description: A stub function for a layer that's currently not used.
13250  *		For now just a placeholder.
13251  *
13252  *     Context: Kernel thread context
13253  */
13254 
13255 static void
13256 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
13257 {
13258 	ASSERT(un != NULL);
13259 	ASSERT(bp != NULL);
13260 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13261 	SD_NEXT_IOSTART(index, un, bp);
13262 }
13263 
13264 
13265 /*
13266  *    Function: sd_checksum_iodone
13267  *
13268  * Description: A stub function for a layer that's currently not used.
13269  *		For now just a placeholder.
13270  *
13271  *     Context: May be called under interrupt context
13272  */
13273 
13274 static void
13275 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
13276 {
13277 	ASSERT(un != NULL);
13278 	ASSERT(bp != NULL);
13279 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13280 	SD_NEXT_IODONE(index, un, bp);
13281 }
13282 
13283 
13284 /*
13285  *    Function: sd_checksum_uscsi_iostart
13286  *
13287  * Description: A stub function for a layer that's currently not used.
13288  *		For now just a placeholder.
13289  *
13290  *     Context: Kernel thread context
13291  */
13292 
13293 static void
13294 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
13295 {
13296 	ASSERT(un != NULL);
13297 	ASSERT(bp != NULL);
13298 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13299 	SD_NEXT_IOSTART(index, un, bp);
13300 }
13301 
13302 
13303 /*
13304  *    Function: sd_checksum_uscsi_iodone
13305  *
13306  * Description: A stub function for a layer that's currently not used.
13307  *		For now just a placeholder.
13308  *
13309  *     Context: May be called under interrupt context
13310  */
13311 
13312 static void
13313 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
13314 {
13315 	ASSERT(un != NULL);
13316 	ASSERT(bp != NULL);
13317 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13318 	SD_NEXT_IODONE(index, un, bp);
13319 }
13320 
13321 
13322 /*
13323  *    Function: sd_pm_iostart
13324  *
13325  * Description: iostart-side routine for Power mangement.
13326  *
13327  *     Context: Kernel thread context
13328  */
13329 
13330 static void
13331 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
13332 {
13333 	ASSERT(un != NULL);
13334 	ASSERT(bp != NULL);
13335 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13336 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13337 
13338 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
13339 
13340 	if (sd_pm_entry(un) != DDI_SUCCESS) {
13341 		/*
13342 		 * Set up to return the failed buf back up the 'iodone'
13343 		 * side of the calling chain.
13344 		 */
13345 		bioerror(bp, EIO);
13346 		bp->b_resid = bp->b_bcount;
13347 
13348 		SD_BEGIN_IODONE(index, un, bp);
13349 
13350 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13351 		return;
13352 	}
13353 
13354 	SD_NEXT_IOSTART(index, un, bp);
13355 
13356 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13357 }
13358 
13359 
13360 /*
13361  *    Function: sd_pm_iodone
13362  *
13363  * Description: iodone-side routine for power mangement.
13364  *
13365  *     Context: may be called from interrupt context
13366  */
13367 
13368 static void
13369 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
13370 {
13371 	ASSERT(un != NULL);
13372 	ASSERT(bp != NULL);
13373 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13374 
13375 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
13376 
13377 	/*
13378 	 * After attach the following flag is only read, so don't
13379 	 * take the penalty of acquiring a mutex for it.
13380 	 */
13381 	if (un->un_f_pm_is_enabled == TRUE) {
13382 		sd_pm_exit(un);
13383 	}
13384 
13385 	SD_NEXT_IODONE(index, un, bp);
13386 
13387 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
13388 }
13389 
13390 
13391 /*
13392  *    Function: sd_core_iostart
13393  *
13394  * Description: Primary driver function for enqueuing buf(9S) structs from
13395  *		the system and initiating IO to the target device
13396  *
13397  *     Context: Kernel thread context. Can sleep.
13398  *
13399  * Assumptions:  - The given xp->xb_blkno is absolute
13400  *		   (ie, relative to the start of the device).
13401  *		 - The IO is to be done using the native blocksize of
13402  *		   the device, as specified in un->un_tgt_blocksize.
13403  */
13404 /* ARGSUSED */
13405 static void
13406 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
13407 {
13408 	struct sd_xbuf *xp;
13409 
13410 	ASSERT(un != NULL);
13411 	ASSERT(bp != NULL);
13412 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13413 	ASSERT(bp->b_resid == 0);
13414 
13415 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
13416 
13417 	xp = SD_GET_XBUF(bp);
13418 	ASSERT(xp != NULL);
13419 
13420 	mutex_enter(SD_MUTEX(un));
13421 
13422 	/*
13423 	 * If we are currently in the failfast state, fail any new IO
13424 	 * that has B_FAILFAST set, then return.
13425 	 */
13426 	if ((bp->b_flags & B_FAILFAST) &&
13427 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
13428 		mutex_exit(SD_MUTEX(un));
13429 		bioerror(bp, EIO);
13430 		bp->b_resid = bp->b_bcount;
13431 		SD_BEGIN_IODONE(index, un, bp);
13432 		return;
13433 	}
13434 
13435 	if (SD_IS_DIRECT_PRIORITY(xp)) {
13436 		/*
13437 		 * Priority command -- transport it immediately.
13438 		 *
13439 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
13440 		 * because all direct priority commands should be associated
13441 		 * with error recovery actions which we don't want to retry.
13442 		 */
13443 		sd_start_cmds(un, bp);
13444 	} else {
13445 		/*
13446 		 * Normal command -- add it to the wait queue, then start
13447 		 * transporting commands from the wait queue.
13448 		 */
13449 		sd_add_buf_to_waitq(un, bp);
13450 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13451 		sd_start_cmds(un, NULL);
13452 	}
13453 
13454 	mutex_exit(SD_MUTEX(un));
13455 
13456 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
13457 }
13458 
13459 
13460 /*
13461  *    Function: sd_init_cdb_limits
13462  *
13463  * Description: This is to handle scsi_pkt initialization differences
13464  *		between the driver platforms.
13465  *
13466  *		Legacy behaviors:
13467  *
13468  *		If the block number or the sector count exceeds the
13469  *		capabilities of a Group 0 command, shift over to a
13470  *		Group 1 command. We don't blindly use Group 1
13471  *		commands because a) some drives (CDC Wren IVs) get a
13472  *		bit confused, and b) there is probably a fair amount
13473  *		of speed difference for a target to receive and decode
13474  *		a 10 byte command instead of a 6 byte command.
13475  *
13476  *		The xfer time difference of 6 vs 10 byte CDBs is
13477  *		still significant so this code is still worthwhile.
13478  *		10 byte CDBs are very inefficient with the fas HBA driver
13479  *		and older disks. Each CDB byte took 1 usec with some
13480  *		popular disks.
13481  *
13482  *     Context: Must be called at attach time
13483  */
13484 
13485 static void
13486 sd_init_cdb_limits(struct sd_lun *un)
13487 {
13488 	int hba_cdb_limit;
13489 
13490 	/*
13491 	 * Use CDB_GROUP1 commands for most devices except for
13492 	 * parallel SCSI fixed drives in which case we get better
13493 	 * performance using CDB_GROUP0 commands (where applicable).
13494 	 */
13495 	un->un_mincdb = SD_CDB_GROUP1;
13496 #if !defined(__fibre)
13497 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
13498 	    !un->un_f_has_removable_media) {
13499 		un->un_mincdb = SD_CDB_GROUP0;
13500 	}
13501 #endif
13502 
13503 	/*
13504 	 * Try to read the max-cdb-length supported by HBA.
13505 	 */
13506 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
13507 	if (0 >= un->un_max_hba_cdb) {
13508 		un->un_max_hba_cdb = CDB_GROUP4;
13509 		hba_cdb_limit = SD_CDB_GROUP4;
13510 	} else if (0 < un->un_max_hba_cdb &&
13511 	    un->un_max_hba_cdb < CDB_GROUP1) {
13512 		hba_cdb_limit = SD_CDB_GROUP0;
13513 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
13514 	    un->un_max_hba_cdb < CDB_GROUP5) {
13515 		hba_cdb_limit = SD_CDB_GROUP1;
13516 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
13517 	    un->un_max_hba_cdb < CDB_GROUP4) {
13518 		hba_cdb_limit = SD_CDB_GROUP5;
13519 	} else {
13520 		hba_cdb_limit = SD_CDB_GROUP4;
13521 	}
13522 
13523 	/*
13524 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
13525 	 * commands for fixed disks unless we are building for a 32 bit
13526 	 * kernel.
13527 	 */
13528 #ifdef _LP64
13529 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13530 	    min(hba_cdb_limit, SD_CDB_GROUP4);
13531 #else
13532 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13533 	    min(hba_cdb_limit, SD_CDB_GROUP1);
13534 #endif
13535 
13536 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
13537 	    ? sizeof (struct scsi_arq_status) : 1);
13538 	if (!ISCD(un))
13539 		un->un_cmd_timeout = (ushort_t)sd_io_time;
13540 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
13541 }
13542 
13543 
13544 /*
13545  *    Function: sd_initpkt_for_buf
13546  *
13547  * Description: Allocate and initialize for transport a scsi_pkt struct,
13548  *		based upon the info specified in the given buf struct.
13549  *
13550  *		Assumes the xb_blkno in the request is absolute (ie,
13551  *		relative to the start of the device (NOT partition!).
13552  *		Also assumes that the request is using the native block
13553  *		size of the device (as returned by the READ CAPACITY
13554  *		command).
13555  *
13556  * Return Code: SD_PKT_ALLOC_SUCCESS
13557  *		SD_PKT_ALLOC_FAILURE
13558  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13559  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13560  *
13561  *     Context: Kernel thread and may be called from software interrupt context
13562  *		as part of a sdrunout callback. This function may not block or
13563  *		call routines that block
13564  */
13565 
13566 static int
13567 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
13568 {
13569 	struct sd_xbuf	*xp;
13570 	struct scsi_pkt *pktp = NULL;
13571 	struct sd_lun	*un;
13572 	size_t		blockcount;
13573 	daddr_t		startblock;
13574 	int		rval;
13575 	int		cmd_flags;
13576 
13577 	ASSERT(bp != NULL);
13578 	ASSERT(pktpp != NULL);
13579 	xp = SD_GET_XBUF(bp);
13580 	ASSERT(xp != NULL);
13581 	un = SD_GET_UN(bp);
13582 	ASSERT(un != NULL);
13583 	ASSERT(mutex_owned(SD_MUTEX(un)));
13584 	ASSERT(bp->b_resid == 0);
13585 
13586 	SD_TRACE(SD_LOG_IO_CORE, un,
13587 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13588 
13589 	mutex_exit(SD_MUTEX(un));
13590 
13591 #if defined(__x86)	/* DMAFREE for x86 only */
13592 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13593 		/*
13594 		 * Already have a scsi_pkt -- just need DMA resources.
13595 		 * We must recompute the CDB in case the mapping returns
13596 		 * a nonzero pkt_resid.
13597 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13598 		 * that is being retried, the unmap/remap of the DMA resouces
13599 		 * will result in the entire transfer starting over again
13600 		 * from the very first block.
13601 		 */
13602 		ASSERT(xp->xb_pktp != NULL);
13603 		pktp = xp->xb_pktp;
13604 	} else {
13605 		pktp = NULL;
13606 	}
13607 #endif /* __x86 */
13608 
13609 	startblock = xp->xb_blkno;	/* Absolute block num. */
13610 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13611 
13612 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13613 
13614 	/*
13615 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13616 	 * call scsi_init_pkt, and build the CDB.
13617 	 */
13618 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13619 	    cmd_flags, sdrunout, (caddr_t)un,
13620 	    startblock, blockcount);
13621 
13622 	if (rval == 0) {
13623 		/*
13624 		 * Success.
13625 		 *
13626 		 * If partial DMA is being used and required for this transfer.
13627 		 * set it up here.
13628 		 */
13629 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13630 		    (pktp->pkt_resid != 0)) {
13631 
13632 			/*
13633 			 * Save the CDB length and pkt_resid for the
13634 			 * next xfer
13635 			 */
13636 			xp->xb_dma_resid = pktp->pkt_resid;
13637 
13638 			/* rezero resid */
13639 			pktp->pkt_resid = 0;
13640 
13641 		} else {
13642 			xp->xb_dma_resid = 0;
13643 		}
13644 
13645 		pktp->pkt_flags = un->un_tagflags;
13646 		pktp->pkt_time  = un->un_cmd_timeout;
13647 		pktp->pkt_comp  = sdintr;
13648 
13649 		pktp->pkt_private = bp;
13650 		*pktpp = pktp;
13651 
13652 		SD_TRACE(SD_LOG_IO_CORE, un,
13653 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13654 
13655 #if defined(__x86)	/* DMAFREE for x86 only */
13656 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13657 #endif
13658 
13659 		mutex_enter(SD_MUTEX(un));
13660 		return (SD_PKT_ALLOC_SUCCESS);
13661 
13662 	}
13663 
13664 	/*
13665 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13666 	 * from sd_setup_rw_pkt.
13667 	 */
13668 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13669 
13670 	if (rval == SD_PKT_ALLOC_FAILURE) {
13671 		*pktpp = NULL;
13672 		/*
13673 		 * Set the driver state to RWAIT to indicate the driver
13674 		 * is waiting on resource allocations. The driver will not
13675 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13676 		 */
13677 		mutex_enter(SD_MUTEX(un));
13678 		New_state(un, SD_STATE_RWAIT);
13679 
13680 		SD_ERROR(SD_LOG_IO_CORE, un,
13681 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13682 
13683 		if ((bp->b_flags & B_ERROR) != 0) {
13684 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13685 		}
13686 		return (SD_PKT_ALLOC_FAILURE);
13687 	} else {
13688 		/*
13689 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13690 		 *
13691 		 * This should never happen.  Maybe someone messed with the
13692 		 * kernel's minphys?
13693 		 */
13694 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13695 		    "Request rejected: too large for CDB: "
13696 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13697 		SD_ERROR(SD_LOG_IO_CORE, un,
13698 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13699 		mutex_enter(SD_MUTEX(un));
13700 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13701 
13702 	}
13703 }
13704 
13705 
13706 /*
13707  *    Function: sd_destroypkt_for_buf
13708  *
13709  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13710  *
13711  *     Context: Kernel thread or interrupt context
13712  */
13713 
13714 static void
13715 sd_destroypkt_for_buf(struct buf *bp)
13716 {
13717 	ASSERT(bp != NULL);
13718 	ASSERT(SD_GET_UN(bp) != NULL);
13719 
13720 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13721 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13722 
13723 	ASSERT(SD_GET_PKTP(bp) != NULL);
13724 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13725 
13726 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13727 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13728 }
13729 
13730 /*
13731  *    Function: sd_setup_rw_pkt
13732  *
13733  * Description: Determines appropriate CDB group for the requested LBA
13734  *		and transfer length, calls scsi_init_pkt, and builds
13735  *		the CDB.  Do not use for partial DMA transfers except
13736  *		for the initial transfer since the CDB size must
13737  *		remain constant.
13738  *
13739  *     Context: Kernel thread and may be called from software interrupt
13740  *		context as part of a sdrunout callback. This function may not
13741  *		block or call routines that block
13742  */
13743 
13744 
13745 int
13746 sd_setup_rw_pkt(struct sd_lun *un,
13747     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13748     int (*callback)(caddr_t), caddr_t callback_arg,
13749     diskaddr_t lba, uint32_t blockcount)
13750 {
13751 	struct scsi_pkt *return_pktp;
13752 	union scsi_cdb *cdbp;
13753 	struct sd_cdbinfo *cp = NULL;
13754 	int i;
13755 
13756 	/*
13757 	 * See which size CDB to use, based upon the request.
13758 	 */
13759 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13760 
13761 		/*
13762 		 * Check lba and block count against sd_cdbtab limits.
13763 		 * In the partial DMA case, we have to use the same size
13764 		 * CDB for all the transfers.  Check lba + blockcount
13765 		 * against the max LBA so we know that segment of the
13766 		 * transfer can use the CDB we select.
13767 		 */
13768 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13769 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13770 
13771 			/*
13772 			 * The command will fit into the CDB type
13773 			 * specified by sd_cdbtab[i].
13774 			 */
13775 			cp = sd_cdbtab + i;
13776 
13777 			/*
13778 			 * Call scsi_init_pkt so we can fill in the
13779 			 * CDB.
13780 			 */
13781 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13782 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13783 			    flags, callback, callback_arg);
13784 
13785 			if (return_pktp != NULL) {
13786 
13787 				/*
13788 				 * Return new value of pkt
13789 				 */
13790 				*pktpp = return_pktp;
13791 
13792 				/*
13793 				 * To be safe, zero the CDB insuring there is
13794 				 * no leftover data from a previous command.
13795 				 */
13796 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13797 
13798 				/*
13799 				 * Handle partial DMA mapping
13800 				 */
13801 				if (return_pktp->pkt_resid != 0) {
13802 
13803 					/*
13804 					 * Not going to xfer as many blocks as
13805 					 * originally expected
13806 					 */
13807 					blockcount -=
13808 					    SD_BYTES2TGTBLOCKS(un,
13809 					    return_pktp->pkt_resid);
13810 				}
13811 
13812 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13813 
13814 				/*
13815 				 * Set command byte based on the CDB
13816 				 * type we matched.
13817 				 */
13818 				cdbp->scc_cmd = cp->sc_grpmask |
13819 				    ((bp->b_flags & B_READ) ?
13820 				    SCMD_READ : SCMD_WRITE);
13821 
13822 				SD_FILL_SCSI1_LUN(un, return_pktp);
13823 
13824 				/*
13825 				 * Fill in LBA and length
13826 				 */
13827 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13828 				    (cp->sc_grpcode == CDB_GROUP4) ||
13829 				    (cp->sc_grpcode == CDB_GROUP0) ||
13830 				    (cp->sc_grpcode == CDB_GROUP5));
13831 
13832 				if (cp->sc_grpcode == CDB_GROUP1) {
13833 					FORMG1ADDR(cdbp, lba);
13834 					FORMG1COUNT(cdbp, blockcount);
13835 					return (0);
13836 				} else if (cp->sc_grpcode == CDB_GROUP4) {
13837 					FORMG4LONGADDR(cdbp, lba);
13838 					FORMG4COUNT(cdbp, blockcount);
13839 					return (0);
13840 				} else if (cp->sc_grpcode == CDB_GROUP0) {
13841 					FORMG0ADDR(cdbp, lba);
13842 					FORMG0COUNT(cdbp, blockcount);
13843 					return (0);
13844 				} else if (cp->sc_grpcode == CDB_GROUP5) {
13845 					FORMG5ADDR(cdbp, lba);
13846 					FORMG5COUNT(cdbp, blockcount);
13847 					return (0);
13848 				}
13849 
13850 				/*
13851 				 * It should be impossible to not match one
13852 				 * of the CDB types above, so we should never
13853 				 * reach this point.  Set the CDB command byte
13854 				 * to test-unit-ready to avoid writing
13855 				 * to somewhere we don't intend.
13856 				 */
13857 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
13858 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13859 			} else {
13860 				/*
13861 				 * Couldn't get scsi_pkt
13862 				 */
13863 				return (SD_PKT_ALLOC_FAILURE);
13864 			}
13865 		}
13866 	}
13867 
13868 	/*
13869 	 * None of the available CDB types were suitable.  This really
13870 	 * should never happen:  on a 64 bit system we support
13871 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
13872 	 * and on a 32 bit system we will refuse to bind to a device
13873 	 * larger than 2TB so addresses will never be larger than 32 bits.
13874 	 */
13875 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13876 }
13877 
13878 /*
13879  *    Function: sd_setup_next_rw_pkt
13880  *
13881  * Description: Setup packet for partial DMA transfers, except for the
13882  *		initial transfer.  sd_setup_rw_pkt should be used for
13883  *		the initial transfer.
13884  *
13885  *     Context: Kernel thread and may be called from interrupt context.
13886  */
13887 
13888 int
13889 sd_setup_next_rw_pkt(struct sd_lun *un,
13890     struct scsi_pkt *pktp, struct buf *bp,
13891     diskaddr_t lba, uint32_t blockcount)
13892 {
13893 	uchar_t com;
13894 	union scsi_cdb *cdbp;
13895 	uchar_t cdb_group_id;
13896 
13897 	ASSERT(pktp != NULL);
13898 	ASSERT(pktp->pkt_cdbp != NULL);
13899 
13900 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
13901 	com = cdbp->scc_cmd;
13902 	cdb_group_id = CDB_GROUPID(com);
13903 
13904 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
13905 	    (cdb_group_id == CDB_GROUPID_1) ||
13906 	    (cdb_group_id == CDB_GROUPID_4) ||
13907 	    (cdb_group_id == CDB_GROUPID_5));
13908 
13909 	/*
13910 	 * Move pkt to the next portion of the xfer.
13911 	 * func is NULL_FUNC so we do not have to release
13912 	 * the disk mutex here.
13913 	 */
13914 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
13915 	    NULL_FUNC, NULL) == pktp) {
13916 		/* Success.  Handle partial DMA */
13917 		if (pktp->pkt_resid != 0) {
13918 			blockcount -=
13919 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
13920 		}
13921 
13922 		cdbp->scc_cmd = com;
13923 		SD_FILL_SCSI1_LUN(un, pktp);
13924 		if (cdb_group_id == CDB_GROUPID_1) {
13925 			FORMG1ADDR(cdbp, lba);
13926 			FORMG1COUNT(cdbp, blockcount);
13927 			return (0);
13928 		} else if (cdb_group_id == CDB_GROUPID_4) {
13929 			FORMG4LONGADDR(cdbp, lba);
13930 			FORMG4COUNT(cdbp, blockcount);
13931 			return (0);
13932 		} else if (cdb_group_id == CDB_GROUPID_0) {
13933 			FORMG0ADDR(cdbp, lba);
13934 			FORMG0COUNT(cdbp, blockcount);
13935 			return (0);
13936 		} else if (cdb_group_id == CDB_GROUPID_5) {
13937 			FORMG5ADDR(cdbp, lba);
13938 			FORMG5COUNT(cdbp, blockcount);
13939 			return (0);
13940 		}
13941 
13942 		/* Unreachable */
13943 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13944 	}
13945 
13946 	/*
13947 	 * Error setting up next portion of cmd transfer.
13948 	 * Something is definitely very wrong and this
13949 	 * should not happen.
13950 	 */
13951 	return (SD_PKT_ALLOC_FAILURE);
13952 }
13953 
13954 /*
13955  *    Function: sd_initpkt_for_uscsi
13956  *
13957  * Description: Allocate and initialize for transport a scsi_pkt struct,
13958  *		based upon the info specified in the given uscsi_cmd struct.
13959  *
13960  * Return Code: SD_PKT_ALLOC_SUCCESS
13961  *		SD_PKT_ALLOC_FAILURE
13962  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13963  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13964  *
13965  *     Context: Kernel thread and may be called from software interrupt context
13966  *		as part of a sdrunout callback. This function may not block or
13967  *		call routines that block
13968  */
13969 
13970 static int
13971 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
13972 {
13973 	struct uscsi_cmd *uscmd;
13974 	struct sd_xbuf	*xp;
13975 	struct scsi_pkt	*pktp;
13976 	struct sd_lun	*un;
13977 	uint32_t	flags = 0;
13978 
13979 	ASSERT(bp != NULL);
13980 	ASSERT(pktpp != NULL);
13981 	xp = SD_GET_XBUF(bp);
13982 	ASSERT(xp != NULL);
13983 	un = SD_GET_UN(bp);
13984 	ASSERT(un != NULL);
13985 	ASSERT(mutex_owned(SD_MUTEX(un)));
13986 
13987 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13988 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13989 	ASSERT(uscmd != NULL);
13990 
13991 	SD_TRACE(SD_LOG_IO_CORE, un,
13992 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
13993 
13994 	/*
13995 	 * Allocate the scsi_pkt for the command.
13996 	 *
13997 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
13998 	 *	 during scsi_init_pkt time and will continue to use the
13999 	 *	 same path as long as the same scsi_pkt is used without
14000 	 *	 intervening scsi_dmafree(). Since uscsi command does
14001 	 *	 not call scsi_dmafree() before retry failed command, it
14002 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
14003 	 *	 set such that scsi_vhci can use other available path for
14004 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
14005 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
14006 	 *
14007 	 *	 More fundamentally, we can't support breaking up this DMA into
14008 	 *	 multiple windows on x86. There is, in general, no guarantee
14009 	 *	 that arbitrary SCSI commands are idempotent, which is required
14010 	 *	 if we want to use multiple windows for a given command.
14011 	 */
14012 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14013 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
14014 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
14015 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
14016 		    - sizeof (struct scsi_extended_sense)), 0,
14017 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
14018 		    sdrunout, (caddr_t)un);
14019 	} else {
14020 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
14021 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
14022 		    sizeof (struct scsi_arq_status), 0,
14023 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
14024 		    sdrunout, (caddr_t)un);
14025 	}
14026 
14027 	if (pktp == NULL) {
14028 		*pktpp = NULL;
14029 		/*
14030 		 * Set the driver state to RWAIT to indicate the driver
14031 		 * is waiting on resource allocations. The driver will not
14032 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
14033 		 */
14034 		New_state(un, SD_STATE_RWAIT);
14035 
14036 		SD_ERROR(SD_LOG_IO_CORE, un,
14037 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
14038 
14039 		if ((bp->b_flags & B_ERROR) != 0) {
14040 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
14041 		}
14042 		return (SD_PKT_ALLOC_FAILURE);
14043 	}
14044 
14045 	/*
14046 	 * We do not do DMA breakup for USCSI commands, so return failure
14047 	 * here if all the needed DMA resources were not allocated.
14048 	 */
14049 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
14050 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
14051 		scsi_destroy_pkt(pktp);
14052 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
14053 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
14054 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
14055 	}
14056 
14057 	/* Init the cdb from the given uscsi struct */
14058 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
14059 	    uscmd->uscsi_cdb[0], 0, 0, 0);
14060 
14061 	SD_FILL_SCSI1_LUN(un, pktp);
14062 
14063 	/*
14064 	 * Set up the optional USCSI flags. See the uscsi(4I) man page
14065 	 * for listing of the supported flags.
14066 	 */
14067 
14068 	if (uscmd->uscsi_flags & USCSI_SILENT) {
14069 		flags |= FLAG_SILENT;
14070 	}
14071 
14072 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
14073 		flags |= FLAG_DIAGNOSE;
14074 	}
14075 
14076 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
14077 		flags |= FLAG_ISOLATE;
14078 	}
14079 
14080 	if (un->un_f_is_fibre == FALSE) {
14081 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
14082 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
14083 		}
14084 	}
14085 
14086 	/*
14087 	 * Set the pkt flags here so we save time later.
14088 	 * Note: These flags are NOT in the uscsi man page!!!
14089 	 */
14090 	if (uscmd->uscsi_flags & USCSI_HEAD) {
14091 		flags |= FLAG_HEAD;
14092 	}
14093 
14094 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
14095 		flags |= FLAG_NOINTR;
14096 	}
14097 
14098 	/*
14099 	 * For tagged queueing, things get a bit complicated.
14100 	 * Check first for head of queue and last for ordered queue.
14101 	 * If neither head nor order, use the default driver tag flags.
14102 	 */
14103 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
14104 		if (uscmd->uscsi_flags & USCSI_HTAG) {
14105 			flags |= FLAG_HTAG;
14106 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
14107 			flags |= FLAG_OTAG;
14108 		} else {
14109 			flags |= un->un_tagflags & FLAG_TAGMASK;
14110 		}
14111 	}
14112 
14113 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
14114 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
14115 	}
14116 
14117 	pktp->pkt_flags = flags;
14118 
14119 	/* Transfer uscsi information to scsi_pkt */
14120 	(void) scsi_uscsi_pktinit(uscmd, pktp);
14121 
14122 	/* Copy the caller's CDB into the pkt... */
14123 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
14124 
14125 	if (uscmd->uscsi_timeout == 0) {
14126 		pktp->pkt_time = un->un_uscsi_timeout;
14127 	} else {
14128 		pktp->pkt_time = uscmd->uscsi_timeout;
14129 	}
14130 
14131 	/* need it later to identify USCSI request in sdintr */
14132 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
14133 
14134 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
14135 
14136 	pktp->pkt_private = bp;
14137 	pktp->pkt_comp = sdintr;
14138 	*pktpp = pktp;
14139 
14140 	SD_TRACE(SD_LOG_IO_CORE, un,
14141 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
14142 
14143 	return (SD_PKT_ALLOC_SUCCESS);
14144 }
14145 
14146 
14147 /*
14148  *    Function: sd_destroypkt_for_uscsi
14149  *
14150  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
14151  *		IOs.. Also saves relevant info into the associated uscsi_cmd
14152  *		struct.
14153  *
14154  *     Context: May be called under interrupt context
14155  */
14156 
14157 static void
14158 sd_destroypkt_for_uscsi(struct buf *bp)
14159 {
14160 	struct uscsi_cmd *uscmd;
14161 	struct sd_xbuf	*xp;
14162 	struct scsi_pkt	*pktp;
14163 	struct sd_lun	*un;
14164 	struct sd_uscsi_info *suip;
14165 
14166 	ASSERT(bp != NULL);
14167 	xp = SD_GET_XBUF(bp);
14168 	ASSERT(xp != NULL);
14169 	un = SD_GET_UN(bp);
14170 	ASSERT(un != NULL);
14171 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14172 	pktp = SD_GET_PKTP(bp);
14173 	ASSERT(pktp != NULL);
14174 
14175 	SD_TRACE(SD_LOG_IO_CORE, un,
14176 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
14177 
14178 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14179 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14180 	ASSERT(uscmd != NULL);
14181 
14182 	/* Save the status and the residual into the uscsi_cmd struct */
14183 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
14184 	uscmd->uscsi_resid  = bp->b_resid;
14185 
14186 	/* Transfer scsi_pkt information to uscsi */
14187 	(void) scsi_uscsi_pktfini(pktp, uscmd);
14188 
14189 	/*
14190 	 * If enabled, copy any saved sense data into the area specified
14191 	 * by the uscsi command.
14192 	 */
14193 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
14194 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
14195 		/*
14196 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
14197 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
14198 		 */
14199 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
14200 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
14201 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14202 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14203 			    MAX_SENSE_LENGTH);
14204 		} else {
14205 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14206 			    SENSE_LENGTH);
14207 		}
14208 	}
14209 	/*
14210 	 * The following assignments are for SCSI FMA.
14211 	 */
14212 	ASSERT(xp->xb_private != NULL);
14213 	suip = (struct sd_uscsi_info *)xp->xb_private;
14214 	suip->ui_pkt_reason = pktp->pkt_reason;
14215 	suip->ui_pkt_state = pktp->pkt_state;
14216 	suip->ui_pkt_statistics = pktp->pkt_statistics;
14217 	suip->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
14218 
14219 	/* We are done with the scsi_pkt; free it now */
14220 	ASSERT(SD_GET_PKTP(bp) != NULL);
14221 	scsi_destroy_pkt(SD_GET_PKTP(bp));
14222 
14223 	SD_TRACE(SD_LOG_IO_CORE, un,
14224 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
14225 }
14226 
14227 
14228 /*
14229  *    Function: sd_bioclone_alloc
14230  *
14231  * Description: Allocate a buf(9S) and init it as per the given buf
14232  *		and the various arguments.  The associated sd_xbuf
14233  *		struct is (nearly) duplicated.  The struct buf *bp
14234  *		argument is saved in new_xp->xb_private.
14235  *
14236  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14237  *		datalen - size of data area for the shadow bp
14238  *		blkno - starting LBA
14239  *		func - function pointer for b_iodone in the shadow buf. (May
14240  *			be NULL if none.)
14241  *
14242  * Return Code: Pointer to allocates buf(9S) struct
14243  *
14244  *     Context: Can sleep.
14245  */
14246 
14247 static struct buf *
14248 sd_bioclone_alloc(struct buf *bp, size_t datalen, daddr_t blkno,
14249     int (*func)(struct buf *))
14250 {
14251 	struct	sd_lun	*un;
14252 	struct	sd_xbuf	*xp;
14253 	struct	sd_xbuf	*new_xp;
14254 	struct	buf	*new_bp;
14255 
14256 	ASSERT(bp != NULL);
14257 	xp = SD_GET_XBUF(bp);
14258 	ASSERT(xp != NULL);
14259 	un = SD_GET_UN(bp);
14260 	ASSERT(un != NULL);
14261 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14262 
14263 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
14264 	    NULL, KM_SLEEP);
14265 
14266 	new_bp->b_lblkno	= blkno;
14267 
14268 	/*
14269 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14270 	 * original xbuf into it.
14271 	 */
14272 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14273 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14274 
14275 	/*
14276 	 * The given bp is automatically saved in the xb_private member
14277 	 * of the new xbuf.  Callers are allowed to depend on this.
14278 	 */
14279 	new_xp->xb_private = bp;
14280 
14281 	new_bp->b_private  = new_xp;
14282 
14283 	return (new_bp);
14284 }
14285 
14286 /*
14287  *    Function: sd_shadow_buf_alloc
14288  *
14289  * Description: Allocate a buf(9S) and init it as per the given buf
14290  *		and the various arguments.  The associated sd_xbuf
14291  *		struct is (nearly) duplicated.  The struct buf *bp
14292  *		argument is saved in new_xp->xb_private.
14293  *
14294  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14295  *		datalen - size of data area for the shadow bp
14296  *		bflags - B_READ or B_WRITE (pseudo flag)
14297  *		blkno - starting LBA
14298  *		func - function pointer for b_iodone in the shadow buf. (May
14299  *			be NULL if none.)
14300  *
14301  * Return Code: Pointer to allocates buf(9S) struct
14302  *
14303  *     Context: Can sleep.
14304  */
14305 
14306 static struct buf *
14307 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
14308     daddr_t blkno, int (*func)(struct buf *))
14309 {
14310 	struct	sd_lun	*un;
14311 	struct	sd_xbuf	*xp;
14312 	struct	sd_xbuf	*new_xp;
14313 	struct	buf	*new_bp;
14314 
14315 	ASSERT(bp != NULL);
14316 	xp = SD_GET_XBUF(bp);
14317 	ASSERT(xp != NULL);
14318 	un = SD_GET_UN(bp);
14319 	ASSERT(un != NULL);
14320 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14321 
14322 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
14323 		bp_mapin(bp);
14324 	}
14325 
14326 	bflags &= (B_READ | B_WRITE);
14327 #if defined(__x86)
14328 	new_bp = getrbuf(KM_SLEEP);
14329 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
14330 	new_bp->b_bcount = datalen;
14331 	new_bp->b_flags = bflags |
14332 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
14333 #else
14334 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
14335 	    datalen, bflags, SLEEP_FUNC, NULL);
14336 #endif
14337 	new_bp->av_forw	= NULL;
14338 	new_bp->av_back	= NULL;
14339 	new_bp->b_dev	= bp->b_dev;
14340 	new_bp->b_blkno	= blkno;
14341 	new_bp->b_iodone = func;
14342 	new_bp->b_edev	= bp->b_edev;
14343 	new_bp->b_resid	= 0;
14344 
14345 	/* We need to preserve the B_FAILFAST flag */
14346 	if (bp->b_flags & B_FAILFAST) {
14347 		new_bp->b_flags |= B_FAILFAST;
14348 	}
14349 
14350 	/*
14351 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14352 	 * original xbuf into it.
14353 	 */
14354 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14355 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14356 
14357 	/* Need later to copy data between the shadow buf & original buf! */
14358 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
14359 
14360 	/*
14361 	 * The given bp is automatically saved in the xb_private member
14362 	 * of the new xbuf.  Callers are allowed to depend on this.
14363 	 */
14364 	new_xp->xb_private = bp;
14365 
14366 	new_bp->b_private  = new_xp;
14367 
14368 	return (new_bp);
14369 }
14370 
14371 /*
14372  *    Function: sd_bioclone_free
14373  *
14374  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
14375  *		in the larger than partition operation.
14376  *
14377  *     Context: May be called under interrupt context
14378  */
14379 
14380 static void
14381 sd_bioclone_free(struct buf *bp)
14382 {
14383 	struct sd_xbuf	*xp;
14384 
14385 	ASSERT(bp != NULL);
14386 	xp = SD_GET_XBUF(bp);
14387 	ASSERT(xp != NULL);
14388 
14389 	/*
14390 	 * Call bp_mapout() before freeing the buf,  in case a lower
14391 	 * layer or HBA  had done a bp_mapin().  we must do this here
14392 	 * as we are the "originator" of the shadow buf.
14393 	 */
14394 	bp_mapout(bp);
14395 
14396 	/*
14397 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14398 	 * never gets confused by a stale value in this field. (Just a little
14399 	 * extra defensiveness here.)
14400 	 */
14401 	bp->b_iodone = NULL;
14402 
14403 	freerbuf(bp);
14404 
14405 	kmem_free(xp, sizeof (struct sd_xbuf));
14406 }
14407 
14408 /*
14409  *    Function: sd_shadow_buf_free
14410  *
14411  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
14412  *
14413  *     Context: May be called under interrupt context
14414  */
14415 
14416 static void
14417 sd_shadow_buf_free(struct buf *bp)
14418 {
14419 	struct sd_xbuf	*xp;
14420 
14421 	ASSERT(bp != NULL);
14422 	xp = SD_GET_XBUF(bp);
14423 	ASSERT(xp != NULL);
14424 
14425 #if defined(__sparc)
14426 	/*
14427 	 * Call bp_mapout() before freeing the buf,  in case a lower
14428 	 * layer or HBA  had done a bp_mapin().  we must do this here
14429 	 * as we are the "originator" of the shadow buf.
14430 	 */
14431 	bp_mapout(bp);
14432 #endif
14433 
14434 	/*
14435 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14436 	 * never gets confused by a stale value in this field. (Just a little
14437 	 * extra defensiveness here.)
14438 	 */
14439 	bp->b_iodone = NULL;
14440 
14441 #if defined(__x86)
14442 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
14443 	freerbuf(bp);
14444 #else
14445 	scsi_free_consistent_buf(bp);
14446 #endif
14447 
14448 	kmem_free(xp, sizeof (struct sd_xbuf));
14449 }
14450 
14451 
14452 /*
14453  *    Function: sd_print_transport_rejected_message
14454  *
14455  * Description: This implements the ludicrously complex rules for printing
14456  *		a "transport rejected" message.  This is to address the
14457  *		specific problem of having a flood of this error message
14458  *		produced when a failover occurs.
14459  *
14460  *     Context: Any.
14461  */
14462 
14463 static void
14464 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
14465     int code)
14466 {
14467 	ASSERT(un != NULL);
14468 	ASSERT(mutex_owned(SD_MUTEX(un)));
14469 	ASSERT(xp != NULL);
14470 
14471 	/*
14472 	 * Print the "transport rejected" message under the following
14473 	 * conditions:
14474 	 *
14475 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
14476 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
14477 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
14478 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
14479 	 *   scsi_transport(9F) (which indicates that the target might have
14480 	 *   gone off-line).  This uses the un->un_tran_fatal_count
14481 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
14482 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
14483 	 *   from scsi_transport().
14484 	 *
14485 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
14486 	 * the preceeding cases in order for the message to be printed.
14487 	 */
14488 	if (((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) &&
14489 	    (SD_FM_LOG(un) == SD_FM_LOG_NSUP)) {
14490 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
14491 		    (code != TRAN_FATAL_ERROR) ||
14492 		    (un->un_tran_fatal_count == 1)) {
14493 			switch (code) {
14494 			case TRAN_BADPKT:
14495 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14496 				    "transport rejected bad packet\n");
14497 				break;
14498 			case TRAN_FATAL_ERROR:
14499 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14500 				    "transport rejected fatal error\n");
14501 				break;
14502 			default:
14503 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14504 				    "transport rejected (%d)\n", code);
14505 				break;
14506 			}
14507 		}
14508 	}
14509 }
14510 
14511 
14512 /*
14513  *    Function: sd_add_buf_to_waitq
14514  *
14515  * Description: Add the given buf(9S) struct to the wait queue for the
14516  *		instance.  If sorting is enabled, then the buf is added
14517  *		to the queue via an elevator sort algorithm (a la
14518  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
14519  *		If sorting is not enabled, then the buf is just added
14520  *		to the end of the wait queue.
14521  *
14522  * Return Code: void
14523  *
14524  *     Context: Does not sleep/block, therefore technically can be called
14525  *		from any context.  However if sorting is enabled then the
14526  *		execution time is indeterminate, and may take long if
14527  *		the wait queue grows large.
14528  */
14529 
14530 static void
14531 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
14532 {
14533 	struct buf *ap;
14534 
14535 	ASSERT(bp != NULL);
14536 	ASSERT(un != NULL);
14537 	ASSERT(mutex_owned(SD_MUTEX(un)));
14538 
14539 	/* If the queue is empty, add the buf as the only entry & return. */
14540 	if (un->un_waitq_headp == NULL) {
14541 		ASSERT(un->un_waitq_tailp == NULL);
14542 		un->un_waitq_headp = un->un_waitq_tailp = bp;
14543 		bp->av_forw = NULL;
14544 		return;
14545 	}
14546 
14547 	ASSERT(un->un_waitq_tailp != NULL);
14548 
14549 	/*
14550 	 * If sorting is disabled, just add the buf to the tail end of
14551 	 * the wait queue and return.
14552 	 */
14553 	if (un->un_f_disksort_disabled || un->un_f_enable_rmw) {
14554 		un->un_waitq_tailp->av_forw = bp;
14555 		un->un_waitq_tailp = bp;
14556 		bp->av_forw = NULL;
14557 		return;
14558 	}
14559 
14560 	/*
14561 	 * Sort thru the list of requests currently on the wait queue
14562 	 * and add the new buf request at the appropriate position.
14563 	 *
14564 	 * The un->un_waitq_headp is an activity chain pointer on which
14565 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
14566 	 * first queue holds those requests which are positioned after
14567 	 * the current SD_GET_BLKNO() (in the first request); the second holds
14568 	 * requests which came in after their SD_GET_BLKNO() number was passed.
14569 	 * Thus we implement a one way scan, retracting after reaching
14570 	 * the end of the drive to the first request on the second
14571 	 * queue, at which time it becomes the first queue.
14572 	 * A one-way scan is natural because of the way UNIX read-ahead
14573 	 * blocks are allocated.
14574 	 *
14575 	 * If we lie after the first request, then we must locate the
14576 	 * second request list and add ourselves to it.
14577 	 */
14578 	ap = un->un_waitq_headp;
14579 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
14580 		while (ap->av_forw != NULL) {
14581 			/*
14582 			 * Look for an "inversion" in the (normally
14583 			 * ascending) block numbers. This indicates
14584 			 * the start of the second request list.
14585 			 */
14586 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14587 				/*
14588 				 * Search the second request list for the
14589 				 * first request at a larger block number.
14590 				 * We go before that; however if there is
14591 				 * no such request, we go at the end.
14592 				 */
14593 				do {
14594 					if (SD_GET_BLKNO(bp) <
14595 					    SD_GET_BLKNO(ap->av_forw)) {
14596 						goto insert;
14597 					}
14598 					ap = ap->av_forw;
14599 				} while (ap->av_forw != NULL);
14600 				goto insert;		/* after last */
14601 			}
14602 			ap = ap->av_forw;
14603 		}
14604 
14605 		/*
14606 		 * No inversions... we will go after the last, and
14607 		 * be the first request in the second request list.
14608 		 */
14609 		goto insert;
14610 	}
14611 
14612 	/*
14613 	 * Request is at/after the current request...
14614 	 * sort in the first request list.
14615 	 */
14616 	while (ap->av_forw != NULL) {
14617 		/*
14618 		 * We want to go after the current request (1) if
14619 		 * there is an inversion after it (i.e. it is the end
14620 		 * of the first request list), or (2) if the next
14621 		 * request is a larger block no. than our request.
14622 		 */
14623 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14624 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14625 			goto insert;
14626 		}
14627 		ap = ap->av_forw;
14628 	}
14629 
14630 	/*
14631 	 * Neither a second list nor a larger request, therefore
14632 	 * we go at the end of the first list (which is the same
14633 	 * as the end of the whole schebang).
14634 	 */
14635 insert:
14636 	bp->av_forw = ap->av_forw;
14637 	ap->av_forw = bp;
14638 
14639 	/*
14640 	 * If we inserted onto the tail end of the waitq, make sure the
14641 	 * tail pointer is updated.
14642 	 */
14643 	if (ap == un->un_waitq_tailp) {
14644 		un->un_waitq_tailp = bp;
14645 	}
14646 }
14647 
14648 
14649 /*
14650  *    Function: sd_start_cmds
14651  *
14652  * Description: Remove and transport cmds from the driver queues.
14653  *
14654  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14655  *
14656  *		immed_bp - ptr to a buf to be transported immediately. Only
14657  *		the immed_bp is transported; bufs on the waitq are not
14658  *		processed and the un_retry_bp is not checked.  If immed_bp is
14659  *		NULL, then normal queue processing is performed.
14660  *
14661  *     Context: May be called from kernel thread context, interrupt context,
14662  *		or runout callback context. This function may not block or
14663  *		call routines that block.
14664  */
14665 
14666 static void
14667 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14668 {
14669 	struct	sd_xbuf	*xp;
14670 	struct	buf	*bp;
14671 	void	(*statp)(kstat_io_t *);
14672 #if defined(__x86)	/* DMAFREE for x86 only */
14673 	void	(*saved_statp)(kstat_io_t *);
14674 #endif
14675 	int	rval;
14676 	struct sd_fm_internal *sfip = NULL;
14677 
14678 	ASSERT(un != NULL);
14679 	ASSERT(mutex_owned(SD_MUTEX(un)));
14680 	ASSERT(un->un_ncmds_in_transport >= 0);
14681 	ASSERT(un->un_throttle >= 0);
14682 
14683 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14684 
14685 	do {
14686 #if defined(__x86)	/* DMAFREE for x86 only */
14687 		saved_statp = NULL;
14688 #endif
14689 
14690 		/*
14691 		 * If we are syncing or dumping, fail the command to
14692 		 * avoid recursively calling back into scsi_transport().
14693 		 * The dump I/O itself uses a separate code path so this
14694 		 * only prevents non-dump I/O from being sent while dumping.
14695 		 * File system sync takes place before dumping begins.
14696 		 * During panic, filesystem I/O is allowed provided
14697 		 * un_in_callback is <= 1.  This is to prevent recursion
14698 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14699 		 * sd_start_cmds and so on.  See panic.c for more information
14700 		 * about the states the system can be in during panic.
14701 		 */
14702 		if ((un->un_state == SD_STATE_DUMPING) ||
14703 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14704 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14705 			    "sd_start_cmds: panicking\n");
14706 			goto exit;
14707 		}
14708 
14709 		if ((bp = immed_bp) != NULL) {
14710 			/*
14711 			 * We have a bp that must be transported immediately.
14712 			 * It's OK to transport the immed_bp here without doing
14713 			 * the throttle limit check because the immed_bp is
14714 			 * always used in a retry/recovery case. This means
14715 			 * that we know we are not at the throttle limit by
14716 			 * virtue of the fact that to get here we must have
14717 			 * already gotten a command back via sdintr(). This also
14718 			 * relies on (1) the command on un_retry_bp preventing
14719 			 * further commands from the waitq from being issued;
14720 			 * and (2) the code in sd_retry_command checking the
14721 			 * throttle limit before issuing a delayed or immediate
14722 			 * retry. This holds even if the throttle limit is
14723 			 * currently ratcheted down from its maximum value.
14724 			 */
14725 			statp = kstat_runq_enter;
14726 			if (bp == un->un_retry_bp) {
14727 				ASSERT((un->un_retry_statp == NULL) ||
14728 				    (un->un_retry_statp == kstat_waitq_enter) ||
14729 				    (un->un_retry_statp ==
14730 				    kstat_runq_back_to_waitq));
14731 				/*
14732 				 * If the waitq kstat was incremented when
14733 				 * sd_set_retry_bp() queued this bp for a retry,
14734 				 * then we must set up statp so that the waitq
14735 				 * count will get decremented correctly below.
14736 				 * Also we must clear un->un_retry_statp to
14737 				 * ensure that we do not act on a stale value
14738 				 * in this field.
14739 				 */
14740 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14741 				    (un->un_retry_statp ==
14742 				    kstat_runq_back_to_waitq)) {
14743 					statp = kstat_waitq_to_runq;
14744 				}
14745 #if defined(__x86)	/* DMAFREE for x86 only */
14746 				saved_statp = un->un_retry_statp;
14747 #endif
14748 				un->un_retry_statp = NULL;
14749 
14750 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14751 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14752 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14753 				    un, un->un_retry_bp, un->un_throttle,
14754 				    un->un_ncmds_in_transport);
14755 			} else {
14756 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14757 				    "processing priority bp:0x%p\n", bp);
14758 			}
14759 
14760 		} else if ((bp = un->un_waitq_headp) != NULL) {
14761 			/*
14762 			 * A command on the waitq is ready to go, but do not
14763 			 * send it if:
14764 			 *
14765 			 * (1) the throttle limit has been reached, or
14766 			 * (2) a retry is pending, or
14767 			 * (3) a START_STOP_UNIT callback pending, or
14768 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14769 			 *	command is pending.
14770 			 *
14771 			 * For all of these conditions, IO processing will
14772 			 * restart after the condition is cleared.
14773 			 */
14774 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14775 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14776 				    "sd_start_cmds: exiting, "
14777 				    "throttle limit reached!\n");
14778 				goto exit;
14779 			}
14780 			if (un->un_retry_bp != NULL) {
14781 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14782 				    "sd_start_cmds: exiting, retry pending!\n");
14783 				goto exit;
14784 			}
14785 			if (un->un_startstop_timeid != NULL) {
14786 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14787 				    "sd_start_cmds: exiting, "
14788 				    "START_STOP pending!\n");
14789 				goto exit;
14790 			}
14791 			if (un->un_direct_priority_timeid != NULL) {
14792 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14793 				    "sd_start_cmds: exiting, "
14794 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14795 				goto exit;
14796 			}
14797 
14798 			/* Dequeue the command */
14799 			un->un_waitq_headp = bp->av_forw;
14800 			if (un->un_waitq_headp == NULL) {
14801 				un->un_waitq_tailp = NULL;
14802 			}
14803 			bp->av_forw = NULL;
14804 			statp = kstat_waitq_to_runq;
14805 			SD_TRACE(SD_LOG_IO_CORE, un,
14806 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14807 
14808 		} else {
14809 			/* No work to do so bail out now */
14810 			SD_TRACE(SD_LOG_IO_CORE, un,
14811 			    "sd_start_cmds: no more work, exiting!\n");
14812 			goto exit;
14813 		}
14814 
14815 		/*
14816 		 * Reset the state to normal. This is the mechanism by which
14817 		 * the state transitions from either SD_STATE_RWAIT or
14818 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14819 		 * If state is SD_STATE_PM_CHANGING then this command is
14820 		 * part of the device power control and the state must
14821 		 * not be put back to normal. Doing so would would
14822 		 * allow new commands to proceed when they shouldn't,
14823 		 * the device may be going off.
14824 		 */
14825 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14826 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14827 			New_state(un, SD_STATE_NORMAL);
14828 		}
14829 
14830 		xp = SD_GET_XBUF(bp);
14831 		ASSERT(xp != NULL);
14832 
14833 #if defined(__x86)	/* DMAFREE for x86 only */
14834 		/*
14835 		 * Allocate the scsi_pkt if we need one, or attach DMA
14836 		 * resources if we have a scsi_pkt that needs them. The
14837 		 * latter should only occur for commands that are being
14838 		 * retried.
14839 		 */
14840 		if ((xp->xb_pktp == NULL) ||
14841 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
14842 #else
14843 		if (xp->xb_pktp == NULL) {
14844 #endif
14845 			/*
14846 			 * There is no scsi_pkt allocated for this buf. Call
14847 			 * the initpkt function to allocate & init one.
14848 			 *
14849 			 * The scsi_init_pkt runout callback functionality is
14850 			 * implemented as follows:
14851 			 *
14852 			 * 1) The initpkt function always calls
14853 			 *    scsi_init_pkt(9F) with sdrunout specified as the
14854 			 *    callback routine.
14855 			 * 2) A successful packet allocation is initialized and
14856 			 *    the I/O is transported.
14857 			 * 3) The I/O associated with an allocation resource
14858 			 *    failure is left on its queue to be retried via
14859 			 *    runout or the next I/O.
14860 			 * 4) The I/O associated with a DMA error is removed
14861 			 *    from the queue and failed with EIO. Processing of
14862 			 *    the transport queues is also halted to be
14863 			 *    restarted via runout or the next I/O.
14864 			 * 5) The I/O associated with a CDB size or packet
14865 			 *    size error is removed from the queue and failed
14866 			 *    with EIO. Processing of the transport queues is
14867 			 *    continued.
14868 			 *
14869 			 * Note: there is no interface for canceling a runout
14870 			 * callback. To prevent the driver from detaching or
14871 			 * suspending while a runout is pending the driver
14872 			 * state is set to SD_STATE_RWAIT
14873 			 *
14874 			 * Note: using the scsi_init_pkt callback facility can
14875 			 * result in an I/O request persisting at the head of
14876 			 * the list which cannot be satisfied even after
14877 			 * multiple retries. In the future the driver may
14878 			 * implement some kind of maximum runout count before
14879 			 * failing an I/O.
14880 			 *
14881 			 * Note: the use of funcp below may seem superfluous,
14882 			 * but it helps warlock figure out the correct
14883 			 * initpkt function calls (see [s]sd.wlcmd).
14884 			 */
14885 			struct scsi_pkt	*pktp;
14886 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
14887 
14888 			ASSERT(bp != un->un_rqs_bp);
14889 
14890 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
14891 			switch ((*funcp)(bp, &pktp)) {
14892 			case  SD_PKT_ALLOC_SUCCESS:
14893 				xp->xb_pktp = pktp;
14894 				SD_TRACE(SD_LOG_IO_CORE, un,
14895 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
14896 				    pktp);
14897 				goto got_pkt;
14898 
14899 			case SD_PKT_ALLOC_FAILURE:
14900 				/*
14901 				 * Temporary (hopefully) resource depletion.
14902 				 * Since retries and RQS commands always have a
14903 				 * scsi_pkt allocated, these cases should never
14904 				 * get here. So the only cases this needs to
14905 				 * handle is a bp from the waitq (which we put
14906 				 * back onto the waitq for sdrunout), or a bp
14907 				 * sent as an immed_bp (which we just fail).
14908 				 */
14909 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14910 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
14911 
14912 #if defined(__x86)	/* DMAFREE for x86 only */
14913 
14914 				if (bp == immed_bp) {
14915 					/*
14916 					 * If SD_XB_DMA_FREED is clear, then
14917 					 * this is a failure to allocate a
14918 					 * scsi_pkt, and we must fail the
14919 					 * command.
14920 					 */
14921 					if ((xp->xb_pkt_flags &
14922 					    SD_XB_DMA_FREED) == 0) {
14923 						break;
14924 					}
14925 
14926 					/*
14927 					 * If this immediate command is NOT our
14928 					 * un_retry_bp, then we must fail it.
14929 					 */
14930 					if (bp != un->un_retry_bp) {
14931 						break;
14932 					}
14933 
14934 					/*
14935 					 * We get here if this cmd is our
14936 					 * un_retry_bp that was DMAFREED, but
14937 					 * scsi_init_pkt() failed to reallocate
14938 					 * DMA resources when we attempted to
14939 					 * retry it. This can happen when an
14940 					 * mpxio failover is in progress, but
14941 					 * we don't want to just fail the
14942 					 * command in this case.
14943 					 *
14944 					 * Use timeout(9F) to restart it after
14945 					 * a 100ms delay.  We don't want to
14946 					 * let sdrunout() restart it, because
14947 					 * sdrunout() is just supposed to start
14948 					 * commands that are sitting on the
14949 					 * wait queue.  The un_retry_bp stays
14950 					 * set until the command completes, but
14951 					 * sdrunout can be called many times
14952 					 * before that happens.  Since sdrunout
14953 					 * cannot tell if the un_retry_bp is
14954 					 * already in the transport, it could
14955 					 * end up calling scsi_transport() for
14956 					 * the un_retry_bp multiple times.
14957 					 *
14958 					 * Also: don't schedule the callback
14959 					 * if some other callback is already
14960 					 * pending.
14961 					 */
14962 					if (un->un_retry_statp == NULL) {
14963 						/*
14964 						 * restore the kstat pointer to
14965 						 * keep kstat counts coherent
14966 						 * when we do retry the command.
14967 						 */
14968 						un->un_retry_statp =
14969 						    saved_statp;
14970 					}
14971 
14972 					if ((un->un_startstop_timeid == NULL) &&
14973 					    (un->un_retry_timeid == NULL) &&
14974 					    (un->un_direct_priority_timeid ==
14975 					    NULL)) {
14976 
14977 						un->un_retry_timeid =
14978 						    timeout(
14979 						    sd_start_retry_command,
14980 						    un, SD_RESTART_TIMEOUT);
14981 					}
14982 					goto exit;
14983 				}
14984 
14985 #else
14986 				if (bp == immed_bp) {
14987 					break;	/* Just fail the command */
14988 				}
14989 #endif
14990 
14991 				/* Add the buf back to the head of the waitq */
14992 				bp->av_forw = un->un_waitq_headp;
14993 				un->un_waitq_headp = bp;
14994 				if (un->un_waitq_tailp == NULL) {
14995 					un->un_waitq_tailp = bp;
14996 				}
14997 				goto exit;
14998 
14999 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
15000 				/*
15001 				 * HBA DMA resource failure. Fail the command
15002 				 * and continue processing of the queues.
15003 				 */
15004 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15005 				    "sd_start_cmds: "
15006 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
15007 				break;
15008 
15009 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
15010 				/*
15011 				 * Note:x86: Partial DMA mapping not supported
15012 				 * for USCSI commands, and all the needed DMA
15013 				 * resources were not allocated.
15014 				 */
15015 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15016 				    "sd_start_cmds: "
15017 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
15018 				break;
15019 
15020 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
15021 				/*
15022 				 * Note:x86: Request cannot fit into CDB based
15023 				 * on lba and len.
15024 				 */
15025 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15026 				    "sd_start_cmds: "
15027 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
15028 				break;
15029 
15030 			default:
15031 				/* Should NEVER get here! */
15032 				panic("scsi_initpkt error");
15033 				/*NOTREACHED*/
15034 			}
15035 
15036 			/*
15037 			 * Fatal error in allocating a scsi_pkt for this buf.
15038 			 * Update kstats & return the buf with an error code.
15039 			 * We must use sd_return_failed_command_no_restart() to
15040 			 * avoid a recursive call back into sd_start_cmds().
15041 			 * However this also means that we must keep processing
15042 			 * the waitq here in order to avoid stalling.
15043 			 */
15044 			if (statp == kstat_waitq_to_runq) {
15045 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
15046 			}
15047 			sd_return_failed_command_no_restart(un, bp, EIO);
15048 			if (bp == immed_bp) {
15049 				/* immed_bp is gone by now, so clear this */
15050 				immed_bp = NULL;
15051 			}
15052 			continue;
15053 		}
15054 got_pkt:
15055 		if (bp == immed_bp) {
15056 			/* goto the head of the class.... */
15057 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15058 		}
15059 
15060 		un->un_ncmds_in_transport++;
15061 		SD_UPDATE_KSTATS(un, statp, bp);
15062 
15063 		/*
15064 		 * Call scsi_transport() to send the command to the target.
15065 		 * According to SCSA architecture, we must drop the mutex here
15066 		 * before calling scsi_transport() in order to avoid deadlock.
15067 		 * Note that the scsi_pkt's completion routine can be executed
15068 		 * (from interrupt context) even before the call to
15069 		 * scsi_transport() returns.
15070 		 */
15071 		SD_TRACE(SD_LOG_IO_CORE, un,
15072 		    "sd_start_cmds: calling scsi_transport()\n");
15073 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
15074 
15075 		mutex_exit(SD_MUTEX(un));
15076 		rval = scsi_transport(xp->xb_pktp);
15077 		mutex_enter(SD_MUTEX(un));
15078 
15079 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15080 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
15081 
15082 		switch (rval) {
15083 		case TRAN_ACCEPT:
15084 			/* Clear this with every pkt accepted by the HBA */
15085 			un->un_tran_fatal_count = 0;
15086 			break;	/* Success; try the next cmd (if any) */
15087 
15088 		case TRAN_BUSY:
15089 			un->un_ncmds_in_transport--;
15090 			ASSERT(un->un_ncmds_in_transport >= 0);
15091 
15092 			/*
15093 			 * Don't retry request sense, the sense data
15094 			 * is lost when another request is sent.
15095 			 * Free up the rqs buf and retry
15096 			 * the original failed cmd.  Update kstat.
15097 			 */
15098 			if (bp == un->un_rqs_bp) {
15099 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15100 				bp = sd_mark_rqs_idle(un, xp);
15101 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15102 				    NULL, NULL, EIO, un->un_busy_timeout / 500,
15103 				    kstat_waitq_enter);
15104 				goto exit;
15105 			}
15106 
15107 #if defined(__x86)	/* DMAFREE for x86 only */
15108 			/*
15109 			 * Free the DMA resources for the  scsi_pkt. This will
15110 			 * allow mpxio to select another path the next time
15111 			 * we call scsi_transport() with this scsi_pkt.
15112 			 * See sdintr() for the rationalization behind this.
15113 			 */
15114 			if ((un->un_f_is_fibre == TRUE) &&
15115 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15116 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
15117 				scsi_dmafree(xp->xb_pktp);
15118 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15119 			}
15120 #endif
15121 
15122 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
15123 				/*
15124 				 * Commands that are SD_PATH_DIRECT_PRIORITY
15125 				 * are for error recovery situations. These do
15126 				 * not use the normal command waitq, so if they
15127 				 * get a TRAN_BUSY we cannot put them back onto
15128 				 * the waitq for later retry. One possible
15129 				 * problem is that there could already be some
15130 				 * other command on un_retry_bp that is waiting
15131 				 * for this one to complete, so we would be
15132 				 * deadlocked if we put this command back onto
15133 				 * the waitq for later retry (since un_retry_bp
15134 				 * must complete before the driver gets back to
15135 				 * commands on the waitq).
15136 				 *
15137 				 * To avoid deadlock we must schedule a callback
15138 				 * that will restart this command after a set
15139 				 * interval.  This should keep retrying for as
15140 				 * long as the underlying transport keeps
15141 				 * returning TRAN_BUSY (just like for other
15142 				 * commands).  Use the same timeout interval as
15143 				 * for the ordinary TRAN_BUSY retry.
15144 				 */
15145 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15146 				    "sd_start_cmds: scsi_transport() returned "
15147 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
15148 
15149 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15150 				un->un_direct_priority_timeid =
15151 				    timeout(sd_start_direct_priority_command,
15152 				    bp, un->un_busy_timeout / 500);
15153 
15154 				goto exit;
15155 			}
15156 
15157 			/*
15158 			 * For TRAN_BUSY, we want to reduce the throttle value,
15159 			 * unless we are retrying a command.
15160 			 */
15161 			if (bp != un->un_retry_bp) {
15162 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
15163 			}
15164 
15165 			/*
15166 			 * Set up the bp to be tried again 10 ms later.
15167 			 * Note:x86: Is there a timeout value in the sd_lun
15168 			 * for this condition?
15169 			 */
15170 			sd_set_retry_bp(un, bp, un->un_busy_timeout / 500,
15171 			    kstat_runq_back_to_waitq);
15172 			goto exit;
15173 
15174 		case TRAN_FATAL_ERROR:
15175 			un->un_tran_fatal_count++;
15176 			/* FALLTHRU */
15177 
15178 		case TRAN_BADPKT:
15179 		default:
15180 			un->un_ncmds_in_transport--;
15181 			ASSERT(un->un_ncmds_in_transport >= 0);
15182 
15183 			/*
15184 			 * If this is our REQUEST SENSE command with a
15185 			 * transport error, we must get back the pointers
15186 			 * to the original buf, and mark the REQUEST
15187 			 * SENSE command as "available".
15188 			 */
15189 			if (bp == un->un_rqs_bp) {
15190 				bp = sd_mark_rqs_idle(un, xp);
15191 				xp = SD_GET_XBUF(bp);
15192 			} else {
15193 				/*
15194 				 * Legacy behavior: do not update transport
15195 				 * error count for request sense commands.
15196 				 */
15197 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
15198 			}
15199 
15200 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15201 			sd_print_transport_rejected_message(un, xp, rval);
15202 
15203 			/*
15204 			 * This command will be terminated by SD driver due
15205 			 * to a fatal transport error. We should post
15206 			 * ereport.io.scsi.cmd.disk.tran with driver-assessment
15207 			 * of "fail" for any command to indicate this
15208 			 * situation.
15209 			 */
15210 			if (xp->xb_ena > 0) {
15211 				ASSERT(un->un_fm_private != NULL);
15212 				sfip = un->un_fm_private;
15213 				sfip->fm_ssc.ssc_flags |= SSC_FLAGS_TRAN_ABORT;
15214 				sd_ssc_extract_info(&sfip->fm_ssc, un,
15215 				    xp->xb_pktp, bp, xp);
15216 				sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15217 			}
15218 
15219 			/*
15220 			 * We must use sd_return_failed_command_no_restart() to
15221 			 * avoid a recursive call back into sd_start_cmds().
15222 			 * However this also means that we must keep processing
15223 			 * the waitq here in order to avoid stalling.
15224 			 */
15225 			sd_return_failed_command_no_restart(un, bp, EIO);
15226 
15227 			/*
15228 			 * Notify any threads waiting in sd_ddi_suspend() that
15229 			 * a command completion has occurred.
15230 			 */
15231 			if (un->un_state == SD_STATE_SUSPENDED) {
15232 				cv_broadcast(&un->un_disk_busy_cv);
15233 			}
15234 
15235 			if (bp == immed_bp) {
15236 				/* immed_bp is gone by now, so clear this */
15237 				immed_bp = NULL;
15238 			}
15239 			break;
15240 		}
15241 
15242 	} while (immed_bp == NULL);
15243 
15244 exit:
15245 	ASSERT(mutex_owned(SD_MUTEX(un)));
15246 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
15247 }
15248 
15249 
15250 /*
15251  *    Function: sd_return_command
15252  *
15253  * Description: Returns a command to its originator (with or without an
15254  *		error).  Also starts commands waiting to be transported
15255  *		to the target.
15256  *
15257  *     Context: May be called from interrupt, kernel, or timeout context
15258  */
15259 
15260 static void
15261 sd_return_command(struct sd_lun *un, struct buf *bp)
15262 {
15263 	struct sd_xbuf *xp;
15264 	struct scsi_pkt *pktp;
15265 	struct sd_fm_internal *sfip;
15266 
15267 	ASSERT(bp != NULL);
15268 	ASSERT(un != NULL);
15269 	ASSERT(mutex_owned(SD_MUTEX(un)));
15270 	ASSERT(bp != un->un_rqs_bp);
15271 	xp = SD_GET_XBUF(bp);
15272 	ASSERT(xp != NULL);
15273 
15274 	pktp = SD_GET_PKTP(bp);
15275 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15276 	ASSERT(sfip != NULL);
15277 
15278 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
15279 
15280 	/*
15281 	 * Note: check for the "sdrestart failed" case.
15282 	 */
15283 	if ((un->un_partial_dma_supported == 1) &&
15284 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
15285 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
15286 	    (xp->xb_pktp->pkt_resid == 0)) {
15287 
15288 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
15289 			/*
15290 			 * Successfully set up next portion of cmd
15291 			 * transfer, try sending it
15292 			 */
15293 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15294 			    NULL, NULL, 0, (clock_t)0, NULL);
15295 			sd_start_cmds(un, NULL);
15296 			return;	/* Note:x86: need a return here? */
15297 		}
15298 	}
15299 
15300 	/*
15301 	 * If this is the failfast bp, clear it from un_failfast_bp. This
15302 	 * can happen if upon being re-tried the failfast bp either
15303 	 * succeeded or encountered another error (possibly even a different
15304 	 * error than the one that precipitated the failfast state, but in
15305 	 * that case it would have had to exhaust retries as well). Regardless,
15306 	 * this should not occur whenever the instance is in the active
15307 	 * failfast state.
15308 	 */
15309 	if (bp == un->un_failfast_bp) {
15310 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15311 		un->un_failfast_bp = NULL;
15312 	}
15313 
15314 	/*
15315 	 * Clear the failfast state upon successful completion of ANY cmd.
15316 	 */
15317 	if (bp->b_error == 0) {
15318 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15319 		/*
15320 		 * If this is a successful command, but used to be retried,
15321 		 * we will take it as a recovered command and post an
15322 		 * ereport with driver-assessment of "recovered".
15323 		 */
15324 		if (xp->xb_ena > 0) {
15325 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15326 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RECOVERY);
15327 		}
15328 	} else {
15329 		/*
15330 		 * If this is a failed non-USCSI command we will post an
15331 		 * ereport with driver-assessment set accordingly("fail" or
15332 		 * "fatal").
15333 		 */
15334 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15335 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15336 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15337 		}
15338 	}
15339 
15340 	/*
15341 	 * This is used if the command was retried one or more times. Show that
15342 	 * we are done with it, and allow processing of the waitq to resume.
15343 	 */
15344 	if (bp == un->un_retry_bp) {
15345 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15346 		    "sd_return_command: un:0x%p: "
15347 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15348 		un->un_retry_bp = NULL;
15349 		un->un_retry_statp = NULL;
15350 	}
15351 
15352 	SD_UPDATE_RDWR_STATS(un, bp);
15353 	SD_UPDATE_PARTITION_STATS(un, bp);
15354 
15355 	switch (un->un_state) {
15356 	case SD_STATE_SUSPENDED:
15357 		/*
15358 		 * Notify any threads waiting in sd_ddi_suspend() that
15359 		 * a command completion has occurred.
15360 		 */
15361 		cv_broadcast(&un->un_disk_busy_cv);
15362 		break;
15363 	default:
15364 		sd_start_cmds(un, NULL);
15365 		break;
15366 	}
15367 
15368 	/* Return this command up the iodone chain to its originator. */
15369 	mutex_exit(SD_MUTEX(un));
15370 
15371 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15372 	xp->xb_pktp = NULL;
15373 
15374 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15375 
15376 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15377 	mutex_enter(SD_MUTEX(un));
15378 
15379 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
15380 }
15381 
15382 
15383 /*
15384  *    Function: sd_return_failed_command
15385  *
15386  * Description: Command completion when an error occurred.
15387  *
15388  *     Context: May be called from interrupt context
15389  */
15390 
15391 static void
15392 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
15393 {
15394 	ASSERT(bp != NULL);
15395 	ASSERT(un != NULL);
15396 	ASSERT(mutex_owned(SD_MUTEX(un)));
15397 
15398 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15399 	    "sd_return_failed_command: entry\n");
15400 
15401 	/*
15402 	 * b_resid could already be nonzero due to a partial data
15403 	 * transfer, so do not change it here.
15404 	 */
15405 	SD_BIOERROR(bp, errcode);
15406 
15407 	sd_return_command(un, bp);
15408 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15409 	    "sd_return_failed_command: exit\n");
15410 }
15411 
15412 
15413 /*
15414  *    Function: sd_return_failed_command_no_restart
15415  *
15416  * Description: Same as sd_return_failed_command, but ensures that no
15417  *		call back into sd_start_cmds will be issued.
15418  *
15419  *     Context: May be called from interrupt context
15420  */
15421 
15422 static void
15423 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
15424     int errcode)
15425 {
15426 	struct sd_xbuf *xp;
15427 
15428 	ASSERT(bp != NULL);
15429 	ASSERT(un != NULL);
15430 	ASSERT(mutex_owned(SD_MUTEX(un)));
15431 	xp = SD_GET_XBUF(bp);
15432 	ASSERT(xp != NULL);
15433 	ASSERT(errcode != 0);
15434 
15435 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15436 	    "sd_return_failed_command_no_restart: entry\n");
15437 
15438 	/*
15439 	 * b_resid could already be nonzero due to a partial data
15440 	 * transfer, so do not change it here.
15441 	 */
15442 	SD_BIOERROR(bp, errcode);
15443 
15444 	/*
15445 	 * If this is the failfast bp, clear it. This can happen if the
15446 	 * failfast bp encounterd a fatal error when we attempted to
15447 	 * re-try it (such as a scsi_transport(9F) failure).  However
15448 	 * we should NOT be in an active failfast state if the failfast
15449 	 * bp is not NULL.
15450 	 */
15451 	if (bp == un->un_failfast_bp) {
15452 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15453 		un->un_failfast_bp = NULL;
15454 	}
15455 
15456 	if (bp == un->un_retry_bp) {
15457 		/*
15458 		 * This command was retried one or more times. Show that we are
15459 		 * done with it, and allow processing of the waitq to resume.
15460 		 */
15461 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15462 		    "sd_return_failed_command_no_restart: "
15463 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15464 		un->un_retry_bp = NULL;
15465 		un->un_retry_statp = NULL;
15466 	}
15467 
15468 	SD_UPDATE_RDWR_STATS(un, bp);
15469 	SD_UPDATE_PARTITION_STATS(un, bp);
15470 
15471 	mutex_exit(SD_MUTEX(un));
15472 
15473 	if (xp->xb_pktp != NULL) {
15474 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15475 		xp->xb_pktp = NULL;
15476 	}
15477 
15478 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15479 
15480 	mutex_enter(SD_MUTEX(un));
15481 
15482 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15483 	    "sd_return_failed_command_no_restart: exit\n");
15484 }
15485 
15486 
15487 /*
15488  *    Function: sd_retry_command
15489  *
15490  * Description: queue up a command for retry, or (optionally) fail it
15491  *		if retry counts are exhausted.
15492  *
15493  *   Arguments: un - Pointer to the sd_lun struct for the target.
15494  *
15495  *		bp - Pointer to the buf for the command to be retried.
15496  *
15497  *		retry_check_flag - Flag to see which (if any) of the retry
15498  *		   counts should be decremented/checked. If the indicated
15499  *		   retry count is exhausted, then the command will not be
15500  *		   retried; it will be failed instead. This should use a
15501  *		   value equal to one of the following:
15502  *
15503  *			SD_RETRIES_NOCHECK
15504  *			SD_RESD_RETRIES_STANDARD
15505  *			SD_RETRIES_VICTIM
15506  *
15507  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
15508  *		   if the check should be made to see of FLAG_ISOLATE is set
15509  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
15510  *		   not retried, it is simply failed.
15511  *
15512  *		user_funcp - Ptr to function to call before dispatching the
15513  *		   command. May be NULL if no action needs to be performed.
15514  *		   (Primarily intended for printing messages.)
15515  *
15516  *		user_arg - Optional argument to be passed along to
15517  *		   the user_funcp call.
15518  *
15519  *		failure_code - errno return code to set in the bp if the
15520  *		   command is going to be failed.
15521  *
15522  *		retry_delay - Retry delay interval in (clock_t) units. May
15523  *		   be zero which indicates that the retry should be retried
15524  *		   immediately (ie, without an intervening delay).
15525  *
15526  *		statp - Ptr to kstat function to be updated if the command
15527  *		   is queued for a delayed retry. May be NULL if no kstat
15528  *		   update is desired.
15529  *
15530  *     Context: May be called from interrupt context.
15531  */
15532 
15533 static void
15534 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
15535     void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int code),
15536     void *user_arg, int failure_code, clock_t retry_delay,
15537     void (*statp)(kstat_io_t *))
15538 {
15539 	struct sd_xbuf	*xp;
15540 	struct scsi_pkt	*pktp;
15541 	struct sd_fm_internal *sfip;
15542 
15543 	ASSERT(un != NULL);
15544 	ASSERT(mutex_owned(SD_MUTEX(un)));
15545 	ASSERT(bp != NULL);
15546 	xp = SD_GET_XBUF(bp);
15547 	ASSERT(xp != NULL);
15548 	pktp = SD_GET_PKTP(bp);
15549 	ASSERT(pktp != NULL);
15550 
15551 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15552 	ASSERT(sfip != NULL);
15553 
15554 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15555 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
15556 
15557 	/*
15558 	 * If we are syncing or dumping, fail the command to avoid
15559 	 * recursively calling back into scsi_transport().
15560 	 */
15561 	if (ddi_in_panic()) {
15562 		goto fail_command_no_log;
15563 	}
15564 
15565 	/*
15566 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
15567 	 * log an error and fail the command.
15568 	 */
15569 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15570 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
15571 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
15572 		sd_dump_memory(un, SD_LOG_IO, "CDB",
15573 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15574 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15575 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15576 		goto fail_command;
15577 	}
15578 
15579 	/*
15580 	 * If we are suspended, then put the command onto head of the
15581 	 * wait queue since we don't want to start more commands, and
15582 	 * clear the un_retry_bp. Next time when we are resumed, will
15583 	 * handle the command in the wait queue.
15584 	 */
15585 	switch (un->un_state) {
15586 	case SD_STATE_SUSPENDED:
15587 	case SD_STATE_DUMPING:
15588 		bp->av_forw = un->un_waitq_headp;
15589 		un->un_waitq_headp = bp;
15590 		if (un->un_waitq_tailp == NULL) {
15591 			un->un_waitq_tailp = bp;
15592 		}
15593 		if (bp == un->un_retry_bp) {
15594 			un->un_retry_bp = NULL;
15595 			un->un_retry_statp = NULL;
15596 		}
15597 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15598 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15599 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15600 		return;
15601 	default:
15602 		break;
15603 	}
15604 
15605 	/*
15606 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15607 	 * is set; if it is then we do not want to retry the command.
15608 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15609 	 */
15610 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15611 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15612 			goto fail_command;
15613 		}
15614 	}
15615 
15616 
15617 	/*
15618 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15619 	 * command timeout or a selection timeout has occurred. This means
15620 	 * that we were unable to establish an kind of communication with
15621 	 * the target, and subsequent retries and/or commands are likely
15622 	 * to encounter similar results and take a long time to complete.
15623 	 *
15624 	 * If this is a failfast error condition, we need to update the
15625 	 * failfast state, even if this bp does not have B_FAILFAST set.
15626 	 */
15627 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15628 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15629 			ASSERT(un->un_failfast_bp == NULL);
15630 			/*
15631 			 * If we are already in the active failfast state, and
15632 			 * another failfast error condition has been detected,
15633 			 * then fail this command if it has B_FAILFAST set.
15634 			 * If B_FAILFAST is clear, then maintain the legacy
15635 			 * behavior of retrying heroically, even tho this will
15636 			 * take a lot more time to fail the command.
15637 			 */
15638 			if (bp->b_flags & B_FAILFAST) {
15639 				goto fail_command;
15640 			}
15641 		} else {
15642 			/*
15643 			 * We're not in the active failfast state, but we
15644 			 * have a failfast error condition, so we must begin
15645 			 * transition to the next state. We do this regardless
15646 			 * of whether or not this bp has B_FAILFAST set.
15647 			 */
15648 			if (un->un_failfast_bp == NULL) {
15649 				/*
15650 				 * This is the first bp to meet a failfast
15651 				 * condition so save it on un_failfast_bp &
15652 				 * do normal retry processing. Do not enter
15653 				 * active failfast state yet. This marks
15654 				 * entry into the "failfast pending" state.
15655 				 */
15656 				un->un_failfast_bp = bp;
15657 
15658 			} else if (un->un_failfast_bp == bp) {
15659 				/*
15660 				 * This is the second time *this* bp has
15661 				 * encountered a failfast error condition,
15662 				 * so enter active failfast state & flush
15663 				 * queues as appropriate.
15664 				 */
15665 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15666 				un->un_failfast_bp = NULL;
15667 				sd_failfast_flushq(un);
15668 
15669 				/*
15670 				 * Fail this bp now if B_FAILFAST set;
15671 				 * otherwise continue with retries. (It would
15672 				 * be pretty ironic if this bp succeeded on a
15673 				 * subsequent retry after we just flushed all
15674 				 * the queues).
15675 				 */
15676 				if (bp->b_flags & B_FAILFAST) {
15677 					goto fail_command;
15678 				}
15679 
15680 #if !defined(lint) && !defined(__lint)
15681 			} else {
15682 				/*
15683 				 * If neither of the preceeding conditionals
15684 				 * was true, it means that there is some
15685 				 * *other* bp that has met an inital failfast
15686 				 * condition and is currently either being
15687 				 * retried or is waiting to be retried. In
15688 				 * that case we should perform normal retry
15689 				 * processing on *this* bp, since there is a
15690 				 * chance that the current failfast condition
15691 				 * is transient and recoverable. If that does
15692 				 * not turn out to be the case, then retries
15693 				 * will be cleared when the wait queue is
15694 				 * flushed anyway.
15695 				 */
15696 #endif
15697 			}
15698 		}
15699 	} else {
15700 		/*
15701 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15702 		 * likely were able to at least establish some level of
15703 		 * communication with the target and subsequent commands
15704 		 * and/or retries are likely to get through to the target,
15705 		 * In this case we want to be aggressive about clearing
15706 		 * the failfast state. Note that this does not affect
15707 		 * the "failfast pending" condition.
15708 		 */
15709 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15710 	}
15711 
15712 
15713 	/*
15714 	 * Check the specified retry count to see if we can still do
15715 	 * any retries with this pkt before we should fail it.
15716 	 */
15717 	switch (retry_check_flag & SD_RETRIES_MASK) {
15718 	case SD_RETRIES_VICTIM:
15719 		/*
15720 		 * Check the victim retry count. If exhausted, then fall
15721 		 * thru & check against the standard retry count.
15722 		 */
15723 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15724 			/* Increment count & proceed with the retry */
15725 			xp->xb_victim_retry_count++;
15726 			break;
15727 		}
15728 		/* Victim retries exhausted, fall back to std. retries... */
15729 		/* FALLTHRU */
15730 
15731 	case SD_RETRIES_STANDARD:
15732 		if (xp->xb_retry_count >= un->un_retry_count) {
15733 			/* Retries exhausted, fail the command */
15734 			SD_TRACE(SD_LOG_IO_CORE, un,
15735 			    "sd_retry_command: retries exhausted!\n");
15736 			/*
15737 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15738 			 * commands with nonzero pkt_resid.
15739 			 */
15740 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15741 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15742 			    (pktp->pkt_resid != 0)) {
15743 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15744 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15745 					SD_UPDATE_B_RESID(bp, pktp);
15746 				}
15747 			}
15748 			goto fail_command;
15749 		}
15750 		xp->xb_retry_count++;
15751 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15752 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15753 		break;
15754 
15755 	case SD_RETRIES_UA:
15756 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15757 			/* Retries exhausted, fail the command */
15758 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15759 			    "Unit Attention retries exhausted. "
15760 			    "Check the target.\n");
15761 			goto fail_command;
15762 		}
15763 		xp->xb_ua_retry_count++;
15764 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15765 		    "sd_retry_command: retry count:%d\n",
15766 		    xp->xb_ua_retry_count);
15767 		break;
15768 
15769 	case SD_RETRIES_BUSY:
15770 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15771 			/* Retries exhausted, fail the command */
15772 			SD_TRACE(SD_LOG_IO_CORE, un,
15773 			    "sd_retry_command: retries exhausted!\n");
15774 			goto fail_command;
15775 		}
15776 		xp->xb_retry_count++;
15777 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15778 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15779 		break;
15780 
15781 	case SD_RETRIES_NOCHECK:
15782 	default:
15783 		/* No retry count to check. Just proceed with the retry */
15784 		break;
15785 	}
15786 
15787 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15788 
15789 	/*
15790 	 * If this is a non-USCSI command being retried
15791 	 * during execution last time, we should post an ereport with
15792 	 * driver-assessment of the value "retry".
15793 	 * For partial DMA, request sense and STATUS_QFULL, there are no
15794 	 * hardware errors, we bypass ereport posting.
15795 	 */
15796 	if (failure_code != 0) {
15797 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15798 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15799 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RETRY);
15800 		}
15801 	}
15802 
15803 	/*
15804 	 * If we were given a zero timeout, we must attempt to retry the
15805 	 * command immediately (ie, without a delay).
15806 	 */
15807 	if (retry_delay == 0) {
15808 		/*
15809 		 * Check some limiting conditions to see if we can actually
15810 		 * do the immediate retry.  If we cannot, then we must
15811 		 * fall back to queueing up a delayed retry.
15812 		 */
15813 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15814 			/*
15815 			 * We are at the throttle limit for the target,
15816 			 * fall back to delayed retry.
15817 			 */
15818 			retry_delay = un->un_busy_timeout;
15819 			statp = kstat_waitq_enter;
15820 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15821 			    "sd_retry_command: immed. retry hit "
15822 			    "throttle!\n");
15823 		} else {
15824 			/*
15825 			 * We're clear to proceed with the immediate retry.
15826 			 * First call the user-provided function (if any)
15827 			 */
15828 			if (user_funcp != NULL) {
15829 				(*user_funcp)(un, bp, user_arg,
15830 				    SD_IMMEDIATE_RETRY_ISSUED);
15831 #ifdef __lock_lint
15832 				sd_print_incomplete_msg(un, bp, user_arg,
15833 				    SD_IMMEDIATE_RETRY_ISSUED);
15834 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15835 				    SD_IMMEDIATE_RETRY_ISSUED);
15836 				sd_print_sense_failed_msg(un, bp, user_arg,
15837 				    SD_IMMEDIATE_RETRY_ISSUED);
15838 #endif
15839 			}
15840 
15841 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15842 			    "sd_retry_command: issuing immediate retry\n");
15843 
15844 			/*
15845 			 * Call sd_start_cmds() to transport the command to
15846 			 * the target.
15847 			 */
15848 			sd_start_cmds(un, bp);
15849 
15850 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15851 			    "sd_retry_command exit\n");
15852 			return;
15853 		}
15854 	}
15855 
15856 	/*
15857 	 * Set up to retry the command after a delay.
15858 	 * First call the user-provided function (if any)
15859 	 */
15860 	if (user_funcp != NULL) {
15861 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
15862 	}
15863 
15864 	sd_set_retry_bp(un, bp, retry_delay, statp);
15865 
15866 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15867 	return;
15868 
15869 fail_command:
15870 
15871 	if (user_funcp != NULL) {
15872 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
15873 	}
15874 
15875 fail_command_no_log:
15876 
15877 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15878 	    "sd_retry_command: returning failed command\n");
15879 
15880 	sd_return_failed_command(un, bp, failure_code);
15881 
15882 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15883 }
15884 
15885 
15886 /*
15887  *    Function: sd_set_retry_bp
15888  *
15889  * Description: Set up the given bp for retry.
15890  *
15891  *   Arguments: un - ptr to associated softstate
15892  *		bp - ptr to buf(9S) for the command
15893  *		retry_delay - time interval before issuing retry (may be 0)
15894  *		statp - optional pointer to kstat function
15895  *
15896  *     Context: May be called under interrupt context
15897  */
15898 
15899 static void
15900 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
15901     void (*statp)(kstat_io_t *))
15902 {
15903 	ASSERT(un != NULL);
15904 	ASSERT(mutex_owned(SD_MUTEX(un)));
15905 	ASSERT(bp != NULL);
15906 
15907 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15908 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
15909 
15910 	/*
15911 	 * Indicate that the command is being retried. This will not allow any
15912 	 * other commands on the wait queue to be transported to the target
15913 	 * until this command has been completed (success or failure). The
15914 	 * "retry command" is not transported to the target until the given
15915 	 * time delay expires, unless the user specified a 0 retry_delay.
15916 	 *
15917 	 * Note: the timeout(9F) callback routine is what actually calls
15918 	 * sd_start_cmds() to transport the command, with the exception of a
15919 	 * zero retry_delay. The only current implementor of a zero retry delay
15920 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
15921 	 */
15922 	if (un->un_retry_bp == NULL) {
15923 		ASSERT(un->un_retry_statp == NULL);
15924 		un->un_retry_bp = bp;
15925 
15926 		/*
15927 		 * If the user has not specified a delay the command should
15928 		 * be queued and no timeout should be scheduled.
15929 		 */
15930 		if (retry_delay == 0) {
15931 			/*
15932 			 * Save the kstat pointer that will be used in the
15933 			 * call to SD_UPDATE_KSTATS() below, so that
15934 			 * sd_start_cmds() can correctly decrement the waitq
15935 			 * count when it is time to transport this command.
15936 			 */
15937 			un->un_retry_statp = statp;
15938 			goto done;
15939 		}
15940 	}
15941 
15942 	if (un->un_retry_bp == bp) {
15943 		/*
15944 		 * Save the kstat pointer that will be used in the call to
15945 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
15946 		 * correctly decrement the waitq count when it is time to
15947 		 * transport this command.
15948 		 */
15949 		un->un_retry_statp = statp;
15950 
15951 		/*
15952 		 * Schedule a timeout if:
15953 		 *   1) The user has specified a delay.
15954 		 *   2) There is not a START_STOP_UNIT callback pending.
15955 		 *
15956 		 * If no delay has been specified, then it is up to the caller
15957 		 * to ensure that IO processing continues without stalling.
15958 		 * Effectively, this means that the caller will issue the
15959 		 * required call to sd_start_cmds(). The START_STOP_UNIT
15960 		 * callback does this after the START STOP UNIT command has
15961 		 * completed. In either of these cases we should not schedule
15962 		 * a timeout callback here.  Also don't schedule the timeout if
15963 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
15964 		 */
15965 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
15966 		    (un->un_direct_priority_timeid == NULL)) {
15967 			un->un_retry_timeid =
15968 			    timeout(sd_start_retry_command, un, retry_delay);
15969 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15970 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
15971 			    " bp:0x%p un_retry_timeid:0x%p\n",
15972 			    un, bp, un->un_retry_timeid);
15973 		}
15974 	} else {
15975 		/*
15976 		 * We only get in here if there is already another command
15977 		 * waiting to be retried.  In this case, we just put the
15978 		 * given command onto the wait queue, so it can be transported
15979 		 * after the current retry command has completed.
15980 		 *
15981 		 * Also we have to make sure that if the command at the head
15982 		 * of the wait queue is the un_failfast_bp, that we do not
15983 		 * put ahead of it any other commands that are to be retried.
15984 		 */
15985 		if ((un->un_failfast_bp != NULL) &&
15986 		    (un->un_failfast_bp == un->un_waitq_headp)) {
15987 			/*
15988 			 * Enqueue this command AFTER the first command on
15989 			 * the wait queue (which is also un_failfast_bp).
15990 			 */
15991 			bp->av_forw = un->un_waitq_headp->av_forw;
15992 			un->un_waitq_headp->av_forw = bp;
15993 			if (un->un_waitq_headp == un->un_waitq_tailp) {
15994 				un->un_waitq_tailp = bp;
15995 			}
15996 		} else {
15997 			/* Enqueue this command at the head of the waitq. */
15998 			bp->av_forw = un->un_waitq_headp;
15999 			un->un_waitq_headp = bp;
16000 			if (un->un_waitq_tailp == NULL) {
16001 				un->un_waitq_tailp = bp;
16002 			}
16003 		}
16004 
16005 		if (statp == NULL) {
16006 			statp = kstat_waitq_enter;
16007 		}
16008 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16009 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
16010 	}
16011 
16012 done:
16013 	if (statp != NULL) {
16014 		SD_UPDATE_KSTATS(un, statp, bp);
16015 	}
16016 
16017 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16018 	    "sd_set_retry_bp: exit un:0x%p\n", un);
16019 }
16020 
16021 
16022 /*
16023  *    Function: sd_start_retry_command
16024  *
16025  * Description: Start the command that has been waiting on the target's
16026  *		retry queue.  Called from timeout(9F) context after the
16027  *		retry delay interval has expired.
16028  *
16029  *   Arguments: arg - pointer to associated softstate for the device.
16030  *
16031  *     Context: timeout(9F) thread context.  May not sleep.
16032  */
16033 
16034 static void
16035 sd_start_retry_command(void *arg)
16036 {
16037 	struct sd_lun *un = arg;
16038 
16039 	ASSERT(un != NULL);
16040 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16041 
16042 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16043 	    "sd_start_retry_command: entry\n");
16044 
16045 	mutex_enter(SD_MUTEX(un));
16046 
16047 	un->un_retry_timeid = NULL;
16048 
16049 	if (un->un_retry_bp != NULL) {
16050 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16051 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
16052 		    un, un->un_retry_bp);
16053 		sd_start_cmds(un, un->un_retry_bp);
16054 	}
16055 
16056 	mutex_exit(SD_MUTEX(un));
16057 
16058 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16059 	    "sd_start_retry_command: exit\n");
16060 }
16061 
16062 /*
16063  *    Function: sd_rmw_msg_print_handler
16064  *
16065  * Description: If RMW mode is enabled and warning message is triggered
16066  *              print I/O count during a fixed interval.
16067  *
16068  *   Arguments: arg - pointer to associated softstate for the device.
16069  *
16070  *     Context: timeout(9F) thread context. May not sleep.
16071  */
16072 static void
16073 sd_rmw_msg_print_handler(void *arg)
16074 {
16075 	struct sd_lun *un = arg;
16076 
16077 	ASSERT(un != NULL);
16078 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16079 
16080 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16081 	    "sd_rmw_msg_print_handler: entry\n");
16082 
16083 	mutex_enter(SD_MUTEX(un));
16084 
16085 	if (un->un_rmw_incre_count > 0) {
16086 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16087 		    "%"PRIu64" I/O requests are not aligned with %d disk "
16088 		    "sector size in %ld seconds. They are handled through "
16089 		    "Read Modify Write but the performance is very low!\n",
16090 		    un->un_rmw_incre_count, un->un_tgt_blocksize,
16091 		    drv_hztousec(SD_RMW_MSG_PRINT_TIMEOUT) / 1000000);
16092 		un->un_rmw_incre_count = 0;
16093 		un->un_rmw_msg_timeid = timeout(sd_rmw_msg_print_handler,
16094 		    un, SD_RMW_MSG_PRINT_TIMEOUT);
16095 	} else {
16096 		un->un_rmw_msg_timeid = NULL;
16097 	}
16098 
16099 	mutex_exit(SD_MUTEX(un));
16100 
16101 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16102 	    "sd_rmw_msg_print_handler: exit\n");
16103 }
16104 
16105 /*
16106  *    Function: sd_start_direct_priority_command
16107  *
16108  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
16109  *		received TRAN_BUSY when we called scsi_transport() to send it
16110  *		to the underlying HBA. This function is called from timeout(9F)
16111  *		context after the delay interval has expired.
16112  *
16113  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
16114  *
16115  *     Context: timeout(9F) thread context.  May not sleep.
16116  */
16117 
16118 static void
16119 sd_start_direct_priority_command(void *arg)
16120 {
16121 	struct buf	*priority_bp = arg;
16122 	struct sd_lun	*un;
16123 
16124 	ASSERT(priority_bp != NULL);
16125 	un = SD_GET_UN(priority_bp);
16126 	ASSERT(un != NULL);
16127 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16128 
16129 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16130 	    "sd_start_direct_priority_command: entry\n");
16131 
16132 	mutex_enter(SD_MUTEX(un));
16133 	un->un_direct_priority_timeid = NULL;
16134 	sd_start_cmds(un, priority_bp);
16135 	mutex_exit(SD_MUTEX(un));
16136 
16137 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16138 	    "sd_start_direct_priority_command: exit\n");
16139 }
16140 
16141 
16142 /*
16143  *    Function: sd_send_request_sense_command
16144  *
16145  * Description: Sends a REQUEST SENSE command to the target
16146  *
16147  *     Context: May be called from interrupt context.
16148  */
16149 
16150 static void
16151 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
16152     struct scsi_pkt *pktp)
16153 {
16154 	ASSERT(bp != NULL);
16155 	ASSERT(un != NULL);
16156 	ASSERT(mutex_owned(SD_MUTEX(un)));
16157 
16158 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
16159 	    "entry: buf:0x%p\n", bp);
16160 
16161 	/*
16162 	 * If we are syncing or dumping, then fail the command to avoid a
16163 	 * recursive callback into scsi_transport(). Also fail the command
16164 	 * if we are suspended (legacy behavior).
16165 	 */
16166 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
16167 	    (un->un_state == SD_STATE_DUMPING)) {
16168 		sd_return_failed_command(un, bp, EIO);
16169 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16170 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
16171 		return;
16172 	}
16173 
16174 	/*
16175 	 * Retry the failed command and don't issue the request sense if:
16176 	 *    1) the sense buf is busy
16177 	 *    2) we have 1 or more outstanding commands on the target
16178 	 *    (the sense data will be cleared or invalidated any way)
16179 	 *
16180 	 * Note: There could be an issue with not checking a retry limit here,
16181 	 * the problem is determining which retry limit to check.
16182 	 */
16183 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
16184 		/* Don't retry if the command is flagged as non-retryable */
16185 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16186 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
16187 			    NULL, NULL, 0, un->un_busy_timeout,
16188 			    kstat_waitq_enter);
16189 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16190 			    "sd_send_request_sense_command: "
16191 			    "at full throttle, retrying exit\n");
16192 		} else {
16193 			sd_return_failed_command(un, bp, EIO);
16194 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16195 			    "sd_send_request_sense_command: "
16196 			    "at full throttle, non-retryable exit\n");
16197 		}
16198 		return;
16199 	}
16200 
16201 	sd_mark_rqs_busy(un, bp);
16202 	sd_start_cmds(un, un->un_rqs_bp);
16203 
16204 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16205 	    "sd_send_request_sense_command: exit\n");
16206 }
16207 
16208 
16209 /*
16210  *    Function: sd_mark_rqs_busy
16211  *
16212  * Description: Indicate that the request sense bp for this instance is
16213  *		in use.
16214  *
16215  *     Context: May be called under interrupt context
16216  */
16217 
16218 static void
16219 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
16220 {
16221 	struct sd_xbuf	*sense_xp;
16222 
16223 	ASSERT(un != NULL);
16224 	ASSERT(bp != NULL);
16225 	ASSERT(mutex_owned(SD_MUTEX(un)));
16226 	ASSERT(un->un_sense_isbusy == 0);
16227 
16228 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
16229 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
16230 
16231 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
16232 	ASSERT(sense_xp != NULL);
16233 
16234 	SD_INFO(SD_LOG_IO, un,
16235 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
16236 
16237 	ASSERT(sense_xp->xb_pktp != NULL);
16238 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
16239 	    == (FLAG_SENSING | FLAG_HEAD));
16240 
16241 	un->un_sense_isbusy = 1;
16242 	un->un_rqs_bp->b_resid = 0;
16243 	sense_xp->xb_pktp->pkt_resid  = 0;
16244 	sense_xp->xb_pktp->pkt_reason = 0;
16245 
16246 	/* So we can get back the bp at interrupt time! */
16247 	sense_xp->xb_sense_bp = bp;
16248 
16249 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
16250 
16251 	/*
16252 	 * Mark this buf as awaiting sense data. (This is already set in
16253 	 * the pkt_flags for the RQS packet.)
16254 	 */
16255 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
16256 
16257 	/* Request sense down same path */
16258 	if (scsi_pkt_allocated_correctly((SD_GET_XBUF(bp))->xb_pktp) &&
16259 	    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance)
16260 		sense_xp->xb_pktp->pkt_path_instance =
16261 		    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance;
16262 
16263 	sense_xp->xb_retry_count = 0;
16264 	sense_xp->xb_victim_retry_count = 0;
16265 	sense_xp->xb_ua_retry_count = 0;
16266 	sense_xp->xb_nr_retry_count = 0;
16267 	sense_xp->xb_dma_resid  = 0;
16268 
16269 	/* Clean up the fields for auto-request sense */
16270 	sense_xp->xb_sense_status = 0;
16271 	sense_xp->xb_sense_state = 0;
16272 	sense_xp->xb_sense_resid = 0;
16273 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
16274 
16275 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
16276 }
16277 
16278 
16279 /*
16280  *    Function: sd_mark_rqs_idle
16281  *
16282  * Description: SD_MUTEX must be held continuously through this routine
16283  *		to prevent reuse of the rqs struct before the caller can
16284  *		complete it's processing.
16285  *
16286  * Return Code: Pointer to the RQS buf
16287  *
16288  *     Context: May be called under interrupt context
16289  */
16290 
16291 static struct buf *
16292 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
16293 {
16294 	struct buf *bp;
16295 	ASSERT(un != NULL);
16296 	ASSERT(sense_xp != NULL);
16297 	ASSERT(mutex_owned(SD_MUTEX(un)));
16298 	ASSERT(un->un_sense_isbusy != 0);
16299 
16300 	un->un_sense_isbusy = 0;
16301 	bp = sense_xp->xb_sense_bp;
16302 	sense_xp->xb_sense_bp = NULL;
16303 
16304 	/* This pkt is no longer interested in getting sense data */
16305 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
16306 
16307 	return (bp);
16308 }
16309 
16310 
16311 
16312 /*
16313  *    Function: sd_alloc_rqs
16314  *
16315  * Description: Set up the unit to receive auto request sense data
16316  *
16317  * Return Code: DDI_SUCCESS or DDI_FAILURE
16318  *
16319  *     Context: Called under attach(9E) context
16320  */
16321 
16322 static int
16323 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
16324 {
16325 	struct sd_xbuf *xp;
16326 
16327 	ASSERT(un != NULL);
16328 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16329 	ASSERT(un->un_rqs_bp == NULL);
16330 	ASSERT(un->un_rqs_pktp == NULL);
16331 
16332 	/*
16333 	 * First allocate the required buf and scsi_pkt structs, then set up
16334 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
16335 	 */
16336 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
16337 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
16338 	if (un->un_rqs_bp == NULL) {
16339 		return (DDI_FAILURE);
16340 	}
16341 
16342 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
16343 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
16344 
16345 	if (un->un_rqs_pktp == NULL) {
16346 		sd_free_rqs(un);
16347 		return (DDI_FAILURE);
16348 	}
16349 
16350 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
16351 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
16352 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
16353 
16354 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
16355 
16356 	/* Set up the other needed members in the ARQ scsi_pkt. */
16357 	un->un_rqs_pktp->pkt_comp   = sdintr;
16358 	un->un_rqs_pktp->pkt_time   = sd_io_time;
16359 	un->un_rqs_pktp->pkt_flags |=
16360 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
16361 
16362 	/*
16363 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
16364 	 * provide any intpkt, destroypkt routines as we take care of
16365 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
16366 	 */
16367 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
16368 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
16369 	xp->xb_pktp = un->un_rqs_pktp;
16370 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
16371 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
16372 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
16373 
16374 	/*
16375 	 * Save the pointer to the request sense private bp so it can
16376 	 * be retrieved in sdintr.
16377 	 */
16378 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
16379 	ASSERT(un->un_rqs_bp->b_private == xp);
16380 
16381 	/*
16382 	 * See if the HBA supports auto-request sense for the specified
16383 	 * target/lun. If it does, then try to enable it (if not already
16384 	 * enabled).
16385 	 *
16386 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
16387 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
16388 	 * return success.  However, in both of these cases ARQ is always
16389 	 * enabled and scsi_ifgetcap will always return true. The best approach
16390 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
16391 	 *
16392 	 * The 3rd case is the HBA (adp) always return enabled on
16393 	 * scsi_ifgetgetcap even when it's not enable, the best approach
16394 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
16395 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
16396 	 */
16397 
16398 	if (un->un_f_is_fibre == TRUE) {
16399 		un->un_f_arq_enabled = TRUE;
16400 	} else {
16401 #if defined(__x86)
16402 		/*
16403 		 * Circumvent the Adaptec bug, remove this code when
16404 		 * the bug is fixed
16405 		 */
16406 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
16407 #endif
16408 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
16409 		case 0:
16410 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16411 			    "sd_alloc_rqs: HBA supports ARQ\n");
16412 			/*
16413 			 * ARQ is supported by this HBA but currently is not
16414 			 * enabled. Attempt to enable it and if successful then
16415 			 * mark this instance as ARQ enabled.
16416 			 */
16417 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
16418 			    == 1) {
16419 				/* Successfully enabled ARQ in the HBA */
16420 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16421 				    "sd_alloc_rqs: ARQ enabled\n");
16422 				un->un_f_arq_enabled = TRUE;
16423 			} else {
16424 				/* Could not enable ARQ in the HBA */
16425 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16426 				    "sd_alloc_rqs: failed ARQ enable\n");
16427 				un->un_f_arq_enabled = FALSE;
16428 			}
16429 			break;
16430 		case 1:
16431 			/*
16432 			 * ARQ is supported by this HBA and is already enabled.
16433 			 * Just mark ARQ as enabled for this instance.
16434 			 */
16435 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16436 			    "sd_alloc_rqs: ARQ already enabled\n");
16437 			un->un_f_arq_enabled = TRUE;
16438 			break;
16439 		default:
16440 			/*
16441 			 * ARQ is not supported by this HBA; disable it for this
16442 			 * instance.
16443 			 */
16444 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16445 			    "sd_alloc_rqs: HBA does not support ARQ\n");
16446 			un->un_f_arq_enabled = FALSE;
16447 			break;
16448 		}
16449 	}
16450 
16451 	return (DDI_SUCCESS);
16452 }
16453 
16454 
16455 /*
16456  *    Function: sd_free_rqs
16457  *
16458  * Description: Cleanup for the pre-instance RQS command.
16459  *
16460  *     Context: Kernel thread context
16461  */
16462 
16463 static void
16464 sd_free_rqs(struct sd_lun *un)
16465 {
16466 	ASSERT(un != NULL);
16467 
16468 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
16469 
16470 	/*
16471 	 * If consistent memory is bound to a scsi_pkt, the pkt
16472 	 * has to be destroyed *before* freeing the consistent memory.
16473 	 * Don't change the sequence of this operations.
16474 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
16475 	 * after it was freed in scsi_free_consistent_buf().
16476 	 */
16477 	if (un->un_rqs_pktp != NULL) {
16478 		scsi_destroy_pkt(un->un_rqs_pktp);
16479 		un->un_rqs_pktp = NULL;
16480 	}
16481 
16482 	if (un->un_rqs_bp != NULL) {
16483 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
16484 		if (xp != NULL) {
16485 			kmem_free(xp, sizeof (struct sd_xbuf));
16486 		}
16487 		scsi_free_consistent_buf(un->un_rqs_bp);
16488 		un->un_rqs_bp = NULL;
16489 	}
16490 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
16491 }
16492 
16493 
16494 
16495 /*
16496  *    Function: sd_reduce_throttle
16497  *
16498  * Description: Reduces the maximum # of outstanding commands on a
16499  *		target to the current number of outstanding commands.
16500  *		Queues a tiemout(9F) callback to restore the limit
16501  *		after a specified interval has elapsed.
16502  *		Typically used when we get a TRAN_BUSY return code
16503  *		back from scsi_transport().
16504  *
16505  *   Arguments: un - ptr to the sd_lun softstate struct
16506  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
16507  *
16508  *     Context: May be called from interrupt context
16509  */
16510 
16511 static void
16512 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
16513 {
16514 	ASSERT(un != NULL);
16515 	ASSERT(mutex_owned(SD_MUTEX(un)));
16516 	ASSERT(un->un_ncmds_in_transport >= 0);
16517 
16518 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16519 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
16520 	    un, un->un_throttle, un->un_ncmds_in_transport);
16521 
16522 	if (un->un_throttle > 1) {
16523 		if (un->un_f_use_adaptive_throttle == TRUE) {
16524 			switch (throttle_type) {
16525 			case SD_THROTTLE_TRAN_BUSY:
16526 				if (un->un_busy_throttle == 0) {
16527 					un->un_busy_throttle = un->un_throttle;
16528 				}
16529 				break;
16530 			case SD_THROTTLE_QFULL:
16531 				un->un_busy_throttle = 0;
16532 				break;
16533 			default:
16534 				ASSERT(FALSE);
16535 			}
16536 
16537 			if (un->un_ncmds_in_transport > 0) {
16538 				un->un_throttle = un->un_ncmds_in_transport;
16539 			}
16540 
16541 		} else {
16542 			if (un->un_ncmds_in_transport == 0) {
16543 				un->un_throttle = 1;
16544 			} else {
16545 				un->un_throttle = un->un_ncmds_in_transport;
16546 			}
16547 		}
16548 	}
16549 
16550 	/* Reschedule the timeout if none is currently active */
16551 	if (un->un_reset_throttle_timeid == NULL) {
16552 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
16553 		    un, SD_THROTTLE_RESET_INTERVAL);
16554 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16555 		    "sd_reduce_throttle: timeout scheduled!\n");
16556 	}
16557 
16558 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16559 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16560 }
16561 
16562 
16563 
16564 /*
16565  *    Function: sd_restore_throttle
16566  *
16567  * Description: Callback function for timeout(9F).  Resets the current
16568  *		value of un->un_throttle to its default.
16569  *
16570  *   Arguments: arg - pointer to associated softstate for the device.
16571  *
16572  *     Context: May be called from interrupt context
16573  */
16574 
16575 static void
16576 sd_restore_throttle(void *arg)
16577 {
16578 	struct sd_lun	*un = arg;
16579 
16580 	ASSERT(un != NULL);
16581 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16582 
16583 	mutex_enter(SD_MUTEX(un));
16584 
16585 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16586 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16587 
16588 	un->un_reset_throttle_timeid = NULL;
16589 
16590 	if (un->un_f_use_adaptive_throttle == TRUE) {
16591 		/*
16592 		 * If un_busy_throttle is nonzero, then it contains the
16593 		 * value that un_throttle was when we got a TRAN_BUSY back
16594 		 * from scsi_transport(). We want to revert back to this
16595 		 * value.
16596 		 *
16597 		 * In the QFULL case, the throttle limit will incrementally
16598 		 * increase until it reaches max throttle.
16599 		 */
16600 		if (un->un_busy_throttle > 0) {
16601 			un->un_throttle = un->un_busy_throttle;
16602 			un->un_busy_throttle = 0;
16603 		} else {
16604 			/*
16605 			 * increase throttle by 10% open gate slowly, schedule
16606 			 * another restore if saved throttle has not been
16607 			 * reached
16608 			 */
16609 			short throttle;
16610 			if (sd_qfull_throttle_enable) {
16611 				throttle = un->un_throttle +
16612 				    max((un->un_throttle / 10), 1);
16613 				un->un_throttle =
16614 				    (throttle < un->un_saved_throttle) ?
16615 				    throttle : un->un_saved_throttle;
16616 				if (un->un_throttle < un->un_saved_throttle) {
16617 					un->un_reset_throttle_timeid =
16618 					    timeout(sd_restore_throttle,
16619 					    un,
16620 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
16621 				}
16622 			}
16623 		}
16624 
16625 		/*
16626 		 * If un_throttle has fallen below the low-water mark, we
16627 		 * restore the maximum value here (and allow it to ratchet
16628 		 * down again if necessary).
16629 		 */
16630 		if (un->un_throttle < un->un_min_throttle) {
16631 			un->un_throttle = un->un_saved_throttle;
16632 		}
16633 	} else {
16634 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16635 		    "restoring limit from 0x%x to 0x%x\n",
16636 		    un->un_throttle, un->un_saved_throttle);
16637 		un->un_throttle = un->un_saved_throttle;
16638 	}
16639 
16640 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16641 	    "sd_restore_throttle: calling sd_start_cmds!\n");
16642 
16643 	sd_start_cmds(un, NULL);
16644 
16645 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16646 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
16647 	    un, un->un_throttle);
16648 
16649 	mutex_exit(SD_MUTEX(un));
16650 
16651 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16652 }
16653 
16654 /*
16655  *    Function: sdrunout
16656  *
16657  * Description: Callback routine for scsi_init_pkt when a resource allocation
16658  *		fails.
16659  *
16660  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16661  *		soft state instance.
16662  *
16663  * Return Code: The scsi_init_pkt routine allows for the callback function to
16664  *		return a 0 indicating the callback should be rescheduled or a 1
16665  *		indicating not to reschedule. This routine always returns 1
16666  *		because the driver always provides a callback function to
16667  *		scsi_init_pkt. This results in a callback always being scheduled
16668  *		(via the scsi_init_pkt callback implementation) if a resource
16669  *		failure occurs.
16670  *
16671  *     Context: This callback function may not block or call routines that block
16672  *
16673  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16674  *		request persisting at the head of the list which cannot be
16675  *		satisfied even after multiple retries. In the future the driver
16676  *		may implement some time of maximum runout count before failing
16677  *		an I/O.
16678  */
16679 
16680 static int
16681 sdrunout(caddr_t arg)
16682 {
16683 	struct sd_lun	*un = (struct sd_lun *)arg;
16684 
16685 	ASSERT(un != NULL);
16686 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16687 
16688 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16689 
16690 	mutex_enter(SD_MUTEX(un));
16691 	sd_start_cmds(un, NULL);
16692 	mutex_exit(SD_MUTEX(un));
16693 	/*
16694 	 * This callback routine always returns 1 (i.e. do not reschedule)
16695 	 * because we always specify sdrunout as the callback handler for
16696 	 * scsi_init_pkt inside the call to sd_start_cmds.
16697 	 */
16698 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16699 	return (1);
16700 }
16701 
16702 
16703 /*
16704  *    Function: sdintr
16705  *
16706  * Description: Completion callback routine for scsi_pkt(9S) structs
16707  *		sent to the HBA driver via scsi_transport(9F).
16708  *
16709  *     Context: Interrupt context
16710  */
16711 
16712 static void
16713 sdintr(struct scsi_pkt *pktp)
16714 {
16715 	struct buf	*bp;
16716 	struct sd_xbuf	*xp;
16717 	struct sd_lun	*un;
16718 	size_t		actual_len;
16719 	sd_ssc_t	*sscp;
16720 
16721 	ASSERT(pktp != NULL);
16722 	bp = (struct buf *)pktp->pkt_private;
16723 	ASSERT(bp != NULL);
16724 	xp = SD_GET_XBUF(bp);
16725 	ASSERT(xp != NULL);
16726 	ASSERT(xp->xb_pktp != NULL);
16727 	un = SD_GET_UN(bp);
16728 	ASSERT(un != NULL);
16729 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16730 
16731 #ifdef SD_FAULT_INJECTION
16732 
16733 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16734 	/* SD FaultInjection */
16735 	sd_faultinjection(pktp);
16736 
16737 #endif /* SD_FAULT_INJECTION */
16738 
16739 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16740 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16741 
16742 	mutex_enter(SD_MUTEX(un));
16743 
16744 	ASSERT(un->un_fm_private != NULL);
16745 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16746 	ASSERT(sscp != NULL);
16747 
16748 	/* Reduce the count of the #commands currently in transport */
16749 	un->un_ncmds_in_transport--;
16750 	ASSERT(un->un_ncmds_in_transport >= 0);
16751 
16752 	/* Increment counter to indicate that the callback routine is active */
16753 	un->un_in_callback++;
16754 
16755 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16756 
16757 #ifdef	SDDEBUG
16758 	if (bp == un->un_retry_bp) {
16759 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16760 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16761 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16762 	}
16763 #endif
16764 
16765 	/*
16766 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
16767 	 * state if needed.
16768 	 */
16769 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16770 		/* Prevent multiple console messages for the same failure. */
16771 		if (un->un_last_pkt_reason != CMD_DEV_GONE) {
16772 			un->un_last_pkt_reason = CMD_DEV_GONE;
16773 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16774 			    "Command failed to complete...Device is gone\n");
16775 		}
16776 		if (un->un_mediastate != DKIO_DEV_GONE) {
16777 			un->un_mediastate = DKIO_DEV_GONE;
16778 			cv_broadcast(&un->un_state_cv);
16779 		}
16780 		/*
16781 		 * If the command happens to be the REQUEST SENSE command,
16782 		 * free up the rqs buf and fail the original command.
16783 		 */
16784 		if (bp == un->un_rqs_bp) {
16785 			bp = sd_mark_rqs_idle(un, xp);
16786 		}
16787 		sd_return_failed_command(un, bp, EIO);
16788 		goto exit;
16789 	}
16790 
16791 	if (pktp->pkt_state & STATE_XARQ_DONE) {
16792 		SD_TRACE(SD_LOG_COMMON, un,
16793 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
16794 	}
16795 
16796 	/*
16797 	 * First see if the pkt has auto-request sense data with it....
16798 	 * Look at the packet state first so we don't take a performance
16799 	 * hit looking at the arq enabled flag unless absolutely necessary.
16800 	 */
16801 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16802 	    (un->un_f_arq_enabled == TRUE)) {
16803 		/*
16804 		 * The HBA did an auto request sense for this command so check
16805 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16806 		 * driver command that should not be retried.
16807 		 */
16808 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16809 			/*
16810 			 * Save the relevant sense info into the xp for the
16811 			 * original cmd.
16812 			 */
16813 			struct scsi_arq_status *asp;
16814 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16815 			xp->xb_sense_status =
16816 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16817 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16818 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16819 			if (pktp->pkt_state & STATE_XARQ_DONE) {
16820 				actual_len = MAX_SENSE_LENGTH -
16821 				    xp->xb_sense_resid;
16822 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16823 				    MAX_SENSE_LENGTH);
16824 			} else {
16825 				if (xp->xb_sense_resid > SENSE_LENGTH) {
16826 					actual_len = MAX_SENSE_LENGTH -
16827 					    xp->xb_sense_resid;
16828 				} else {
16829 					actual_len = SENSE_LENGTH -
16830 					    xp->xb_sense_resid;
16831 				}
16832 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16833 					if ((((struct uscsi_cmd *)
16834 					    (xp->xb_pktinfo))->uscsi_rqlen) >
16835 					    actual_len) {
16836 						xp->xb_sense_resid =
16837 						    (((struct uscsi_cmd *)
16838 						    (xp->xb_pktinfo))->
16839 						    uscsi_rqlen) - actual_len;
16840 					} else {
16841 						xp->xb_sense_resid = 0;
16842 					}
16843 				}
16844 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16845 				    SENSE_LENGTH);
16846 			}
16847 
16848 			/* fail the command */
16849 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16850 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
16851 			sd_return_failed_command(un, bp, EIO);
16852 			goto exit;
16853 		}
16854 
16855 #if (defined(__x86))	/* DMAFREE for x86 only */
16856 		/*
16857 		 * We want to either retry or fail this command, so free
16858 		 * the DMA resources here.  If we retry the command then
16859 		 * the DMA resources will be reallocated in sd_start_cmds().
16860 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
16861 		 * causes the *entire* transfer to start over again from the
16862 		 * beginning of the request, even for PARTIAL chunks that
16863 		 * have already transferred successfully.
16864 		 */
16865 		if ((un->un_f_is_fibre == TRUE) &&
16866 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16867 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16868 			scsi_dmafree(pktp);
16869 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16870 		}
16871 #endif
16872 
16873 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16874 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
16875 
16876 		sd_handle_auto_request_sense(un, bp, xp, pktp);
16877 		goto exit;
16878 	}
16879 
16880 	/* Next see if this is the REQUEST SENSE pkt for the instance */
16881 	if (pktp->pkt_flags & FLAG_SENSING)  {
16882 		/* This pktp is from the unit's REQUEST_SENSE command */
16883 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16884 		    "sdintr: sd_handle_request_sense\n");
16885 		sd_handle_request_sense(un, bp, xp, pktp);
16886 		goto exit;
16887 	}
16888 
16889 	/*
16890 	 * Check to see if the command successfully completed as requested;
16891 	 * this is the most common case (and also the hot performance path).
16892 	 *
16893 	 * Requirements for successful completion are:
16894 	 * pkt_reason is CMD_CMPLT and packet status is status good.
16895 	 * In addition:
16896 	 * - A residual of zero indicates successful completion no matter what
16897 	 *   the command is.
16898 	 * - If the residual is not zero and the command is not a read or
16899 	 *   write, then it's still defined as successful completion. In other
16900 	 *   words, if the command is a read or write the residual must be
16901 	 *   zero for successful completion.
16902 	 * - If the residual is not zero and the command is a read or
16903 	 *   write, and it's a USCSICMD, then it's still defined as
16904 	 *   successful completion.
16905 	 */
16906 	if ((pktp->pkt_reason == CMD_CMPLT) &&
16907 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
16908 
16909 		/*
16910 		 * Since this command is returned with a good status, we
16911 		 * can reset the count for Sonoma failover.
16912 		 */
16913 		un->un_sonoma_failure_count = 0;
16914 
16915 		/*
16916 		 * Return all USCSI commands on good status
16917 		 */
16918 		if (pktp->pkt_resid == 0) {
16919 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16920 			    "sdintr: returning command for resid == 0\n");
16921 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
16922 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
16923 			SD_UPDATE_B_RESID(bp, pktp);
16924 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16925 			    "sdintr: returning command for resid != 0\n");
16926 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16927 			SD_UPDATE_B_RESID(bp, pktp);
16928 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16929 			    "sdintr: returning uscsi command\n");
16930 		} else {
16931 			goto not_successful;
16932 		}
16933 		sd_return_command(un, bp);
16934 
16935 		/*
16936 		 * Decrement counter to indicate that the callback routine
16937 		 * is done.
16938 		 */
16939 		un->un_in_callback--;
16940 		ASSERT(un->un_in_callback >= 0);
16941 		mutex_exit(SD_MUTEX(un));
16942 
16943 		return;
16944 	}
16945 
16946 not_successful:
16947 
16948 #if (defined(__x86))	/* DMAFREE for x86 only */
16949 	/*
16950 	 * The following is based upon knowledge of the underlying transport
16951 	 * and its use of DMA resources.  This code should be removed when
16952 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
16953 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
16954 	 * and sd_start_cmds().
16955 	 *
16956 	 * Free any DMA resources associated with this command if there
16957 	 * is a chance it could be retried or enqueued for later retry.
16958 	 * If we keep the DMA binding then mpxio cannot reissue the
16959 	 * command on another path whenever a path failure occurs.
16960 	 *
16961 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
16962 	 * causes the *entire* transfer to start over again from the
16963 	 * beginning of the request, even for PARTIAL chunks that
16964 	 * have already transferred successfully.
16965 	 *
16966 	 * This is only done for non-uscsi commands (and also skipped for the
16967 	 * driver's internal RQS command). Also just do this for Fibre Channel
16968 	 * devices as these are the only ones that support mpxio.
16969 	 */
16970 	if ((un->un_f_is_fibre == TRUE) &&
16971 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16972 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16973 		scsi_dmafree(pktp);
16974 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16975 	}
16976 #endif
16977 
16978 	/*
16979 	 * The command did not successfully complete as requested so check
16980 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16981 	 * driver command that should not be retried so just return. If
16982 	 * FLAG_DIAGNOSE is not set the error will be processed below.
16983 	 */
16984 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16985 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16986 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
16987 		/*
16988 		 * Issue a request sense if a check condition caused the error
16989 		 * (we handle the auto request sense case above), otherwise
16990 		 * just fail the command.
16991 		 */
16992 		if ((pktp->pkt_reason == CMD_CMPLT) &&
16993 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
16994 			sd_send_request_sense_command(un, bp, pktp);
16995 		} else {
16996 			sd_return_failed_command(un, bp, EIO);
16997 		}
16998 		goto exit;
16999 	}
17000 
17001 	/*
17002 	 * The command did not successfully complete as requested so process
17003 	 * the error, retry, and/or attempt recovery.
17004 	 */
17005 	switch (pktp->pkt_reason) {
17006 	case CMD_CMPLT:
17007 		switch (SD_GET_PKT_STATUS(pktp)) {
17008 		case STATUS_GOOD:
17009 			/*
17010 			 * The command completed successfully with a non-zero
17011 			 * residual
17012 			 */
17013 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17014 			    "sdintr: STATUS_GOOD \n");
17015 			sd_pkt_status_good(un, bp, xp, pktp);
17016 			break;
17017 
17018 		case STATUS_CHECK:
17019 		case STATUS_TERMINATED:
17020 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17021 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
17022 			sd_pkt_status_check_condition(un, bp, xp, pktp);
17023 			break;
17024 
17025 		case STATUS_BUSY:
17026 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17027 			    "sdintr: STATUS_BUSY\n");
17028 			sd_pkt_status_busy(un, bp, xp, pktp);
17029 			break;
17030 
17031 		case STATUS_RESERVATION_CONFLICT:
17032 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17033 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
17034 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17035 			break;
17036 
17037 		case STATUS_QFULL:
17038 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17039 			    "sdintr: STATUS_QFULL\n");
17040 			sd_pkt_status_qfull(un, bp, xp, pktp);
17041 			break;
17042 
17043 		case STATUS_MET:
17044 		case STATUS_INTERMEDIATE:
17045 		case STATUS_SCSI2:
17046 		case STATUS_INTERMEDIATE_MET:
17047 		case STATUS_ACA_ACTIVE:
17048 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17049 			    "Unexpected SCSI status received: 0x%x\n",
17050 			    SD_GET_PKT_STATUS(pktp));
17051 			/*
17052 			 * Mark the ssc_flags when detected invalid status
17053 			 * code for non-USCSI command.
17054 			 */
17055 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17056 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17057 				    0, "stat-code");
17058 			}
17059 			sd_return_failed_command(un, bp, EIO);
17060 			break;
17061 
17062 		default:
17063 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17064 			    "Invalid SCSI status received: 0x%x\n",
17065 			    SD_GET_PKT_STATUS(pktp));
17066 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17067 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17068 				    0, "stat-code");
17069 			}
17070 			sd_return_failed_command(un, bp, EIO);
17071 			break;
17072 
17073 		}
17074 		break;
17075 
17076 	case CMD_INCOMPLETE:
17077 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17078 		    "sdintr:  CMD_INCOMPLETE\n");
17079 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
17080 		break;
17081 	case CMD_TRAN_ERR:
17082 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17083 		    "sdintr: CMD_TRAN_ERR\n");
17084 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
17085 		break;
17086 	case CMD_RESET:
17087 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17088 		    "sdintr: CMD_RESET \n");
17089 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
17090 		break;
17091 	case CMD_ABORTED:
17092 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17093 		    "sdintr: CMD_ABORTED \n");
17094 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
17095 		break;
17096 	case CMD_TIMEOUT:
17097 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17098 		    "sdintr: CMD_TIMEOUT\n");
17099 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
17100 		break;
17101 	case CMD_UNX_BUS_FREE:
17102 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17103 		    "sdintr: CMD_UNX_BUS_FREE \n");
17104 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
17105 		break;
17106 	case CMD_TAG_REJECT:
17107 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17108 		    "sdintr: CMD_TAG_REJECT\n");
17109 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
17110 		break;
17111 	default:
17112 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17113 		    "sdintr: default\n");
17114 		/*
17115 		 * Mark the ssc_flags for detecting invliad pkt_reason.
17116 		 */
17117 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17118 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_PKT_REASON,
17119 			    0, "pkt-reason");
17120 		}
17121 		sd_pkt_reason_default(un, bp, xp, pktp);
17122 		break;
17123 	}
17124 
17125 exit:
17126 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
17127 
17128 	/* Decrement counter to indicate that the callback routine is done. */
17129 	un->un_in_callback--;
17130 	ASSERT(un->un_in_callback >= 0);
17131 
17132 	/*
17133 	 * At this point, the pkt has been dispatched, ie, it is either
17134 	 * being re-tried or has been returned to its caller and should
17135 	 * not be referenced.
17136 	 */
17137 
17138 	mutex_exit(SD_MUTEX(un));
17139 }
17140 
17141 
17142 /*
17143  *    Function: sd_print_incomplete_msg
17144  *
17145  * Description: Prints the error message for a CMD_INCOMPLETE error.
17146  *
17147  *   Arguments: un - ptr to associated softstate for the device.
17148  *		bp - ptr to the buf(9S) for the command.
17149  *		arg - message string ptr
17150  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
17151  *			or SD_NO_RETRY_ISSUED.
17152  *
17153  *     Context: May be called under interrupt context
17154  */
17155 
17156 static void
17157 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17158 {
17159 	struct scsi_pkt	*pktp;
17160 	char	*msgp;
17161 	char	*cmdp = arg;
17162 
17163 	ASSERT(un != NULL);
17164 	ASSERT(mutex_owned(SD_MUTEX(un)));
17165 	ASSERT(bp != NULL);
17166 	ASSERT(arg != NULL);
17167 	pktp = SD_GET_PKTP(bp);
17168 	ASSERT(pktp != NULL);
17169 
17170 	switch (code) {
17171 	case SD_DELAYED_RETRY_ISSUED:
17172 	case SD_IMMEDIATE_RETRY_ISSUED:
17173 		msgp = "retrying";
17174 		break;
17175 	case SD_NO_RETRY_ISSUED:
17176 	default:
17177 		msgp = "giving up";
17178 		break;
17179 	}
17180 
17181 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17182 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17183 		    "incomplete %s- %s\n", cmdp, msgp);
17184 	}
17185 }
17186 
17187 
17188 
17189 /*
17190  *    Function: sd_pkt_status_good
17191  *
17192  * Description: Processing for a STATUS_GOOD code in pkt_status.
17193  *
17194  *     Context: May be called under interrupt context
17195  */
17196 
17197 static void
17198 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
17199     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17200 {
17201 	char	*cmdp;
17202 
17203 	ASSERT(un != NULL);
17204 	ASSERT(mutex_owned(SD_MUTEX(un)));
17205 	ASSERT(bp != NULL);
17206 	ASSERT(xp != NULL);
17207 	ASSERT(pktp != NULL);
17208 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
17209 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
17210 	ASSERT(pktp->pkt_resid != 0);
17211 
17212 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
17213 
17214 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17215 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
17216 	case SCMD_READ:
17217 		cmdp = "read";
17218 		break;
17219 	case SCMD_WRITE:
17220 		cmdp = "write";
17221 		break;
17222 	default:
17223 		SD_UPDATE_B_RESID(bp, pktp);
17224 		sd_return_command(un, bp);
17225 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17226 		return;
17227 	}
17228 
17229 	/*
17230 	 * See if we can retry the read/write, preferrably immediately.
17231 	 * If retries are exhaused, then sd_retry_command() will update
17232 	 * the b_resid count.
17233 	 */
17234 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
17235 	    cmdp, EIO, (clock_t)0, NULL);
17236 
17237 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17238 }
17239 
17240 
17241 
17242 
17243 
17244 /*
17245  *    Function: sd_handle_request_sense
17246  *
17247  * Description: Processing for non-auto Request Sense command.
17248  *
17249  *   Arguments: un - ptr to associated softstate
17250  *		sense_bp - ptr to buf(9S) for the RQS command
17251  *		sense_xp - ptr to the sd_xbuf for the RQS command
17252  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
17253  *
17254  *     Context: May be called under interrupt context
17255  */
17256 
17257 static void
17258 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
17259     struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
17260 {
17261 	struct buf	*cmd_bp;	/* buf for the original command */
17262 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
17263 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
17264 	size_t		actual_len;	/* actual sense data length */
17265 
17266 	ASSERT(un != NULL);
17267 	ASSERT(mutex_owned(SD_MUTEX(un)));
17268 	ASSERT(sense_bp != NULL);
17269 	ASSERT(sense_xp != NULL);
17270 	ASSERT(sense_pktp != NULL);
17271 
17272 	/*
17273 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
17274 	 * RQS command and not the original command.
17275 	 */
17276 	ASSERT(sense_pktp == un->un_rqs_pktp);
17277 	ASSERT(sense_bp   == un->un_rqs_bp);
17278 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
17279 	    (FLAG_SENSING | FLAG_HEAD));
17280 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
17281 	    FLAG_SENSING) == FLAG_SENSING);
17282 
17283 	/* These are the bp, xp, and pktp for the original command */
17284 	cmd_bp = sense_xp->xb_sense_bp;
17285 	cmd_xp = SD_GET_XBUF(cmd_bp);
17286 	cmd_pktp = SD_GET_PKTP(cmd_bp);
17287 
17288 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
17289 		/*
17290 		 * The REQUEST SENSE command failed.  Release the REQUEST
17291 		 * SENSE command for re-use, get back the bp for the original
17292 		 * command, and attempt to re-try the original command if
17293 		 * FLAG_DIAGNOSE is not set in the original packet.
17294 		 */
17295 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17296 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17297 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
17298 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
17299 			    NULL, NULL, EIO, (clock_t)0, NULL);
17300 			return;
17301 		}
17302 	}
17303 
17304 	/*
17305 	 * Save the relevant sense info into the xp for the original cmd.
17306 	 *
17307 	 * Note: if the request sense failed the state info will be zero
17308 	 * as set in sd_mark_rqs_busy()
17309 	 */
17310 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
17311 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
17312 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
17313 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
17314 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
17315 	    SENSE_LENGTH)) {
17316 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17317 		    MAX_SENSE_LENGTH);
17318 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
17319 	} else {
17320 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17321 		    SENSE_LENGTH);
17322 		if (actual_len < SENSE_LENGTH) {
17323 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
17324 		} else {
17325 			cmd_xp->xb_sense_resid = 0;
17326 		}
17327 	}
17328 
17329 	/*
17330 	 *  Free up the RQS command....
17331 	 *  NOTE:
17332 	 *	Must do this BEFORE calling sd_validate_sense_data!
17333 	 *	sd_validate_sense_data may return the original command in
17334 	 *	which case the pkt will be freed and the flags can no
17335 	 *	longer be touched.
17336 	 *	SD_MUTEX is held through this process until the command
17337 	 *	is dispatched based upon the sense data, so there are
17338 	 *	no race conditions.
17339 	 */
17340 	(void) sd_mark_rqs_idle(un, sense_xp);
17341 
17342 	/*
17343 	 * For a retryable command see if we have valid sense data, if so then
17344 	 * turn it over to sd_decode_sense() to figure out the right course of
17345 	 * action. Just fail a non-retryable command.
17346 	 */
17347 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17348 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
17349 		    SD_SENSE_DATA_IS_VALID) {
17350 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
17351 		}
17352 	} else {
17353 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
17354 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17355 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
17356 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
17357 		sd_return_failed_command(un, cmd_bp, EIO);
17358 	}
17359 }
17360 
17361 
17362 
17363 
17364 /*
17365  *    Function: sd_handle_auto_request_sense
17366  *
17367  * Description: Processing for auto-request sense information.
17368  *
17369  *   Arguments: un - ptr to associated softstate
17370  *		bp - ptr to buf(9S) for the command
17371  *		xp - ptr to the sd_xbuf for the command
17372  *		pktp - ptr to the scsi_pkt(9S) for the command
17373  *
17374  *     Context: May be called under interrupt context
17375  */
17376 
17377 static void
17378 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
17379     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17380 {
17381 	struct scsi_arq_status *asp;
17382 	size_t actual_len;
17383 
17384 	ASSERT(un != NULL);
17385 	ASSERT(mutex_owned(SD_MUTEX(un)));
17386 	ASSERT(bp != NULL);
17387 	ASSERT(xp != NULL);
17388 	ASSERT(pktp != NULL);
17389 	ASSERT(pktp != un->un_rqs_pktp);
17390 	ASSERT(bp   != un->un_rqs_bp);
17391 
17392 	/*
17393 	 * For auto-request sense, we get a scsi_arq_status back from
17394 	 * the HBA, with the sense data in the sts_sensedata member.
17395 	 * The pkt_scbp of the packet points to this scsi_arq_status.
17396 	 */
17397 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
17398 
17399 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
17400 		/*
17401 		 * The auto REQUEST SENSE failed; see if we can re-try
17402 		 * the original command.
17403 		 */
17404 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17405 		    "auto request sense failed (reason=%s)\n",
17406 		    scsi_rname(asp->sts_rqpkt_reason));
17407 
17408 		sd_reset_target(un, pktp);
17409 
17410 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17411 		    NULL, NULL, EIO, (clock_t)0, NULL);
17412 		return;
17413 	}
17414 
17415 	/* Save the relevant sense info into the xp for the original cmd. */
17416 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
17417 	xp->xb_sense_state  = asp->sts_rqpkt_state;
17418 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
17419 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
17420 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17421 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
17422 		    MAX_SENSE_LENGTH);
17423 	} else {
17424 		if (xp->xb_sense_resid > SENSE_LENGTH) {
17425 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17426 		} else {
17427 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
17428 		}
17429 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17430 			if ((((struct uscsi_cmd *)
17431 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
17432 				xp->xb_sense_resid = (((struct uscsi_cmd *)
17433 				    (xp->xb_pktinfo))->uscsi_rqlen) -
17434 				    actual_len;
17435 			} else {
17436 				xp->xb_sense_resid = 0;
17437 			}
17438 		}
17439 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
17440 	}
17441 
17442 	/*
17443 	 * See if we have valid sense data, if so then turn it over to
17444 	 * sd_decode_sense() to figure out the right course of action.
17445 	 */
17446 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
17447 	    SD_SENSE_DATA_IS_VALID) {
17448 		sd_decode_sense(un, bp, xp, pktp);
17449 	}
17450 }
17451 
17452 
17453 /*
17454  *    Function: sd_print_sense_failed_msg
17455  *
17456  * Description: Print log message when RQS has failed.
17457  *
17458  *   Arguments: un - ptr to associated softstate
17459  *		bp - ptr to buf(9S) for the command
17460  *		arg - generic message string ptr
17461  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17462  *			or SD_NO_RETRY_ISSUED
17463  *
17464  *     Context: May be called from interrupt context
17465  */
17466 
17467 static void
17468 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
17469     int code)
17470 {
17471 	char	*msgp = arg;
17472 
17473 	ASSERT(un != NULL);
17474 	ASSERT(mutex_owned(SD_MUTEX(un)));
17475 	ASSERT(bp != NULL);
17476 
17477 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
17478 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
17479 	}
17480 }
17481 
17482 
17483 /*
17484  *    Function: sd_validate_sense_data
17485  *
17486  * Description: Check the given sense data for validity.
17487  *		If the sense data is not valid, the command will
17488  *		be either failed or retried!
17489  *
17490  * Return Code: SD_SENSE_DATA_IS_INVALID
17491  *		SD_SENSE_DATA_IS_VALID
17492  *
17493  *     Context: May be called from interrupt context
17494  */
17495 
17496 static int
17497 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17498     size_t actual_len)
17499 {
17500 	struct scsi_extended_sense *esp;
17501 	struct	scsi_pkt *pktp;
17502 	char	*msgp = NULL;
17503 	sd_ssc_t *sscp;
17504 
17505 	ASSERT(un != NULL);
17506 	ASSERT(mutex_owned(SD_MUTEX(un)));
17507 	ASSERT(bp != NULL);
17508 	ASSERT(bp != un->un_rqs_bp);
17509 	ASSERT(xp != NULL);
17510 	ASSERT(un->un_fm_private != NULL);
17511 
17512 	pktp = SD_GET_PKTP(bp);
17513 	ASSERT(pktp != NULL);
17514 
17515 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
17516 	ASSERT(sscp != NULL);
17517 
17518 	/*
17519 	 * Check the status of the RQS command (auto or manual).
17520 	 */
17521 	switch (xp->xb_sense_status & STATUS_MASK) {
17522 	case STATUS_GOOD:
17523 		break;
17524 
17525 	case STATUS_RESERVATION_CONFLICT:
17526 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17527 		return (SD_SENSE_DATA_IS_INVALID);
17528 
17529 	case STATUS_BUSY:
17530 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17531 		    "Busy Status on REQUEST SENSE\n");
17532 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
17533 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17534 		return (SD_SENSE_DATA_IS_INVALID);
17535 
17536 	case STATUS_QFULL:
17537 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17538 		    "QFULL Status on REQUEST SENSE\n");
17539 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
17540 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17541 		return (SD_SENSE_DATA_IS_INVALID);
17542 
17543 	case STATUS_CHECK:
17544 	case STATUS_TERMINATED:
17545 		msgp = "Check Condition on REQUEST SENSE\n";
17546 		goto sense_failed;
17547 
17548 	default:
17549 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
17550 		goto sense_failed;
17551 	}
17552 
17553 	/*
17554 	 * See if we got the minimum required amount of sense data.
17555 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
17556 	 * or less.
17557 	 */
17558 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
17559 	    (actual_len == 0)) {
17560 		msgp = "Request Sense couldn't get sense data\n";
17561 		goto sense_failed;
17562 	}
17563 
17564 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
17565 		msgp = "Not enough sense information\n";
17566 		/* Mark the ssc_flags for detecting invalid sense data */
17567 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17568 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17569 			    "sense-data");
17570 		}
17571 		goto sense_failed;
17572 	}
17573 
17574 	/*
17575 	 * We require the extended sense data
17576 	 */
17577 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
17578 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
17579 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17580 			static char tmp[8];
17581 			static char buf[148];
17582 			char *p = (char *)(xp->xb_sense_data);
17583 			int i;
17584 
17585 			mutex_enter(&sd_sense_mutex);
17586 			(void) strcpy(buf, "undecodable sense information:");
17587 			for (i = 0; i < actual_len; i++) {
17588 				(void) sprintf(tmp, " 0x%x", *(p++) & 0xff);
17589 				(void) strcpy(&buf[strlen(buf)], tmp);
17590 			}
17591 			i = strlen(buf);
17592 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
17593 
17594 			if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
17595 				scsi_log(SD_DEVINFO(un), sd_label,
17596 				    CE_WARN, buf);
17597 			}
17598 			mutex_exit(&sd_sense_mutex);
17599 		}
17600 
17601 		/* Mark the ssc_flags for detecting invalid sense data */
17602 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17603 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17604 			    "sense-data");
17605 		}
17606 
17607 		/* Note: Legacy behavior, fail the command with no retry */
17608 		sd_return_failed_command(un, bp, EIO);
17609 		return (SD_SENSE_DATA_IS_INVALID);
17610 	}
17611 
17612 	/*
17613 	 * Check that es_code is valid (es_class concatenated with es_code
17614 	 * make up the "response code" field.  es_class will always be 7, so
17615 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
17616 	 * format.
17617 	 */
17618 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
17619 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
17620 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
17621 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
17622 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
17623 		/* Mark the ssc_flags for detecting invalid sense data */
17624 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17625 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17626 			    "sense-data");
17627 		}
17628 		goto sense_failed;
17629 	}
17630 
17631 	return (SD_SENSE_DATA_IS_VALID);
17632 
17633 sense_failed:
17634 	/*
17635 	 * If the request sense failed (for whatever reason), attempt
17636 	 * to retry the original command.
17637 	 */
17638 #if defined(__x86)
17639 	/*
17640 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
17641 	 * sddef.h for Sparc platform, and x86 uses 1 binary
17642 	 * for both SCSI/FC.
17643 	 * The SD_RETRY_DELAY value need to be adjusted here
17644 	 * when SD_RETRY_DELAY change in sddef.h
17645 	 */
17646 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17647 	    sd_print_sense_failed_msg, msgp, EIO,
17648 	    un->un_f_is_fibre ? drv_usectohz(100000) : (clock_t)0, NULL);
17649 #else
17650 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17651 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
17652 #endif
17653 
17654 	return (SD_SENSE_DATA_IS_INVALID);
17655 }
17656 
17657 /*
17658  *    Function: sd_decode_sense
17659  *
17660  * Description: Take recovery action(s) when SCSI Sense Data is received.
17661  *
17662  *     Context: Interrupt context.
17663  */
17664 
17665 static void
17666 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17667     struct scsi_pkt *pktp)
17668 {
17669 	uint8_t sense_key;
17670 
17671 	ASSERT(un != NULL);
17672 	ASSERT(mutex_owned(SD_MUTEX(un)));
17673 	ASSERT(bp != NULL);
17674 	ASSERT(bp != un->un_rqs_bp);
17675 	ASSERT(xp != NULL);
17676 	ASSERT(pktp != NULL);
17677 
17678 	sense_key = scsi_sense_key(xp->xb_sense_data);
17679 
17680 	switch (sense_key) {
17681 	case KEY_NO_SENSE:
17682 		sd_sense_key_no_sense(un, bp, xp, pktp);
17683 		break;
17684 	case KEY_RECOVERABLE_ERROR:
17685 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
17686 		    bp, xp, pktp);
17687 		break;
17688 	case KEY_NOT_READY:
17689 		sd_sense_key_not_ready(un, xp->xb_sense_data,
17690 		    bp, xp, pktp);
17691 		break;
17692 	case KEY_MEDIUM_ERROR:
17693 	case KEY_HARDWARE_ERROR:
17694 		sd_sense_key_medium_or_hardware_error(un,
17695 		    xp->xb_sense_data, bp, xp, pktp);
17696 		break;
17697 	case KEY_ILLEGAL_REQUEST:
17698 		sd_sense_key_illegal_request(un, bp, xp, pktp);
17699 		break;
17700 	case KEY_UNIT_ATTENTION:
17701 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
17702 		    bp, xp, pktp);
17703 		break;
17704 	case KEY_WRITE_PROTECT:
17705 	case KEY_VOLUME_OVERFLOW:
17706 	case KEY_MISCOMPARE:
17707 		sd_sense_key_fail_command(un, bp, xp, pktp);
17708 		break;
17709 	case KEY_BLANK_CHECK:
17710 		sd_sense_key_blank_check(un, bp, xp, pktp);
17711 		break;
17712 	case KEY_ABORTED_COMMAND:
17713 		sd_sense_key_aborted_command(un, bp, xp, pktp);
17714 		break;
17715 	case KEY_VENDOR_UNIQUE:
17716 	case KEY_COPY_ABORTED:
17717 	case KEY_EQUAL:
17718 	case KEY_RESERVED:
17719 	default:
17720 		sd_sense_key_default(un, xp->xb_sense_data,
17721 		    bp, xp, pktp);
17722 		break;
17723 	}
17724 }
17725 
17726 
17727 /*
17728  *    Function: sd_dump_memory
17729  *
17730  * Description: Debug logging routine to print the contents of a user provided
17731  *		buffer. The output of the buffer is broken up into 256 byte
17732  *		segments due to a size constraint of the scsi_log.
17733  *		implementation.
17734  *
17735  *   Arguments: un - ptr to softstate
17736  *		comp - component mask
17737  *		title - "title" string to preceed data when printed
17738  *		data - ptr to data block to be printed
17739  *		len - size of data block to be printed
17740  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
17741  *
17742  *     Context: May be called from interrupt context
17743  */
17744 
17745 #define	SD_DUMP_MEMORY_BUF_SIZE	256
17746 
17747 static char *sd_dump_format_string[] = {
17748 		" 0x%02x",
17749 		" %c"
17750 };
17751 
17752 static void
17753 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
17754     int len, int fmt)
17755 {
17756 	int	i, j;
17757 	int	avail_count;
17758 	int	start_offset;
17759 	int	end_offset;
17760 	size_t	entry_len;
17761 	char	*bufp;
17762 	char	*local_buf;
17763 	char	*format_string;
17764 
17765 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
17766 
17767 	/*
17768 	 * In the debug version of the driver, this function is called from a
17769 	 * number of places which are NOPs in the release driver.
17770 	 * The debug driver therefore has additional methods of filtering
17771 	 * debug output.
17772 	 */
17773 #ifdef SDDEBUG
17774 	/*
17775 	 * In the debug version of the driver we can reduce the amount of debug
17776 	 * messages by setting sd_error_level to something other than
17777 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17778 	 * sd_component_mask.
17779 	 */
17780 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17781 	    (sd_error_level != SCSI_ERR_ALL)) {
17782 		return;
17783 	}
17784 	if (((sd_component_mask & comp) == 0) ||
17785 	    (sd_error_level != SCSI_ERR_ALL)) {
17786 		return;
17787 	}
17788 #else
17789 	if (sd_error_level != SCSI_ERR_ALL) {
17790 		return;
17791 	}
17792 #endif
17793 
17794 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17795 	bufp = local_buf;
17796 	/*
17797 	 * Available length is the length of local_buf[], minus the
17798 	 * length of the title string, minus one for the ":", minus
17799 	 * one for the newline, minus one for the NULL terminator.
17800 	 * This gives the #bytes available for holding the printed
17801 	 * values from the given data buffer.
17802 	 */
17803 	if (fmt == SD_LOG_HEX) {
17804 		format_string = sd_dump_format_string[0];
17805 	} else /* SD_LOG_CHAR */ {
17806 		format_string = sd_dump_format_string[1];
17807 	}
17808 	/*
17809 	 * Available count is the number of elements from the given
17810 	 * data buffer that we can fit into the available length.
17811 	 * This is based upon the size of the format string used.
17812 	 * Make one entry and find it's size.
17813 	 */
17814 	(void) sprintf(bufp, format_string, data[0]);
17815 	entry_len = strlen(bufp);
17816 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17817 
17818 	j = 0;
17819 	while (j < len) {
17820 		bufp = local_buf;
17821 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17822 		start_offset = j;
17823 
17824 		end_offset = start_offset + avail_count;
17825 
17826 		(void) sprintf(bufp, "%s:", title);
17827 		bufp += strlen(bufp);
17828 		for (i = start_offset; ((i < end_offset) && (j < len));
17829 		    i++, j++) {
17830 			(void) sprintf(bufp, format_string, data[i]);
17831 			bufp += entry_len;
17832 		}
17833 		(void) sprintf(bufp, "\n");
17834 
17835 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17836 	}
17837 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
17838 }
17839 
17840 /*
17841  *    Function: sd_print_sense_msg
17842  *
17843  * Description: Log a message based upon the given sense data.
17844  *
17845  *   Arguments: un - ptr to associated softstate
17846  *		bp - ptr to buf(9S) for the command
17847  *		arg - ptr to associate sd_sense_info struct
17848  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17849  *			or SD_NO_RETRY_ISSUED
17850  *
17851  *     Context: May be called from interrupt context
17852  */
17853 
17854 static void
17855 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17856 {
17857 	struct sd_xbuf	*xp;
17858 	struct scsi_pkt	*pktp;
17859 	uint8_t *sensep;
17860 	daddr_t request_blkno;
17861 	diskaddr_t err_blkno;
17862 	int severity;
17863 	int pfa_flag;
17864 	extern struct scsi_key_strings scsi_cmds[];
17865 
17866 	ASSERT(un != NULL);
17867 	ASSERT(mutex_owned(SD_MUTEX(un)));
17868 	ASSERT(bp != NULL);
17869 	xp = SD_GET_XBUF(bp);
17870 	ASSERT(xp != NULL);
17871 	pktp = SD_GET_PKTP(bp);
17872 	ASSERT(pktp != NULL);
17873 	ASSERT(arg != NULL);
17874 
17875 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
17876 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
17877 
17878 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
17879 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
17880 		severity = SCSI_ERR_RETRYABLE;
17881 	}
17882 
17883 	/* Use absolute block number for the request block number */
17884 	request_blkno = xp->xb_blkno;
17885 
17886 	/*
17887 	 * Now try to get the error block number from the sense data
17888 	 */
17889 	sensep = xp->xb_sense_data;
17890 
17891 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
17892 	    (uint64_t *)&err_blkno)) {
17893 		/*
17894 		 * We retrieved the error block number from the information
17895 		 * portion of the sense data.
17896 		 *
17897 		 * For USCSI commands we are better off using the error
17898 		 * block no. as the requested block no. (This is the best
17899 		 * we can estimate.)
17900 		 */
17901 		if ((SD_IS_BUFIO(xp) == FALSE) &&
17902 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
17903 			request_blkno = err_blkno;
17904 		}
17905 	} else {
17906 		/*
17907 		 * Without the es_valid bit set (for fixed format) or an
17908 		 * information descriptor (for descriptor format) we cannot
17909 		 * be certain of the error blkno, so just use the
17910 		 * request_blkno.
17911 		 */
17912 		err_blkno = (diskaddr_t)request_blkno;
17913 	}
17914 
17915 	/*
17916 	 * The following will log the buffer contents for the release driver
17917 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
17918 	 * level is set to verbose.
17919 	 */
17920 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
17921 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17922 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
17923 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
17924 
17925 	if (pfa_flag == FALSE) {
17926 		/* This is normally only set for USCSI */
17927 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
17928 			return;
17929 		}
17930 
17931 		if ((SD_IS_BUFIO(xp) == TRUE) &&
17932 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
17933 		    (severity < sd_error_level))) {
17934 			return;
17935 		}
17936 	}
17937 	/*
17938 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
17939 	 */
17940 	if ((SD_IS_LSI(un)) &&
17941 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
17942 	    (scsi_sense_asc(sensep) == 0x94) &&
17943 	    (scsi_sense_ascq(sensep) == 0x01)) {
17944 		un->un_sonoma_failure_count++;
17945 		if (un->un_sonoma_failure_count > 1) {
17946 			return;
17947 		}
17948 	}
17949 
17950 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP ||
17951 	    ((scsi_sense_key(sensep) == KEY_RECOVERABLE_ERROR) &&
17952 	    (pktp->pkt_resid == 0))) {
17953 		scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
17954 		    request_blkno, err_blkno, scsi_cmds,
17955 		    (struct scsi_extended_sense *)sensep,
17956 		    un->un_additional_codes, NULL);
17957 	}
17958 }
17959 
17960 /*
17961  *    Function: sd_sense_key_no_sense
17962  *
17963  * Description: Recovery action when sense data was not received.
17964  *
17965  *     Context: May be called from interrupt context
17966  */
17967 
17968 static void
17969 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17970     struct scsi_pkt *pktp)
17971 {
17972 	struct sd_sense_info	si;
17973 
17974 	ASSERT(un != NULL);
17975 	ASSERT(mutex_owned(SD_MUTEX(un)));
17976 	ASSERT(bp != NULL);
17977 	ASSERT(xp != NULL);
17978 	ASSERT(pktp != NULL);
17979 
17980 	si.ssi_severity = SCSI_ERR_FATAL;
17981 	si.ssi_pfa_flag = FALSE;
17982 
17983 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
17984 
17985 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17986 	    &si, EIO, (clock_t)0, NULL);
17987 }
17988 
17989 
17990 /*
17991  *    Function: sd_sense_key_recoverable_error
17992  *
17993  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
17994  *
17995  *     Context: May be called from interrupt context
17996  */
17997 
17998 static void
17999 sd_sense_key_recoverable_error(struct sd_lun *un, uint8_t *sense_datap,
18000     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18001 {
18002 	struct sd_sense_info	si;
18003 	uint8_t asc = scsi_sense_asc(sense_datap);
18004 	uint8_t ascq = scsi_sense_ascq(sense_datap);
18005 
18006 	ASSERT(un != NULL);
18007 	ASSERT(mutex_owned(SD_MUTEX(un)));
18008 	ASSERT(bp != NULL);
18009 	ASSERT(xp != NULL);
18010 	ASSERT(pktp != NULL);
18011 
18012 	/*
18013 	 * 0x00, 0x1D: ATA PASSTHROUGH INFORMATION AVAILABLE
18014 	 */
18015 	if (asc == 0x00 && ascq == 0x1D) {
18016 		sd_return_command(un, bp);
18017 		return;
18018 	}
18019 
18020 	/*
18021 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
18022 	 */
18023 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
18024 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18025 		si.ssi_severity = SCSI_ERR_INFO;
18026 		si.ssi_pfa_flag = TRUE;
18027 	} else {
18028 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
18029 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
18030 		si.ssi_severity = SCSI_ERR_RECOVERED;
18031 		si.ssi_pfa_flag = FALSE;
18032 	}
18033 
18034 	if (pktp->pkt_resid == 0) {
18035 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18036 		sd_return_command(un, bp);
18037 		return;
18038 	}
18039 
18040 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18041 	    &si, EIO, (clock_t)0, NULL);
18042 }
18043 
18044 
18045 
18046 
18047 /*
18048  *    Function: sd_sense_key_not_ready
18049  *
18050  * Description: Recovery actions for a SCSI "Not Ready" sense key.
18051  *
18052  *     Context: May be called from interrupt context
18053  */
18054 
18055 static void
18056 sd_sense_key_not_ready(struct sd_lun *un, uint8_t *sense_datap, struct buf *bp,
18057     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18058 {
18059 	struct sd_sense_info	si;
18060 	uint8_t asc = scsi_sense_asc(sense_datap);
18061 	uint8_t ascq = scsi_sense_ascq(sense_datap);
18062 
18063 	ASSERT(un != NULL);
18064 	ASSERT(mutex_owned(SD_MUTEX(un)));
18065 	ASSERT(bp != NULL);
18066 	ASSERT(xp != NULL);
18067 	ASSERT(pktp != NULL);
18068 
18069 	si.ssi_severity = SCSI_ERR_FATAL;
18070 	si.ssi_pfa_flag = FALSE;
18071 
18072 	/*
18073 	 * Update error stats after first NOT READY error. Disks may have
18074 	 * been powered down and may need to be restarted.  For CDROMs,
18075 	 * report NOT READY errors only if media is present.
18076 	 */
18077 	if ((ISCD(un) && (asc == 0x3A)) ||
18078 	    (xp->xb_nr_retry_count > 0)) {
18079 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18080 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
18081 	}
18082 
18083 	/*
18084 	 * Just fail if the "not ready" retry limit has been reached.
18085 	 */
18086 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
18087 		/* Special check for error message printing for removables. */
18088 		if (un->un_f_has_removable_media && (asc == 0x04) &&
18089 		    (ascq >= 0x04)) {
18090 			si.ssi_severity = SCSI_ERR_ALL;
18091 		}
18092 		goto fail_command;
18093 	}
18094 
18095 	/*
18096 	 * Check the ASC and ASCQ in the sense data as needed, to determine
18097 	 * what to do.
18098 	 */
18099 	switch (asc) {
18100 	case 0x04:	/* LOGICAL UNIT NOT READY */
18101 		/*
18102 		 * disk drives that don't spin up result in a very long delay
18103 		 * in format without warning messages. We will log a message
18104 		 * if the error level is set to verbose.
18105 		 */
18106 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18107 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18108 			    "logical unit not ready, resetting disk\n");
18109 		}
18110 
18111 		/*
18112 		 * There are different requirements for CDROMs and disks for
18113 		 * the number of retries.  If a CD-ROM is giving this, it is
18114 		 * probably reading TOC and is in the process of getting
18115 		 * ready, so we should keep on trying for a long time to make
18116 		 * sure that all types of media are taken in account (for
18117 		 * some media the drive takes a long time to read TOC).  For
18118 		 * disks we do not want to retry this too many times as this
18119 		 * can cause a long hang in format when the drive refuses to
18120 		 * spin up (a very common failure).
18121 		 */
18122 		switch (ascq) {
18123 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
18124 			/*
18125 			 * Disk drives frequently refuse to spin up which
18126 			 * results in a very long hang in format without
18127 			 * warning messages.
18128 			 *
18129 			 * Note: This code preserves the legacy behavior of
18130 			 * comparing xb_nr_retry_count against zero for fibre
18131 			 * channel targets instead of comparing against the
18132 			 * un_reset_retry_count value.  The reason for this
18133 			 * discrepancy has been so utterly lost beneath the
18134 			 * Sands of Time that even Indiana Jones could not
18135 			 * find it.
18136 			 */
18137 			if (un->un_f_is_fibre == TRUE) {
18138 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18139 				    (xp->xb_nr_retry_count > 0)) &&
18140 				    (un->un_startstop_timeid == NULL)) {
18141 					scsi_log(SD_DEVINFO(un), sd_label,
18142 					    CE_WARN, "logical unit not ready, "
18143 					    "resetting disk\n");
18144 					sd_reset_target(un, pktp);
18145 				}
18146 			} else {
18147 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18148 				    (xp->xb_nr_retry_count >
18149 				    un->un_reset_retry_count)) &&
18150 				    (un->un_startstop_timeid == NULL)) {
18151 					scsi_log(SD_DEVINFO(un), sd_label,
18152 					    CE_WARN, "logical unit not ready, "
18153 					    "resetting disk\n");
18154 					sd_reset_target(un, pktp);
18155 				}
18156 			}
18157 			break;
18158 
18159 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
18160 			/*
18161 			 * If the target is in the process of becoming
18162 			 * ready, just proceed with the retry. This can
18163 			 * happen with CD-ROMs that take a long time to
18164 			 * read TOC after a power cycle or reset.
18165 			 */
18166 			goto do_retry;
18167 
18168 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
18169 			break;
18170 
18171 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
18172 			/*
18173 			 * Retries cannot help here so just fail right away.
18174 			 */
18175 			goto fail_command;
18176 
18177 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
18178 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
18179 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
18180 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
18181 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
18182 		default:    /* Possible future codes in SCSI spec? */
18183 			/*
18184 			 * For removable-media devices, do not retry if
18185 			 * ASCQ > 2 as these result mostly from USCSI commands
18186 			 * on MMC devices issued to check status of an
18187 			 * operation initiated in immediate mode.  Also for
18188 			 * ASCQ >= 4 do not print console messages as these
18189 			 * mainly represent a user-initiated operation
18190 			 * instead of a system failure.
18191 			 */
18192 			if (un->un_f_has_removable_media) {
18193 				si.ssi_severity = SCSI_ERR_ALL;
18194 				goto fail_command;
18195 			}
18196 			break;
18197 		}
18198 
18199 		/*
18200 		 * As part of our recovery attempt for the NOT READY
18201 		 * condition, we issue a START STOP UNIT command. However
18202 		 * we want to wait for a short delay before attempting this
18203 		 * as there may still be more commands coming back from the
18204 		 * target with the check condition. To do this we use
18205 		 * timeout(9F) to call sd_start_stop_unit_callback() after
18206 		 * the delay interval expires. (sd_start_stop_unit_callback()
18207 		 * dispatches sd_start_stop_unit_task(), which will issue
18208 		 * the actual START STOP UNIT command. The delay interval
18209 		 * is one-half of the delay that we will use to retry the
18210 		 * command that generated the NOT READY condition.
18211 		 *
18212 		 * Note that we could just dispatch sd_start_stop_unit_task()
18213 		 * from here and allow it to sleep for the delay interval,
18214 		 * but then we would be tying up the taskq thread
18215 		 * uncesessarily for the duration of the delay.
18216 		 *
18217 		 * Do not issue the START STOP UNIT if the current command
18218 		 * is already a START STOP UNIT.
18219 		 */
18220 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
18221 			break;
18222 		}
18223 
18224 		/*
18225 		 * Do not schedule the timeout if one is already pending.
18226 		 */
18227 		if (un->un_startstop_timeid != NULL) {
18228 			SD_INFO(SD_LOG_ERROR, un,
18229 			    "sd_sense_key_not_ready: restart already issued to"
18230 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
18231 			    ddi_get_instance(SD_DEVINFO(un)));
18232 			break;
18233 		}
18234 
18235 		/*
18236 		 * Schedule the START STOP UNIT command, then queue the command
18237 		 * for a retry.
18238 		 *
18239 		 * Note: A timeout is not scheduled for this retry because we
18240 		 * want the retry to be serial with the START_STOP_UNIT. The
18241 		 * retry will be started when the START_STOP_UNIT is completed
18242 		 * in sd_start_stop_unit_task.
18243 		 */
18244 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
18245 		    un, un->un_busy_timeout / 2);
18246 		xp->xb_nr_retry_count++;
18247 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
18248 		return;
18249 
18250 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
18251 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18252 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18253 			    "unit does not respond to selection\n");
18254 		}
18255 		break;
18256 
18257 	case 0x3A:	/* MEDIUM NOT PRESENT */
18258 		if (sd_error_level >= SCSI_ERR_FATAL) {
18259 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18260 			    "Caddy not inserted in drive\n");
18261 		}
18262 
18263 		sr_ejected(un);
18264 		un->un_mediastate = DKIO_EJECTED;
18265 		/* The state has changed, inform the media watch routines */
18266 		cv_broadcast(&un->un_state_cv);
18267 		/* Just fail if no media is present in the drive. */
18268 		goto fail_command;
18269 
18270 	default:
18271 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18272 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
18273 			    "Unit not Ready. Additional sense code 0x%x\n",
18274 			    asc);
18275 		}
18276 		break;
18277 	}
18278 
18279 do_retry:
18280 
18281 	/*
18282 	 * Retry the command, as some targets may report NOT READY for
18283 	 * several seconds after being reset.
18284 	 */
18285 	xp->xb_nr_retry_count++;
18286 	si.ssi_severity = SCSI_ERR_RETRYABLE;
18287 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
18288 	    &si, EIO, un->un_busy_timeout, NULL);
18289 
18290 	return;
18291 
18292 fail_command:
18293 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18294 	sd_return_failed_command(un, bp, EIO);
18295 }
18296 
18297 
18298 
18299 /*
18300  *    Function: sd_sense_key_medium_or_hardware_error
18301  *
18302  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
18303  *		sense key.
18304  *
18305  *     Context: May be called from interrupt context
18306  */
18307 
18308 static void
18309 sd_sense_key_medium_or_hardware_error(struct sd_lun *un, uint8_t *sense_datap,
18310     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18311 {
18312 	struct sd_sense_info	si;
18313 	uint8_t sense_key = scsi_sense_key(sense_datap);
18314 	uint8_t asc = scsi_sense_asc(sense_datap);
18315 
18316 	ASSERT(un != NULL);
18317 	ASSERT(mutex_owned(SD_MUTEX(un)));
18318 	ASSERT(bp != NULL);
18319 	ASSERT(xp != NULL);
18320 	ASSERT(pktp != NULL);
18321 
18322 	si.ssi_severity = SCSI_ERR_FATAL;
18323 	si.ssi_pfa_flag = FALSE;
18324 
18325 	if (sense_key == KEY_MEDIUM_ERROR) {
18326 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
18327 	}
18328 
18329 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18330 
18331 	if ((un->un_reset_retry_count != 0) &&
18332 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
18333 		mutex_exit(SD_MUTEX(un));
18334 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
18335 		if (un->un_f_allow_bus_device_reset == TRUE) {
18336 
18337 			boolean_t try_resetting_target = B_TRUE;
18338 
18339 			/*
18340 			 * We need to be able to handle specific ASC when we are
18341 			 * handling a KEY_HARDWARE_ERROR. In particular
18342 			 * taking the default action of resetting the target may
18343 			 * not be the appropriate way to attempt recovery.
18344 			 * Resetting a target because of a single LUN failure
18345 			 * victimizes all LUNs on that target.
18346 			 *
18347 			 * This is true for the LSI arrays, if an LSI
18348 			 * array controller returns an ASC of 0x84 (LUN Dead) we
18349 			 * should trust it.
18350 			 */
18351 
18352 			if (sense_key == KEY_HARDWARE_ERROR) {
18353 				switch (asc) {
18354 				case 0x84:
18355 					if (SD_IS_LSI(un)) {
18356 						try_resetting_target = B_FALSE;
18357 					}
18358 					break;
18359 				default:
18360 					break;
18361 				}
18362 			}
18363 
18364 			if (try_resetting_target == B_TRUE) {
18365 				int reset_retval = 0;
18366 				if (un->un_f_lun_reset_enabled == TRUE) {
18367 					SD_TRACE(SD_LOG_IO_CORE, un,
18368 					    "sd_sense_key_medium_or_hardware_"
18369 					    "error: issuing RESET_LUN\n");
18370 					reset_retval =
18371 					    scsi_reset(SD_ADDRESS(un),
18372 					    RESET_LUN);
18373 				}
18374 				if (reset_retval == 0) {
18375 					SD_TRACE(SD_LOG_IO_CORE, un,
18376 					    "sd_sense_key_medium_or_hardware_"
18377 					    "error: issuing RESET_TARGET\n");
18378 					(void) scsi_reset(SD_ADDRESS(un),
18379 					    RESET_TARGET);
18380 				}
18381 			}
18382 		}
18383 		mutex_enter(SD_MUTEX(un));
18384 	}
18385 
18386 	/*
18387 	 * This really ought to be a fatal error, but we will retry anyway
18388 	 * as some drives report this as a spurious error.
18389 	 */
18390 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18391 	    &si, EIO, (clock_t)0, NULL);
18392 }
18393 
18394 
18395 
18396 /*
18397  *    Function: sd_sense_key_illegal_request
18398  *
18399  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
18400  *
18401  *     Context: May be called from interrupt context
18402  */
18403 
18404 static void
18405 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
18406     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18407 {
18408 	struct sd_sense_info	si;
18409 
18410 	ASSERT(un != NULL);
18411 	ASSERT(mutex_owned(SD_MUTEX(un)));
18412 	ASSERT(bp != NULL);
18413 	ASSERT(xp != NULL);
18414 	ASSERT(pktp != NULL);
18415 
18416 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
18417 
18418 	si.ssi_severity = SCSI_ERR_INFO;
18419 	si.ssi_pfa_flag = FALSE;
18420 
18421 	/* Pointless to retry if the target thinks it's an illegal request */
18422 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18423 	sd_return_failed_command(un, bp, EIO);
18424 }
18425 
18426 
18427 
18428 
18429 /*
18430  *    Function: sd_sense_key_unit_attention
18431  *
18432  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
18433  *
18434  *     Context: May be called from interrupt context
18435  */
18436 
18437 static void
18438 sd_sense_key_unit_attention(struct sd_lun *un, uint8_t *sense_datap,
18439     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18440 {
18441 	/*
18442 	 * For UNIT ATTENTION we allow retries for one minute. Devices
18443 	 * like Sonoma can return UNIT ATTENTION close to a minute
18444 	 * under certain conditions.
18445 	 */
18446 	int	retry_check_flag = SD_RETRIES_UA;
18447 	boolean_t	kstat_updated = B_FALSE;
18448 	struct	sd_sense_info		si;
18449 	uint8_t asc = scsi_sense_asc(sense_datap);
18450 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
18451 
18452 	ASSERT(un != NULL);
18453 	ASSERT(mutex_owned(SD_MUTEX(un)));
18454 	ASSERT(bp != NULL);
18455 	ASSERT(xp != NULL);
18456 	ASSERT(pktp != NULL);
18457 
18458 	si.ssi_severity = SCSI_ERR_INFO;
18459 	si.ssi_pfa_flag = FALSE;
18460 
18461 
18462 	switch (asc) {
18463 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
18464 		if (sd_report_pfa != 0) {
18465 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18466 			si.ssi_pfa_flag = TRUE;
18467 			retry_check_flag = SD_RETRIES_STANDARD;
18468 			goto do_retry;
18469 		}
18470 
18471 		break;
18472 
18473 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
18474 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
18475 			un->un_resvd_status |=
18476 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
18477 		}
18478 #ifdef _LP64
18479 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
18480 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
18481 			    un, KM_NOSLEEP) == TASKQID_INVALID) {
18482 				/*
18483 				 * If we can't dispatch the task we'll just
18484 				 * live without descriptor sense.  We can
18485 				 * try again on the next "unit attention"
18486 				 */
18487 				SD_ERROR(SD_LOG_ERROR, un,
18488 				    "sd_sense_key_unit_attention: "
18489 				    "Could not dispatch "
18490 				    "sd_reenable_dsense_task\n");
18491 			}
18492 		}
18493 #endif /* _LP64 */
18494 		/* FALLTHRU */
18495 
18496 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
18497 		if (!un->un_f_has_removable_media) {
18498 			break;
18499 		}
18500 
18501 		/*
18502 		 * When we get a unit attention from a removable-media device,
18503 		 * it may be in a state that will take a long time to recover
18504 		 * (e.g., from a reset).  Since we are executing in interrupt
18505 		 * context here, we cannot wait around for the device to come
18506 		 * back. So hand this command off to sd_media_change_task()
18507 		 * for deferred processing under taskq thread context. (Note
18508 		 * that the command still may be failed if a problem is
18509 		 * encountered at a later time.)
18510 		 */
18511 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
18512 		    KM_NOSLEEP) == TASKQID_INVALID) {
18513 			/*
18514 			 * Cannot dispatch the request so fail the command.
18515 			 */
18516 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
18517 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18518 			si.ssi_severity = SCSI_ERR_FATAL;
18519 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18520 			sd_return_failed_command(un, bp, EIO);
18521 		}
18522 
18523 		/*
18524 		 * If failed to dispatch sd_media_change_task(), we already
18525 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
18526 		 * we should update kstat later if it encounters an error. So,
18527 		 * we update kstat_updated flag here.
18528 		 */
18529 		kstat_updated = B_TRUE;
18530 
18531 		/*
18532 		 * Either the command has been successfully dispatched to a
18533 		 * task Q for retrying, or the dispatch failed. In either case
18534 		 * do NOT retry again by calling sd_retry_command. This sets up
18535 		 * two retries of the same command and when one completes and
18536 		 * frees the resources the other will access freed memory,
18537 		 * a bad thing.
18538 		 */
18539 		return;
18540 
18541 	default:
18542 		break;
18543 	}
18544 
18545 	/*
18546 	 * ASC  ASCQ
18547 	 *  2A   09	Capacity data has changed
18548 	 *  2A   01	Mode parameters changed
18549 	 *  3F   0E	Reported luns data has changed
18550 	 * Arrays that support logical unit expansion should report
18551 	 * capacity changes(2Ah/09). Mode parameters changed and
18552 	 * reported luns data has changed are the approximation.
18553 	 */
18554 	if (((asc == 0x2a) && (ascq == 0x09)) ||
18555 	    ((asc == 0x2a) && (ascq == 0x01)) ||
18556 	    ((asc == 0x3f) && (ascq == 0x0e))) {
18557 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
18558 		    KM_NOSLEEP) == TASKQID_INVALID) {
18559 			SD_ERROR(SD_LOG_ERROR, un,
18560 			    "sd_sense_key_unit_attention: "
18561 			    "Could not dispatch sd_target_change_task\n");
18562 		}
18563 	}
18564 
18565 	/*
18566 	 * Update kstat if we haven't done that.
18567 	 */
18568 	if (!kstat_updated) {
18569 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18570 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18571 	}
18572 
18573 do_retry:
18574 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
18575 	    EIO, SD_UA_RETRY_DELAY, NULL);
18576 }
18577 
18578 
18579 
18580 /*
18581  *    Function: sd_sense_key_fail_command
18582  *
18583  * Description: Use to fail a command when we don't like the sense key that
18584  *		was returned.
18585  *
18586  *     Context: May be called from interrupt context
18587  */
18588 
18589 static void
18590 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18591     struct scsi_pkt *pktp)
18592 {
18593 	struct sd_sense_info	si;
18594 
18595 	ASSERT(un != NULL);
18596 	ASSERT(mutex_owned(SD_MUTEX(un)));
18597 	ASSERT(bp != NULL);
18598 	ASSERT(xp != NULL);
18599 	ASSERT(pktp != NULL);
18600 
18601 	si.ssi_severity = SCSI_ERR_FATAL;
18602 	si.ssi_pfa_flag = FALSE;
18603 
18604 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18605 	sd_return_failed_command(un, bp, EIO);
18606 }
18607 
18608 
18609 
18610 /*
18611  *    Function: sd_sense_key_blank_check
18612  *
18613  * Description: Recovery actions for a SCSI "Blank Check" sense key.
18614  *		Has no monetary connotation.
18615  *
18616  *     Context: May be called from interrupt context
18617  */
18618 
18619 static void
18620 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18621     struct scsi_pkt *pktp)
18622 {
18623 	struct sd_sense_info	si;
18624 
18625 	ASSERT(un != NULL);
18626 	ASSERT(mutex_owned(SD_MUTEX(un)));
18627 	ASSERT(bp != NULL);
18628 	ASSERT(xp != NULL);
18629 	ASSERT(pktp != NULL);
18630 
18631 	/*
18632 	 * Blank check is not fatal for removable devices, therefore
18633 	 * it does not require a console message.
18634 	 */
18635 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
18636 	    SCSI_ERR_FATAL;
18637 	si.ssi_pfa_flag = FALSE;
18638 
18639 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18640 	sd_return_failed_command(un, bp, EIO);
18641 }
18642 
18643 
18644 
18645 
18646 /*
18647  *    Function: sd_sense_key_aborted_command
18648  *
18649  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
18650  *
18651  *     Context: May be called from interrupt context
18652  */
18653 
18654 static void
18655 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
18656     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18657 {
18658 	struct sd_sense_info	si;
18659 
18660 	ASSERT(un != NULL);
18661 	ASSERT(mutex_owned(SD_MUTEX(un)));
18662 	ASSERT(bp != NULL);
18663 	ASSERT(xp != NULL);
18664 	ASSERT(pktp != NULL);
18665 
18666 	si.ssi_severity = SCSI_ERR_FATAL;
18667 	si.ssi_pfa_flag = FALSE;
18668 
18669 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18670 
18671 	/*
18672 	 * This really ought to be a fatal error, but we will retry anyway
18673 	 * as some drives report this as a spurious error.
18674 	 */
18675 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18676 	    &si, EIO, drv_usectohz(100000), NULL);
18677 }
18678 
18679 
18680 
18681 /*
18682  *    Function: sd_sense_key_default
18683  *
18684  * Description: Default recovery action for several SCSI sense keys (basically
18685  *		attempts a retry).
18686  *
18687  *     Context: May be called from interrupt context
18688  */
18689 
18690 static void
18691 sd_sense_key_default(struct sd_lun *un, uint8_t *sense_datap, struct buf *bp,
18692     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18693 {
18694 	struct sd_sense_info	si;
18695 	uint8_t sense_key = scsi_sense_key(sense_datap);
18696 
18697 	ASSERT(un != NULL);
18698 	ASSERT(mutex_owned(SD_MUTEX(un)));
18699 	ASSERT(bp != NULL);
18700 	ASSERT(xp != NULL);
18701 	ASSERT(pktp != NULL);
18702 
18703 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18704 
18705 	/*
18706 	 * Undecoded sense key.	Attempt retries and hope that will fix
18707 	 * the problem.  Otherwise, we're dead.
18708 	 */
18709 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18710 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18711 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18712 	}
18713 
18714 	si.ssi_severity = SCSI_ERR_FATAL;
18715 	si.ssi_pfa_flag = FALSE;
18716 
18717 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18718 	    &si, EIO, (clock_t)0, NULL);
18719 }
18720 
18721 
18722 
18723 /*
18724  *    Function: sd_print_retry_msg
18725  *
18726  * Description: Print a message indicating the retry action being taken.
18727  *
18728  *   Arguments: un - ptr to associated softstate
18729  *		bp - ptr to buf(9S) for the command
18730  *		arg - not used.
18731  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18732  *			or SD_NO_RETRY_ISSUED
18733  *
18734  *     Context: May be called from interrupt context
18735  */
18736 /* ARGSUSED */
18737 static void
18738 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18739 {
18740 	struct sd_xbuf	*xp;
18741 	struct scsi_pkt *pktp;
18742 	char *reasonp;
18743 	char *msgp;
18744 
18745 	ASSERT(un != NULL);
18746 	ASSERT(mutex_owned(SD_MUTEX(un)));
18747 	ASSERT(bp != NULL);
18748 	pktp = SD_GET_PKTP(bp);
18749 	ASSERT(pktp != NULL);
18750 	xp = SD_GET_XBUF(bp);
18751 	ASSERT(xp != NULL);
18752 
18753 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18754 	mutex_enter(&un->un_pm_mutex);
18755 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18756 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18757 	    (pktp->pkt_flags & FLAG_SILENT)) {
18758 		mutex_exit(&un->un_pm_mutex);
18759 		goto update_pkt_reason;
18760 	}
18761 	mutex_exit(&un->un_pm_mutex);
18762 
18763 	/*
18764 	 * Suppress messages if they are all the same pkt_reason; with
18765 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18766 	 * If we are in panic, then suppress the retry messages.
18767 	 */
18768 	switch (flag) {
18769 	case SD_NO_RETRY_ISSUED:
18770 		msgp = "giving up";
18771 		break;
18772 	case SD_IMMEDIATE_RETRY_ISSUED:
18773 	case SD_DELAYED_RETRY_ISSUED:
18774 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18775 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18776 		    (sd_error_level != SCSI_ERR_ALL))) {
18777 			return;
18778 		}
18779 		msgp = "retrying command";
18780 		break;
18781 	default:
18782 		goto update_pkt_reason;
18783 	}
18784 
18785 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18786 	    scsi_rname(pktp->pkt_reason));
18787 
18788 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
18789 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18790 		    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18791 	}
18792 
18793 update_pkt_reason:
18794 	/*
18795 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18796 	 * This is to prevent multiple console messages for the same failure
18797 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18798 	 * when the command is retried successfully because there still may be
18799 	 * more commands coming back with the same value of pktp->pkt_reason.
18800 	 */
18801 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18802 		un->un_last_pkt_reason = pktp->pkt_reason;
18803 	}
18804 }
18805 
18806 
18807 /*
18808  *    Function: sd_print_cmd_incomplete_msg
18809  *
18810  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18811  *
18812  *   Arguments: un - ptr to associated softstate
18813  *		bp - ptr to buf(9S) for the command
18814  *		arg - passed to sd_print_retry_msg()
18815  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18816  *			or SD_NO_RETRY_ISSUED
18817  *
18818  *     Context: May be called from interrupt context
18819  */
18820 
18821 static void
18822 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18823     int code)
18824 {
18825 	dev_info_t	*dip;
18826 
18827 	ASSERT(un != NULL);
18828 	ASSERT(mutex_owned(SD_MUTEX(un)));
18829 	ASSERT(bp != NULL);
18830 
18831 	switch (code) {
18832 	case SD_NO_RETRY_ISSUED:
18833 		/* Command was failed. Someone turned off this target? */
18834 		if (un->un_state != SD_STATE_OFFLINE) {
18835 			/*
18836 			 * Suppress message if we are detaching and
18837 			 * device has been disconnected
18838 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
18839 			 * private interface and not part of the DDI
18840 			 */
18841 			dip = un->un_sd->sd_dev;
18842 			if (!(DEVI_IS_DETACHING(dip) &&
18843 			    DEVI_IS_DEVICE_REMOVED(dip))) {
18844 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18845 				"disk not responding to selection\n");
18846 			}
18847 			New_state(un, SD_STATE_OFFLINE);
18848 		}
18849 		break;
18850 
18851 	case SD_DELAYED_RETRY_ISSUED:
18852 	case SD_IMMEDIATE_RETRY_ISSUED:
18853 	default:
18854 		/* Command was successfully queued for retry */
18855 		sd_print_retry_msg(un, bp, arg, code);
18856 		break;
18857 	}
18858 }
18859 
18860 
18861 /*
18862  *    Function: sd_pkt_reason_cmd_incomplete
18863  *
18864  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
18865  *
18866  *     Context: May be called from interrupt context
18867  */
18868 
18869 static void
18870 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
18871     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18872 {
18873 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
18874 
18875 	ASSERT(un != NULL);
18876 	ASSERT(mutex_owned(SD_MUTEX(un)));
18877 	ASSERT(bp != NULL);
18878 	ASSERT(xp != NULL);
18879 	ASSERT(pktp != NULL);
18880 
18881 	/* Do not do a reset if selection did not complete */
18882 	/* Note: Should this not just check the bit? */
18883 	if (pktp->pkt_state != STATE_GOT_BUS) {
18884 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18885 		sd_reset_target(un, pktp);
18886 	}
18887 
18888 	/*
18889 	 * If the target was not successfully selected, then set
18890 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
18891 	 * with the target, and further retries and/or commands are
18892 	 * likely to take a long time.
18893 	 */
18894 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
18895 		flag |= SD_RETRIES_FAILFAST;
18896 	}
18897 
18898 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18899 
18900 	sd_retry_command(un, bp, flag,
18901 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18902 }
18903 
18904 
18905 
18906 /*
18907  *    Function: sd_pkt_reason_cmd_tran_err
18908  *
18909  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
18910  *
18911  *     Context: May be called from interrupt context
18912  */
18913 
18914 static void
18915 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
18916     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18917 {
18918 	ASSERT(un != NULL);
18919 	ASSERT(mutex_owned(SD_MUTEX(un)));
18920 	ASSERT(bp != NULL);
18921 	ASSERT(xp != NULL);
18922 	ASSERT(pktp != NULL);
18923 
18924 	/*
18925 	 * Do not reset if we got a parity error, or if
18926 	 * selection did not complete.
18927 	 */
18928 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18929 	/* Note: Should this not just check the bit for pkt_state? */
18930 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
18931 	    (pktp->pkt_state != STATE_GOT_BUS)) {
18932 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18933 		sd_reset_target(un, pktp);
18934 	}
18935 
18936 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18937 
18938 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18939 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18940 }
18941 
18942 
18943 
18944 /*
18945  *    Function: sd_pkt_reason_cmd_reset
18946  *
18947  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
18948  *
18949  *     Context: May be called from interrupt context
18950  */
18951 
18952 static void
18953 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18954     struct scsi_pkt *pktp)
18955 {
18956 	ASSERT(un != NULL);
18957 	ASSERT(mutex_owned(SD_MUTEX(un)));
18958 	ASSERT(bp != NULL);
18959 	ASSERT(xp != NULL);
18960 	ASSERT(pktp != NULL);
18961 
18962 	/* The target may still be running the command, so try to reset. */
18963 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18964 	sd_reset_target(un, pktp);
18965 
18966 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18967 
18968 	/*
18969 	 * If pkt_reason is CMD_RESET chances are that this pkt got
18970 	 * reset because another target on this bus caused it. The target
18971 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18972 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18973 	 */
18974 
18975 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18976 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18977 }
18978 
18979 
18980 
18981 
18982 /*
18983  *    Function: sd_pkt_reason_cmd_aborted
18984  *
18985  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
18986  *
18987  *     Context: May be called from interrupt context
18988  */
18989 
18990 static void
18991 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18992     struct scsi_pkt *pktp)
18993 {
18994 	ASSERT(un != NULL);
18995 	ASSERT(mutex_owned(SD_MUTEX(un)));
18996 	ASSERT(bp != NULL);
18997 	ASSERT(xp != NULL);
18998 	ASSERT(pktp != NULL);
18999 
19000 	/* The target may still be running the command, so try to reset. */
19001 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19002 	sd_reset_target(un, pktp);
19003 
19004 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19005 
19006 	/*
19007 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
19008 	 * aborted because another target on this bus caused it. The target
19009 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
19010 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
19011 	 */
19012 
19013 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
19014 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19015 }
19016 
19017 
19018 
19019 /*
19020  *    Function: sd_pkt_reason_cmd_timeout
19021  *
19022  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
19023  *
19024  *     Context: May be called from interrupt context
19025  */
19026 
19027 static void
19028 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19029     struct scsi_pkt *pktp)
19030 {
19031 	ASSERT(un != NULL);
19032 	ASSERT(mutex_owned(SD_MUTEX(un)));
19033 	ASSERT(bp != NULL);
19034 	ASSERT(xp != NULL);
19035 	ASSERT(pktp != NULL);
19036 
19037 
19038 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19039 	sd_reset_target(un, pktp);
19040 
19041 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19042 
19043 	/*
19044 	 * A command timeout indicates that we could not establish
19045 	 * communication with the target, so set SD_RETRIES_FAILFAST
19046 	 * as further retries/commands are likely to take a long time.
19047 	 */
19048 	sd_retry_command(un, bp,
19049 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
19050 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19051 }
19052 
19053 
19054 
19055 /*
19056  *    Function: sd_pkt_reason_cmd_unx_bus_free
19057  *
19058  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
19059  *
19060  *     Context: May be called from interrupt context
19061  */
19062 
19063 static void
19064 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
19065     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19066 {
19067 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
19068 
19069 	ASSERT(un != NULL);
19070 	ASSERT(mutex_owned(SD_MUTEX(un)));
19071 	ASSERT(bp != NULL);
19072 	ASSERT(xp != NULL);
19073 	ASSERT(pktp != NULL);
19074 
19075 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19076 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19077 
19078 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
19079 	    sd_print_retry_msg : NULL;
19080 
19081 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19082 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19083 }
19084 
19085 
19086 /*
19087  *    Function: sd_pkt_reason_cmd_tag_reject
19088  *
19089  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
19090  *
19091  *     Context: May be called from interrupt context
19092  */
19093 
19094 static void
19095 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
19096     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19097 {
19098 	ASSERT(un != NULL);
19099 	ASSERT(mutex_owned(SD_MUTEX(un)));
19100 	ASSERT(bp != NULL);
19101 	ASSERT(xp != NULL);
19102 	ASSERT(pktp != NULL);
19103 
19104 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
19105 	pktp->pkt_flags = 0;
19106 	un->un_tagflags = 0;
19107 	if (un->un_f_opt_queueing == TRUE) {
19108 		un->un_throttle = min(un->un_throttle, 3);
19109 	} else {
19110 		un->un_throttle = 1;
19111 	}
19112 	mutex_exit(SD_MUTEX(un));
19113 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
19114 	mutex_enter(SD_MUTEX(un));
19115 
19116 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19117 
19118 	/* Legacy behavior not to check retry counts here. */
19119 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
19120 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19121 }
19122 
19123 
19124 /*
19125  *    Function: sd_pkt_reason_default
19126  *
19127  * Description: Default recovery actions for SCSA pkt_reason values that
19128  *		do not have more explicit recovery actions.
19129  *
19130  *     Context: May be called from interrupt context
19131  */
19132 
19133 static void
19134 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19135     struct scsi_pkt *pktp)
19136 {
19137 	ASSERT(un != NULL);
19138 	ASSERT(mutex_owned(SD_MUTEX(un)));
19139 	ASSERT(bp != NULL);
19140 	ASSERT(xp != NULL);
19141 	ASSERT(pktp != NULL);
19142 
19143 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19144 	sd_reset_target(un, pktp);
19145 
19146 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19147 
19148 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19149 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19150 }
19151 
19152 
19153 
19154 /*
19155  *    Function: sd_pkt_status_check_condition
19156  *
19157  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
19158  *
19159  *     Context: May be called from interrupt context
19160  */
19161 
19162 static void
19163 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
19164     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19165 {
19166 	ASSERT(un != NULL);
19167 	ASSERT(mutex_owned(SD_MUTEX(un)));
19168 	ASSERT(bp != NULL);
19169 	ASSERT(xp != NULL);
19170 	ASSERT(pktp != NULL);
19171 
19172 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
19173 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
19174 
19175 	/*
19176 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
19177 	 * command will be retried after the request sense). Otherwise, retry
19178 	 * the command. Note: we are issuing the request sense even though the
19179 	 * retry limit may have been reached for the failed command.
19180 	 */
19181 	if (un->un_f_arq_enabled == FALSE) {
19182 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19183 		    "no ARQ, sending request sense command\n");
19184 		sd_send_request_sense_command(un, bp, pktp);
19185 	} else {
19186 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19187 		    "ARQ,retrying request sense command\n");
19188 #if defined(__x86)
19189 		/*
19190 		 * The SD_RETRY_DELAY value need to be adjusted here
19191 		 * when SD_RETRY_DELAY change in sddef.h
19192 		 */
19193 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19194 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
19195 		    NULL);
19196 #else
19197 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
19198 		    EIO, SD_RETRY_DELAY, NULL);
19199 #endif
19200 	}
19201 
19202 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
19203 }
19204 
19205 
19206 /*
19207  *    Function: sd_pkt_status_busy
19208  *
19209  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
19210  *
19211  *     Context: May be called from interrupt context
19212  */
19213 
19214 static void
19215 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19216     struct scsi_pkt *pktp)
19217 {
19218 	ASSERT(un != NULL);
19219 	ASSERT(mutex_owned(SD_MUTEX(un)));
19220 	ASSERT(bp != NULL);
19221 	ASSERT(xp != NULL);
19222 	ASSERT(pktp != NULL);
19223 
19224 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19225 	    "sd_pkt_status_busy: entry\n");
19226 
19227 	/* If retries are exhausted, just fail the command. */
19228 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
19229 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19230 		    "device busy too long\n");
19231 		sd_return_failed_command(un, bp, EIO);
19232 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19233 		    "sd_pkt_status_busy: exit\n");
19234 		return;
19235 	}
19236 	xp->xb_retry_count++;
19237 
19238 	/*
19239 	 * Try to reset the target. However, we do not want to perform
19240 	 * more than one reset if the device continues to fail. The reset
19241 	 * will be performed when the retry count reaches the reset
19242 	 * threshold.  This threshold should be set such that at least
19243 	 * one retry is issued before the reset is performed.
19244 	 */
19245 	if (xp->xb_retry_count ==
19246 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
19247 		int rval = 0;
19248 		mutex_exit(SD_MUTEX(un));
19249 		if (un->un_f_allow_bus_device_reset == TRUE) {
19250 			/*
19251 			 * First try to reset the LUN; if we cannot then
19252 			 * try to reset the target.
19253 			 */
19254 			if (un->un_f_lun_reset_enabled == TRUE) {
19255 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19256 				    "sd_pkt_status_busy: RESET_LUN\n");
19257 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19258 			}
19259 			if (rval == 0) {
19260 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19261 				    "sd_pkt_status_busy: RESET_TARGET\n");
19262 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19263 			}
19264 		}
19265 		if (rval == 0) {
19266 			/*
19267 			 * If the RESET_LUN and/or RESET_TARGET failed,
19268 			 * try RESET_ALL
19269 			 */
19270 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19271 			    "sd_pkt_status_busy: RESET_ALL\n");
19272 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
19273 		}
19274 		mutex_enter(SD_MUTEX(un));
19275 		if (rval == 0) {
19276 			/*
19277 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
19278 			 * At this point we give up & fail the command.
19279 			 */
19280 			sd_return_failed_command(un, bp, EIO);
19281 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19282 			    "sd_pkt_status_busy: exit (failed cmd)\n");
19283 			return;
19284 		}
19285 	}
19286 
19287 	/*
19288 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
19289 	 * we have already checked the retry counts above.
19290 	 */
19291 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
19292 	    EIO, un->un_busy_timeout, NULL);
19293 
19294 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19295 	    "sd_pkt_status_busy: exit\n");
19296 }
19297 
19298 
19299 /*
19300  *    Function: sd_pkt_status_reservation_conflict
19301  *
19302  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
19303  *		command status.
19304  *
19305  *     Context: May be called from interrupt context
19306  */
19307 
19308 static void
19309 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
19310     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19311 {
19312 	ASSERT(un != NULL);
19313 	ASSERT(mutex_owned(SD_MUTEX(un)));
19314 	ASSERT(bp != NULL);
19315 	ASSERT(xp != NULL);
19316 	ASSERT(pktp != NULL);
19317 
19318 	/*
19319 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
19320 	 * conflict could be due to various reasons like incorrect keys, not
19321 	 * registered or not reserved etc. So, we return EACCES to the caller.
19322 	 */
19323 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
19324 		int cmd = SD_GET_PKT_OPCODE(pktp);
19325 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
19326 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
19327 			sd_return_failed_command(un, bp, EACCES);
19328 			return;
19329 		}
19330 	}
19331 
19332 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
19333 
19334 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
19335 		if (sd_failfast_enable != 0) {
19336 			/* By definition, we must panic here.... */
19337 			sd_panic_for_res_conflict(un);
19338 			/*NOTREACHED*/
19339 		}
19340 		SD_ERROR(SD_LOG_IO, un,
19341 		    "sd_handle_resv_conflict: Disk Reserved\n");
19342 		sd_return_failed_command(un, bp, EACCES);
19343 		return;
19344 	}
19345 
19346 	/*
19347 	 * 1147670: retry only if sd_retry_on_reservation_conflict
19348 	 * property is set (default is 1). Retries will not succeed
19349 	 * on a disk reserved by another initiator. HA systems
19350 	 * may reset this via sd.conf to avoid these retries.
19351 	 *
19352 	 * Note: The legacy return code for this failure is EIO, however EACCES
19353 	 * seems more appropriate for a reservation conflict.
19354 	 */
19355 	if (sd_retry_on_reservation_conflict == 0) {
19356 		SD_ERROR(SD_LOG_IO, un,
19357 		    "sd_handle_resv_conflict: Device Reserved\n");
19358 		sd_return_failed_command(un, bp, EIO);
19359 		return;
19360 	}
19361 
19362 	/*
19363 	 * Retry the command if we can.
19364 	 *
19365 	 * Note: The legacy return code for this failure is EIO, however EACCES
19366 	 * seems more appropriate for a reservation conflict.
19367 	 */
19368 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19369 	    (clock_t)2, NULL);
19370 }
19371 
19372 
19373 
19374 /*
19375  *    Function: sd_pkt_status_qfull
19376  *
19377  * Description: Handle a QUEUE FULL condition from the target.  This can
19378  *		occur if the HBA does not handle the queue full condition.
19379  *		(Basically this means third-party HBAs as Sun HBAs will
19380  *		handle the queue full condition.)  Note that if there are
19381  *		some commands already in the transport, then the queue full
19382  *		has occurred because the queue for this nexus is actually
19383  *		full. If there are no commands in the transport, then the
19384  *		queue full is resulting from some other initiator or lun
19385  *		consuming all the resources at the target.
19386  *
19387  *     Context: May be called from interrupt context
19388  */
19389 
19390 static void
19391 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19392     struct scsi_pkt *pktp)
19393 {
19394 	ASSERT(un != NULL);
19395 	ASSERT(mutex_owned(SD_MUTEX(un)));
19396 	ASSERT(bp != NULL);
19397 	ASSERT(xp != NULL);
19398 	ASSERT(pktp != NULL);
19399 
19400 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19401 	    "sd_pkt_status_qfull: entry\n");
19402 
19403 	/*
19404 	 * Just lower the QFULL throttle and retry the command.  Note that
19405 	 * we do not limit the number of retries here.
19406 	 */
19407 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
19408 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
19409 	    SD_RESTART_TIMEOUT, NULL);
19410 
19411 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19412 	    "sd_pkt_status_qfull: exit\n");
19413 }
19414 
19415 
19416 /*
19417  *    Function: sd_reset_target
19418  *
19419  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
19420  *		RESET_TARGET, or RESET_ALL.
19421  *
19422  *     Context: May be called under interrupt context.
19423  */
19424 
19425 static void
19426 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
19427 {
19428 	int rval = 0;
19429 
19430 	ASSERT(un != NULL);
19431 	ASSERT(mutex_owned(SD_MUTEX(un)));
19432 	ASSERT(pktp != NULL);
19433 
19434 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
19435 
19436 	/*
19437 	 * No need to reset if the transport layer has already done so.
19438 	 */
19439 	if ((pktp->pkt_statistics &
19440 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
19441 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19442 		    "sd_reset_target: no reset\n");
19443 		return;
19444 	}
19445 
19446 	mutex_exit(SD_MUTEX(un));
19447 
19448 	if (un->un_f_allow_bus_device_reset == TRUE) {
19449 		if (un->un_f_lun_reset_enabled == TRUE) {
19450 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19451 			    "sd_reset_target: RESET_LUN\n");
19452 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19453 		}
19454 		if (rval == 0) {
19455 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19456 			    "sd_reset_target: RESET_TARGET\n");
19457 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19458 		}
19459 	}
19460 
19461 	if (rval == 0) {
19462 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19463 		    "sd_reset_target: RESET_ALL\n");
19464 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
19465 	}
19466 
19467 	mutex_enter(SD_MUTEX(un));
19468 
19469 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
19470 }
19471 
19472 /*
19473  *    Function: sd_target_change_task
19474  *
19475  * Description: Handle dynamic target change
19476  *
19477  *     Context: Executes in a taskq() thread context
19478  */
19479 static void
19480 sd_target_change_task(void *arg)
19481 {
19482 	struct sd_lun		*un = arg;
19483 	uint64_t		capacity;
19484 	diskaddr_t		label_cap;
19485 	uint_t			lbasize;
19486 	sd_ssc_t		*ssc;
19487 
19488 	ASSERT(un != NULL);
19489 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19490 
19491 	if ((un->un_f_blockcount_is_valid == FALSE) ||
19492 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
19493 		return;
19494 	}
19495 
19496 	ssc = sd_ssc_init(un);
19497 
19498 	if (sd_send_scsi_READ_CAPACITY(ssc, &capacity,
19499 	    &lbasize, SD_PATH_DIRECT) != 0) {
19500 		SD_ERROR(SD_LOG_ERROR, un,
19501 		    "sd_target_change_task: fail to read capacity\n");
19502 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19503 		goto task_exit;
19504 	}
19505 
19506 	mutex_enter(SD_MUTEX(un));
19507 	if (capacity <= un->un_blockcount) {
19508 		mutex_exit(SD_MUTEX(un));
19509 		goto task_exit;
19510 	}
19511 
19512 	sd_update_block_info(un, lbasize, capacity);
19513 	mutex_exit(SD_MUTEX(un));
19514 
19515 	/*
19516 	 * If lun is EFI labeled and lun capacity is greater than the
19517 	 * capacity contained in the label, log a sys event.
19518 	 */
19519 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
19520 	    (void*)SD_PATH_DIRECT) == 0) {
19521 		mutex_enter(SD_MUTEX(un));
19522 		if (un->un_f_blockcount_is_valid &&
19523 		    un->un_blockcount > label_cap) {
19524 			mutex_exit(SD_MUTEX(un));
19525 			sd_log_lun_expansion_event(un, KM_SLEEP);
19526 		} else {
19527 			mutex_exit(SD_MUTEX(un));
19528 		}
19529 	}
19530 
19531 task_exit:
19532 	sd_ssc_fini(ssc);
19533 }
19534 
19535 
19536 /*
19537  *    Function: sd_log_dev_status_event
19538  *
19539  * Description: Log EC_dev_status sysevent
19540  *
19541  *     Context: Never called from interrupt context
19542  */
19543 static void
19544 sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag)
19545 {
19546 	int err;
19547 	char			*path;
19548 	nvlist_t		*attr_list;
19549 	size_t			n;
19550 
19551 	/* Allocate and build sysevent attribute list */
19552 	err = nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
19553 	if (err != 0) {
19554 		SD_ERROR(SD_LOG_ERROR, un,
19555 		    "sd_log_dev_status_event: fail to allocate space\n");
19556 		return;
19557 	}
19558 
19559 	path = kmem_alloc(MAXPATHLEN, km_flag);
19560 	if (path == NULL) {
19561 		nvlist_free(attr_list);
19562 		SD_ERROR(SD_LOG_ERROR, un,
19563 		    "sd_log_dev_status_event: fail to allocate space\n");
19564 		return;
19565 	}
19566 
19567 	n = snprintf(path, MAXPATHLEN, "/devices");
19568 	(void) ddi_pathname(SD_DEVINFO(un), path + n);
19569 	n = strlen(path);
19570 	n += snprintf(path + n, MAXPATHLEN - n, ":x");
19571 
19572 	/*
19573 	 * On receipt of this event, the ZFS sysevent module will scan
19574 	 * active zpools for child vdevs matching this physical path.
19575 	 * In order to catch both whole disk pools and those with an
19576 	 * EFI boot partition, generate separate sysevents for minor
19577 	 * node 'a' and 'b'.
19578 	 */
19579 	for (char c = 'a'; c < 'c'; c++) {
19580 		path[n - 1] = c;
19581 
19582 		err = nvlist_add_string(attr_list, DEV_PHYS_PATH, path);
19583 		if (err != 0) {
19584 			SD_ERROR(SD_LOG_ERROR, un,
19585 			    "sd_log_dev_status_event: fail to add attribute\n");
19586 			break;
19587 		}
19588 
19589 		err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR,
19590 		    EC_DEV_STATUS, esc, attr_list, NULL, km_flag);
19591 		if (err != DDI_SUCCESS) {
19592 			SD_ERROR(SD_LOG_ERROR, un,
19593 			    "sd_log_dev_status_event: fail to log sysevent\n");
19594 			break;
19595 		}
19596 	}
19597 
19598 	nvlist_free(attr_list);
19599 	kmem_free(path, MAXPATHLEN);
19600 }
19601 
19602 
19603 /*
19604  *    Function: sd_log_lun_expansion_event
19605  *
19606  * Description: Log lun expansion sys event
19607  *
19608  *     Context: Never called from interrupt context
19609  */
19610 static void
19611 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
19612 {
19613 	sd_log_dev_status_event(un, ESC_DEV_DLE, km_flag);
19614 }
19615 
19616 
19617 /*
19618  *    Function: sd_log_eject_request_event
19619  *
19620  * Description: Log eject request sysevent
19621  *
19622  *     Context: Never called from interrupt context
19623  */
19624 static void
19625 sd_log_eject_request_event(struct sd_lun *un, int km_flag)
19626 {
19627 	sd_log_dev_status_event(un, ESC_DEV_EJECT_REQUEST, km_flag);
19628 }
19629 
19630 
19631 /*
19632  *    Function: sd_media_change_task
19633  *
19634  * Description: Recovery action for CDROM to become available.
19635  *
19636  *     Context: Executes in a taskq() thread context
19637  */
19638 
19639 static void
19640 sd_media_change_task(void *arg)
19641 {
19642 	struct	scsi_pkt	*pktp = arg;
19643 	struct	sd_lun		*un;
19644 	struct	buf		*bp;
19645 	struct	sd_xbuf		*xp;
19646 	int	err		= 0;
19647 	int	retry_count	= 0;
19648 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
19649 	struct	sd_sense_info	si;
19650 
19651 	ASSERT(pktp != NULL);
19652 	bp = (struct buf *)pktp->pkt_private;
19653 	ASSERT(bp != NULL);
19654 	xp = SD_GET_XBUF(bp);
19655 	ASSERT(xp != NULL);
19656 	un = SD_GET_UN(bp);
19657 	ASSERT(un != NULL);
19658 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19659 	ASSERT(un->un_f_monitor_media_state);
19660 
19661 	si.ssi_severity = SCSI_ERR_INFO;
19662 	si.ssi_pfa_flag = FALSE;
19663 
19664 	/*
19665 	 * When a reset is issued on a CDROM, it takes a long time to
19666 	 * recover. First few attempts to read capacity and other things
19667 	 * related to handling unit attention fail (with a ASC 0x4 and
19668 	 * ASCQ 0x1). In that case we want to do enough retries and we want
19669 	 * to limit the retries in other cases of genuine failures like
19670 	 * no media in drive.
19671 	 */
19672 	while (retry_count++ < retry_limit) {
19673 		if ((err = sd_handle_mchange(un)) == 0) {
19674 			break;
19675 		}
19676 		if (err == EAGAIN) {
19677 			retry_limit = SD_UNIT_ATTENTION_RETRY;
19678 		}
19679 		/* Sleep for 0.5 sec. & try again */
19680 		delay(drv_usectohz(500000));
19681 	}
19682 
19683 	/*
19684 	 * Dispatch (retry or fail) the original command here,
19685 	 * along with appropriate console messages....
19686 	 *
19687 	 * Must grab the mutex before calling sd_retry_command,
19688 	 * sd_print_sense_msg and sd_return_failed_command.
19689 	 */
19690 	mutex_enter(SD_MUTEX(un));
19691 	if (err != SD_CMD_SUCCESS) {
19692 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
19693 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
19694 		si.ssi_severity = SCSI_ERR_FATAL;
19695 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
19696 		sd_return_failed_command(un, bp, EIO);
19697 	} else {
19698 		sd_retry_command(un, bp, SD_RETRIES_UA, sd_print_sense_msg,
19699 		    &si, EIO, (clock_t)0, NULL);
19700 	}
19701 	mutex_exit(SD_MUTEX(un));
19702 }
19703 
19704 
19705 
19706 /*
19707  *    Function: sd_handle_mchange
19708  *
19709  * Description: Perform geometry validation & other recovery when CDROM
19710  *		has been removed from drive.
19711  *
19712  * Return Code: 0 for success
19713  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
19714  *		sd_send_scsi_READ_CAPACITY()
19715  *
19716  *     Context: Executes in a taskq() thread context
19717  */
19718 
19719 static int
19720 sd_handle_mchange(struct sd_lun *un)
19721 {
19722 	uint64_t	capacity;
19723 	uint32_t	lbasize;
19724 	int		rval;
19725 	sd_ssc_t	*ssc;
19726 
19727 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19728 	ASSERT(un->un_f_monitor_media_state);
19729 
19730 	ssc = sd_ssc_init(un);
19731 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
19732 	    SD_PATH_DIRECT_PRIORITY);
19733 
19734 	if (rval != 0)
19735 		goto failed;
19736 
19737 	mutex_enter(SD_MUTEX(un));
19738 	sd_update_block_info(un, lbasize, capacity);
19739 
19740 	if (un->un_errstats != NULL) {
19741 		struct	sd_errstats *stp =
19742 		    (struct sd_errstats *)un->un_errstats->ks_data;
19743 		stp->sd_capacity.value.ui64 = (uint64_t)
19744 		    ((uint64_t)un->un_blockcount *
19745 		    (uint64_t)un->un_tgt_blocksize);
19746 	}
19747 
19748 	/*
19749 	 * Check if the media in the device is writable or not
19750 	 */
19751 	if (ISCD(un)) {
19752 		sd_check_for_writable_cd(ssc, SD_PATH_DIRECT_PRIORITY);
19753 	}
19754 
19755 	/*
19756 	 * Note: Maybe let the strategy/partitioning chain worry about getting
19757 	 * valid geometry.
19758 	 */
19759 	mutex_exit(SD_MUTEX(un));
19760 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
19761 
19762 
19763 	if (cmlb_validate(un->un_cmlbhandle, 0,
19764 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
19765 		sd_ssc_fini(ssc);
19766 		return (EIO);
19767 	} else {
19768 		if (un->un_f_pkstats_enabled) {
19769 			sd_set_pstats(un);
19770 			SD_TRACE(SD_LOG_IO_PARTITION, un,
19771 			    "sd_handle_mchange: un:0x%p pstats created and "
19772 			    "set\n", un);
19773 		}
19774 	}
19775 
19776 	/*
19777 	 * Try to lock the door
19778 	 */
19779 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
19780 	    SD_PATH_DIRECT_PRIORITY);
19781 failed:
19782 	if (rval != 0)
19783 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19784 	sd_ssc_fini(ssc);
19785 	return (rval);
19786 }
19787 
19788 
19789 /*
19790  *    Function: sd_send_scsi_DOORLOCK
19791  *
19792  * Description: Issue the scsi DOOR LOCK command
19793  *
19794  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19795  *                      structure for this target.
19796  *		flag  - SD_REMOVAL_ALLOW
19797  *			SD_REMOVAL_PREVENT
19798  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19799  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19800  *			to use the USCSI "direct" chain and bypass the normal
19801  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19802  *			command is issued as part of an error recovery action.
19803  *
19804  * Return Code: 0   - Success
19805  *		errno return code from sd_ssc_send()
19806  *
19807  *     Context: Can sleep.
19808  */
19809 
19810 static int
19811 sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag)
19812 {
19813 	struct scsi_extended_sense	sense_buf;
19814 	union scsi_cdb		cdb;
19815 	struct uscsi_cmd	ucmd_buf;
19816 	int			status;
19817 	struct sd_lun		*un;
19818 
19819 	ASSERT(ssc != NULL);
19820 	un = ssc->ssc_un;
19821 	ASSERT(un != NULL);
19822 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19823 
19824 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
19825 
19826 	/* already determined doorlock is not supported, fake success */
19827 	if (un->un_f_doorlock_supported == FALSE) {
19828 		return (0);
19829 	}
19830 
19831 	/*
19832 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
19833 	 * ignore the command so we can complete the eject
19834 	 * operation.
19835 	 */
19836 	if (flag == SD_REMOVAL_PREVENT) {
19837 		mutex_enter(SD_MUTEX(un));
19838 		if (un->un_f_ejecting == TRUE) {
19839 			mutex_exit(SD_MUTEX(un));
19840 			return (EAGAIN);
19841 		}
19842 		mutex_exit(SD_MUTEX(un));
19843 	}
19844 
19845 	bzero(&cdb, sizeof (cdb));
19846 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19847 
19848 	cdb.scc_cmd = SCMD_DOORLOCK;
19849 	cdb.cdb_opaque[4] = (uchar_t)flag;
19850 
19851 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19852 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19853 	ucmd_buf.uscsi_bufaddr	= NULL;
19854 	ucmd_buf.uscsi_buflen	= 0;
19855 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19856 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19857 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19858 	ucmd_buf.uscsi_timeout	= 15;
19859 
19860 	SD_TRACE(SD_LOG_IO, un,
19861 	    "sd_send_scsi_DOORLOCK: returning sd_ssc_send\n");
19862 
19863 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19864 	    UIO_SYSSPACE, path_flag);
19865 
19866 	if (status == 0)
19867 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19868 
19869 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
19870 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19871 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
19872 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19873 
19874 		/* fake success and skip subsequent doorlock commands */
19875 		un->un_f_doorlock_supported = FALSE;
19876 		return (0);
19877 	}
19878 
19879 	return (status);
19880 }
19881 
19882 /*
19883  *    Function: sd_send_scsi_READ_CAPACITY
19884  *
19885  * Description: This routine uses the scsi READ CAPACITY command to determine
19886  *		the device capacity in number of blocks and the device native
19887  *		block size. If this function returns a failure, then the
19888  *		values in *capp and *lbap are undefined.  If the capacity
19889  *		returned is 0xffffffff then the lun is too large for a
19890  *		normal READ CAPACITY command and the results of a
19891  *		READ CAPACITY 16 will be used instead.
19892  *
19893  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
19894  *		capp - ptr to unsigned 64-bit variable to receive the
19895  *			capacity value from the command.
19896  *		lbap - ptr to unsigned 32-bit varaible to receive the
19897  *			block size value from the command
19898  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19899  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19900  *			to use the USCSI "direct" chain and bypass the normal
19901  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19902  *			command is issued as part of an error recovery action.
19903  *
19904  * Return Code: 0   - Success
19905  *		EIO - IO error
19906  *		EACCES - Reservation conflict detected
19907  *		EAGAIN - Device is becoming ready
19908  *		errno return code from sd_ssc_send()
19909  *
19910  *     Context: Can sleep.  Blocks until command completes.
19911  */
19912 
19913 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
19914 
19915 static int
19916 sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
19917     int path_flag)
19918 {
19919 	struct	scsi_extended_sense	sense_buf;
19920 	struct	uscsi_cmd	ucmd_buf;
19921 	union	scsi_cdb	cdb;
19922 	uint32_t		*capacity_buf;
19923 	uint64_t		capacity;
19924 	uint32_t		lbasize;
19925 	uint32_t		pbsize;
19926 	int			status;
19927 	struct sd_lun		*un;
19928 
19929 	ASSERT(ssc != NULL);
19930 
19931 	un = ssc->ssc_un;
19932 	ASSERT(un != NULL);
19933 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19934 	ASSERT(capp != NULL);
19935 	ASSERT(lbap != NULL);
19936 
19937 	SD_TRACE(SD_LOG_IO, un,
19938 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19939 
19940 	/*
19941 	 * First send a READ_CAPACITY command to the target.
19942 	 * (This command is mandatory under SCSI-2.)
19943 	 *
19944 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
19945 	 * Medium Indicator bit is cleared.  The address field must be
19946 	 * zero if the PMI bit is zero.
19947 	 */
19948 	bzero(&cdb, sizeof (cdb));
19949 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19950 
19951 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
19952 
19953 	cdb.scc_cmd = SCMD_READ_CAPACITY;
19954 
19955 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19956 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19957 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
19958 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
19959 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19960 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19961 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19962 	ucmd_buf.uscsi_timeout	= 60;
19963 
19964 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19965 	    UIO_SYSSPACE, path_flag);
19966 
19967 	switch (status) {
19968 	case 0:
19969 		/* Return failure if we did not get valid capacity data. */
19970 		if (ucmd_buf.uscsi_resid != 0) {
19971 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19972 			    "sd_send_scsi_READ_CAPACITY received invalid "
19973 			    "capacity data");
19974 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19975 			return (EIO);
19976 		}
19977 		/*
19978 		 * Read capacity and block size from the READ CAPACITY 10 data.
19979 		 * This data may be adjusted later due to device specific
19980 		 * issues.
19981 		 *
19982 		 * According to the SCSI spec, the READ CAPACITY 10
19983 		 * command returns the following:
19984 		 *
19985 		 *  bytes 0-3: Maximum logical block address available.
19986 		 *		(MSB in byte:0 & LSB in byte:3)
19987 		 *
19988 		 *  bytes 4-7: Block length in bytes
19989 		 *		(MSB in byte:4 & LSB in byte:7)
19990 		 *
19991 		 */
19992 		capacity = BE_32(capacity_buf[0]);
19993 		lbasize = BE_32(capacity_buf[1]);
19994 
19995 		/*
19996 		 * Done with capacity_buf
19997 		 */
19998 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19999 
20000 		/*
20001 		 * if the reported capacity is set to all 0xf's, then
20002 		 * this disk is too large and requires SBC-2 commands.
20003 		 * Reissue the request using READ CAPACITY 16.
20004 		 */
20005 		if (capacity == 0xffffffff) {
20006 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20007 			status = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity,
20008 			    &lbasize, &pbsize, path_flag);
20009 			if (status != 0) {
20010 				return (status);
20011 			} else {
20012 				goto rc16_done;
20013 			}
20014 		}
20015 		break;	/* Success! */
20016 	case EIO:
20017 		switch (ucmd_buf.uscsi_status) {
20018 		case STATUS_RESERVATION_CONFLICT:
20019 			status = EACCES;
20020 			break;
20021 		case STATUS_CHECK:
20022 			/*
20023 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20024 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20025 			 */
20026 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20027 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20028 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20029 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20030 				return (EAGAIN);
20031 			}
20032 			break;
20033 		default:
20034 			break;
20035 		}
20036 		/* FALLTHRU */
20037 	default:
20038 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
20039 		return (status);
20040 	}
20041 
20042 	/*
20043 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20044 	 * (2352 and 0 are common) so for these devices always force the value
20045 	 * to 2048 as required by the ATAPI specs.
20046 	 */
20047 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20048 		lbasize = 2048;
20049 	}
20050 
20051 	/*
20052 	 * Get the maximum LBA value from the READ CAPACITY data.
20053 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20054 	 * was cleared when issuing the command. This means that the LBA
20055 	 * returned from the device is the LBA of the last logical block
20056 	 * on the logical unit.  The actual logical block count will be
20057 	 * this value plus one.
20058 	 */
20059 	capacity += 1;
20060 
20061 	/*
20062 	 * Currently, for removable media, the capacity is saved in terms
20063 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20064 	 */
20065 	if (un->un_f_has_removable_media)
20066 		capacity *= (lbasize / un->un_sys_blocksize);
20067 
20068 rc16_done:
20069 
20070 	/*
20071 	 * Copy the values from the READ CAPACITY command into the space
20072 	 * provided by the caller.
20073 	 */
20074 	*capp = capacity;
20075 	*lbap = lbasize;
20076 
20077 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
20078 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
20079 
20080 	/*
20081 	 * Both the lbasize and capacity from the device must be nonzero,
20082 	 * otherwise we assume that the values are not valid and return
20083 	 * failure to the caller. (4203735)
20084 	 */
20085 	if ((capacity == 0) || (lbasize == 0)) {
20086 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20087 		    "sd_send_scsi_READ_CAPACITY received invalid value "
20088 		    "capacity %llu lbasize %d", capacity, lbasize);
20089 		return (EIO);
20090 	}
20091 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20092 	return (0);
20093 }
20094 
20095 /*
20096  *    Function: sd_send_scsi_READ_CAPACITY_16
20097  *
20098  * Description: This routine uses the scsi READ CAPACITY 16 command to
20099  *		determine the device capacity in number of blocks and the
20100  *		device native block size.  If this function returns a failure,
20101  *		then the values in *capp and *lbap are undefined.
20102  *		This routine should be called by sd_send_scsi_READ_CAPACITY
20103  *              which will apply any device specific adjustments to capacity
20104  *              and lbasize. One exception is it is also called by
20105  *              sd_get_media_info_ext. In that function, there is no need to
20106  *              adjust the capacity and lbasize.
20107  *
20108  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
20109  *		capp - ptr to unsigned 64-bit variable to receive the
20110  *			capacity value from the command.
20111  *		lbap - ptr to unsigned 32-bit varaible to receive the
20112  *			block size value from the command
20113  *              psp  - ptr to unsigned 32-bit variable to receive the
20114  *                      physical block size value from the command
20115  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20116  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20117  *			to use the USCSI "direct" chain and bypass the normal
20118  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
20119  *			this command is issued as part of an error recovery
20120  *			action.
20121  *
20122  * Return Code: 0   - Success
20123  *		EIO - IO error
20124  *		EACCES - Reservation conflict detected
20125  *		EAGAIN - Device is becoming ready
20126  *		errno return code from sd_ssc_send()
20127  *
20128  *     Context: Can sleep.  Blocks until command completes.
20129  */
20130 
20131 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
20132 
20133 static int
20134 sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
20135     uint32_t *psp, int path_flag)
20136 {
20137 	struct	scsi_extended_sense	sense_buf;
20138 	struct	uscsi_cmd	ucmd_buf;
20139 	union	scsi_cdb	cdb;
20140 	uint64_t		*capacity16_buf;
20141 	uint64_t		capacity;
20142 	uint32_t		lbasize;
20143 	uint32_t		pbsize;
20144 	uint32_t		lbpb_exp;
20145 	int			status;
20146 	struct sd_lun		*un;
20147 
20148 	ASSERT(ssc != NULL);
20149 
20150 	un = ssc->ssc_un;
20151 	ASSERT(un != NULL);
20152 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20153 	ASSERT(capp != NULL);
20154 	ASSERT(lbap != NULL);
20155 
20156 	SD_TRACE(SD_LOG_IO, un,
20157 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20158 
20159 	/*
20160 	 * First send a READ_CAPACITY_16 command to the target.
20161 	 *
20162 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
20163 	 * Medium Indicator bit is cleared.  The address field must be
20164 	 * zero if the PMI bit is zero.
20165 	 */
20166 	bzero(&cdb, sizeof (cdb));
20167 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20168 
20169 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
20170 
20171 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20172 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
20173 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
20174 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
20175 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20176 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20177 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20178 	ucmd_buf.uscsi_timeout	= 60;
20179 
20180 	/*
20181 	 * Read Capacity (16) is a Service Action In command.  One
20182 	 * command byte (0x9E) is overloaded for multiple operations,
20183 	 * with the second CDB byte specifying the desired operation
20184 	 */
20185 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
20186 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
20187 
20188 	/*
20189 	 * Fill in allocation length field
20190 	 */
20191 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
20192 
20193 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20194 	    UIO_SYSSPACE, path_flag);
20195 
20196 	switch (status) {
20197 	case 0:
20198 		/* Return failure if we did not get valid capacity data. */
20199 		if (ucmd_buf.uscsi_resid > 20) {
20200 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20201 			    "sd_send_scsi_READ_CAPACITY_16 received invalid "
20202 			    "capacity data");
20203 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20204 			return (EIO);
20205 		}
20206 
20207 		/*
20208 		 * Read capacity and block size from the READ CAPACITY 16 data.
20209 		 * This data may be adjusted later due to device specific
20210 		 * issues.
20211 		 *
20212 		 * According to the SCSI spec, the READ CAPACITY 16
20213 		 * command returns the following:
20214 		 *
20215 		 *  bytes 0-7: Maximum logical block address available.
20216 		 *		(MSB in byte:0 & LSB in byte:7)
20217 		 *
20218 		 *  bytes 8-11: Block length in bytes
20219 		 *		(MSB in byte:8 & LSB in byte:11)
20220 		 *
20221 		 *  byte 13: LOGICAL BLOCKS PER PHYSICAL BLOCK EXPONENT
20222 		 *
20223 		 *  byte 14:
20224 		 *	bit 7: Thin-Provisioning Enabled
20225 		 *	bit 6: Thin-Provisioning Read Zeros
20226 		 */
20227 		capacity = BE_64(capacity16_buf[0]);
20228 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
20229 		lbpb_exp = (BE_64(capacity16_buf[1]) >> 16) & 0x0f;
20230 
20231 		un->un_thin_flags = 0;
20232 		if (((uint8_t *)capacity16_buf)[14] & (1 << 7))
20233 			un->un_thin_flags |= SD_THIN_PROV_ENABLED;
20234 		if (((uint8_t *)capacity16_buf)[14] & (1 << 6))
20235 			un->un_thin_flags |= SD_THIN_PROV_READ_ZEROS;
20236 
20237 		pbsize = lbasize << lbpb_exp;
20238 
20239 		/*
20240 		 * Done with capacity16_buf
20241 		 */
20242 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20243 
20244 		/*
20245 		 * if the reported capacity is set to all 0xf's, then
20246 		 * this disk is too large.  This could only happen with
20247 		 * a device that supports LBAs larger than 64 bits which
20248 		 * are not defined by any current T10 standards.
20249 		 */
20250 		if (capacity == 0xffffffffffffffff) {
20251 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20252 			    "disk is too large");
20253 			return (EIO);
20254 		}
20255 		break;	/* Success! */
20256 	case EIO:
20257 		switch (ucmd_buf.uscsi_status) {
20258 		case STATUS_RESERVATION_CONFLICT:
20259 			status = EACCES;
20260 			break;
20261 		case STATUS_CHECK:
20262 			/*
20263 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20264 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20265 			 */
20266 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20267 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20268 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20269 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20270 				return (EAGAIN);
20271 			}
20272 			break;
20273 		default:
20274 			break;
20275 		}
20276 		/* FALLTHRU */
20277 	default:
20278 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20279 		return (status);
20280 	}
20281 
20282 	/*
20283 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20284 	 * (2352 and 0 are common) so for these devices always force the value
20285 	 * to 2048 as required by the ATAPI specs.
20286 	 */
20287 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20288 		lbasize = 2048;
20289 	}
20290 
20291 	/*
20292 	 * Get the maximum LBA value from the READ CAPACITY 16 data.
20293 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20294 	 * was cleared when issuing the command. This means that the LBA
20295 	 * returned from the device is the LBA of the last logical block
20296 	 * on the logical unit.  The actual logical block count will be
20297 	 * this value plus one.
20298 	 */
20299 	capacity += 1;
20300 
20301 	/*
20302 	 * Currently, for removable media, the capacity is saved in terms
20303 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20304 	 */
20305 	if (un->un_f_has_removable_media)
20306 		capacity *= (lbasize / un->un_sys_blocksize);
20307 
20308 	*capp = capacity;
20309 	*lbap = lbasize;
20310 	*psp = pbsize;
20311 
20312 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
20313 	    "capacity:0x%llx  lbasize:0x%x, pbsize: 0x%x\n",
20314 	    capacity, lbasize, pbsize);
20315 
20316 	if ((capacity == 0) || (lbasize == 0) || (pbsize == 0)) {
20317 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20318 		    "sd_send_scsi_READ_CAPACITY_16 received invalid value "
20319 		    "capacity %llu lbasize %d pbsize %d", capacity, lbasize);
20320 		return (EIO);
20321 	}
20322 
20323 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20324 	return (0);
20325 }
20326 
20327 
20328 /*
20329  *    Function: sd_send_scsi_START_STOP_UNIT
20330  *
20331  * Description: Issue a scsi START STOP UNIT command to the target.
20332  *
20333  *   Arguments: ssc    - ssc contatins pointer to driver soft state (unit)
20334  *                       structure for this target.
20335  *      pc_flag - SD_POWER_CONDITION
20336  *                SD_START_STOP
20337  *		flag  - SD_TARGET_START
20338  *			SD_TARGET_STOP
20339  *			SD_TARGET_EJECT
20340  *			SD_TARGET_CLOSE
20341  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20342  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20343  *			to use the USCSI "direct" chain and bypass the normal
20344  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
20345  *			command is issued as part of an error recovery action.
20346  *
20347  * Return Code: 0   - Success
20348  *		EIO - IO error
20349  *		EACCES - Reservation conflict detected
20350  *		ENXIO  - Not Ready, medium not present
20351  *		errno return code from sd_ssc_send()
20352  *
20353  *     Context: Can sleep.
20354  */
20355 
20356 static int
20357 sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag, int flag,
20358     int path_flag)
20359 {
20360 	struct	scsi_extended_sense	sense_buf;
20361 	union scsi_cdb		cdb;
20362 	struct uscsi_cmd	ucmd_buf;
20363 	int			status;
20364 	struct sd_lun		*un;
20365 
20366 	ASSERT(ssc != NULL);
20367 	un = ssc->ssc_un;
20368 	ASSERT(un != NULL);
20369 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20370 
20371 	SD_TRACE(SD_LOG_IO, un,
20372 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
20373 
20374 	if (un->un_f_check_start_stop &&
20375 	    (pc_flag == SD_START_STOP) &&
20376 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
20377 	    (un->un_f_start_stop_supported != TRUE)) {
20378 		return (0);
20379 	}
20380 
20381 	/*
20382 	 * If we are performing an eject operation and
20383 	 * we receive any command other than SD_TARGET_EJECT
20384 	 * we should immediately return.
20385 	 */
20386 	if (flag != SD_TARGET_EJECT) {
20387 		mutex_enter(SD_MUTEX(un));
20388 		if (un->un_f_ejecting == TRUE) {
20389 			mutex_exit(SD_MUTEX(un));
20390 			return (EAGAIN);
20391 		}
20392 		mutex_exit(SD_MUTEX(un));
20393 	}
20394 
20395 	bzero(&cdb, sizeof (cdb));
20396 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20397 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20398 
20399 	cdb.scc_cmd = SCMD_START_STOP;
20400 	cdb.cdb_opaque[4] = (pc_flag == SD_POWER_CONDITION) ?
20401 	    (uchar_t)(flag << 4) : (uchar_t)flag;
20402 
20403 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20404 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20405 	ucmd_buf.uscsi_bufaddr	= NULL;
20406 	ucmd_buf.uscsi_buflen	= 0;
20407 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20408 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20409 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20410 	ucmd_buf.uscsi_timeout	= 200;
20411 
20412 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20413 	    UIO_SYSSPACE, path_flag);
20414 
20415 	switch (status) {
20416 	case 0:
20417 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
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 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
20426 				switch (scsi_sense_key(
20427 				    (uint8_t *)&sense_buf)) {
20428 				case KEY_ILLEGAL_REQUEST:
20429 					status = ENOTSUP;
20430 					break;
20431 				case KEY_NOT_READY:
20432 					if (scsi_sense_asc(
20433 					    (uint8_t *)&sense_buf)
20434 					    == 0x3A) {
20435 						status = ENXIO;
20436 					}
20437 					break;
20438 				default:
20439 					break;
20440 				}
20441 			}
20442 			break;
20443 		default:
20444 			break;
20445 		}
20446 		break;
20447 	default:
20448 		break;
20449 	}
20450 
20451 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
20452 
20453 	return (status);
20454 }
20455 
20456 
20457 /*
20458  *    Function: sd_start_stop_unit_callback
20459  *
20460  * Description: timeout(9F) callback to begin recovery process for a
20461  *		device that has spun down.
20462  *
20463  *   Arguments: arg - pointer to associated softstate struct.
20464  *
20465  *     Context: Executes in a timeout(9F) thread context
20466  */
20467 
20468 static void
20469 sd_start_stop_unit_callback(void *arg)
20470 {
20471 	struct sd_lun	*un = arg;
20472 	ASSERT(un != NULL);
20473 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20474 
20475 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
20476 
20477 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
20478 }
20479 
20480 
20481 /*
20482  *    Function: sd_start_stop_unit_task
20483  *
20484  * Description: Recovery procedure when a drive is spun down.
20485  *
20486  *   Arguments: arg - pointer to associated softstate struct.
20487  *
20488  *     Context: Executes in a taskq() thread context
20489  */
20490 
20491 static void
20492 sd_start_stop_unit_task(void *arg)
20493 {
20494 	struct sd_lun	*un = arg;
20495 	sd_ssc_t	*ssc;
20496 	int		power_level;
20497 	int		rval;
20498 
20499 	ASSERT(un != NULL);
20500 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20501 
20502 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
20503 
20504 	/*
20505 	 * Some unformatted drives report not ready error, no need to
20506 	 * restart if format has been initiated.
20507 	 */
20508 	mutex_enter(SD_MUTEX(un));
20509 	if (un->un_f_format_in_progress == TRUE) {
20510 		mutex_exit(SD_MUTEX(un));
20511 		return;
20512 	}
20513 	mutex_exit(SD_MUTEX(un));
20514 
20515 	ssc = sd_ssc_init(un);
20516 	/*
20517 	 * When a START STOP command is issued from here, it is part of a
20518 	 * failure recovery operation and must be issued before any other
20519 	 * commands, including any pending retries. Thus it must be sent
20520 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
20521 	 * succeeds or not, we will start I/O after the attempt.
20522 	 * If power condition is supported and the current power level
20523 	 * is capable of performing I/O, we should set the power condition
20524 	 * to that level. Otherwise, set the power condition to ACTIVE.
20525 	 */
20526 	if (un->un_f_power_condition_supported) {
20527 		mutex_enter(SD_MUTEX(un));
20528 		ASSERT(SD_PM_IS_LEVEL_VALID(un, un->un_power_level));
20529 		power_level = sd_pwr_pc.ran_perf[un->un_power_level]
20530 		    > 0 ? un->un_power_level : SD_SPINDLE_ACTIVE;
20531 		mutex_exit(SD_MUTEX(un));
20532 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
20533 		    sd_pl2pc[power_level], SD_PATH_DIRECT_PRIORITY);
20534 	} else {
20535 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
20536 		    SD_TARGET_START, SD_PATH_DIRECT_PRIORITY);
20537 	}
20538 
20539 	if (rval != 0)
20540 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20541 	sd_ssc_fini(ssc);
20542 	/*
20543 	 * The above call blocks until the START_STOP_UNIT command completes.
20544 	 * Now that it has completed, we must re-try the original IO that
20545 	 * received the NOT READY condition in the first place. There are
20546 	 * three possible conditions here:
20547 	 *
20548 	 *  (1) The original IO is on un_retry_bp.
20549 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
20550 	 *	is NULL.
20551 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
20552 	 *	points to some other, unrelated bp.
20553 	 *
20554 	 * For each case, we must call sd_start_cmds() with un_retry_bp
20555 	 * as the argument. If un_retry_bp is NULL, this will initiate
20556 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
20557 	 * then this will process the bp on un_retry_bp. That may or may not
20558 	 * be the original IO, but that does not matter: the important thing
20559 	 * is to keep the IO processing going at this point.
20560 	 *
20561 	 * Note: This is a very specific error recovery sequence associated
20562 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
20563 	 * serialize the I/O with completion of the spin-up.
20564 	 */
20565 	mutex_enter(SD_MUTEX(un));
20566 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
20567 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
20568 	    un, un->un_retry_bp);
20569 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
20570 	sd_start_cmds(un, un->un_retry_bp);
20571 	mutex_exit(SD_MUTEX(un));
20572 
20573 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
20574 }
20575 
20576 
20577 /*
20578  *    Function: sd_send_scsi_INQUIRY
20579  *
20580  * Description: Issue the scsi INQUIRY command.
20581  *
20582  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20583  *                      structure for this target.
20584  *		bufaddr
20585  *		buflen
20586  *		evpd
20587  *		page_code
20588  *		page_length
20589  *
20590  * Return Code: 0   - Success
20591  *		errno return code from sd_ssc_send()
20592  *
20593  *     Context: Can sleep. Does not return until command is completed.
20594  */
20595 
20596 static int
20597 sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr, size_t buflen,
20598     uchar_t evpd, uchar_t page_code, size_t *residp)
20599 {
20600 	union scsi_cdb		cdb;
20601 	struct uscsi_cmd	ucmd_buf;
20602 	int			status;
20603 	struct sd_lun		*un;
20604 
20605 	ASSERT(ssc != NULL);
20606 	un = ssc->ssc_un;
20607 	ASSERT(un != NULL);
20608 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20609 	ASSERT(bufaddr != NULL);
20610 
20611 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
20612 
20613 	bzero(&cdb, sizeof (cdb));
20614 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20615 	bzero(bufaddr, buflen);
20616 
20617 	cdb.scc_cmd = SCMD_INQUIRY;
20618 	cdb.cdb_opaque[1] = evpd;
20619 	cdb.cdb_opaque[2] = page_code;
20620 	FORMG0COUNT(&cdb, buflen);
20621 
20622 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20623 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20624 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20625 	ucmd_buf.uscsi_buflen	= buflen;
20626 	ucmd_buf.uscsi_rqbuf	= NULL;
20627 	ucmd_buf.uscsi_rqlen	= 0;
20628 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
20629 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
20630 
20631 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20632 	    UIO_SYSSPACE, SD_PATH_DIRECT);
20633 
20634 	/*
20635 	 * Only handle status == 0, the upper-level caller
20636 	 * will put different assessment based on the context.
20637 	 */
20638 	if (status == 0)
20639 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20640 
20641 	if ((status == 0) && (residp != NULL)) {
20642 		*residp = ucmd_buf.uscsi_resid;
20643 	}
20644 
20645 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
20646 
20647 	return (status);
20648 }
20649 
20650 
20651 /*
20652  *    Function: sd_send_scsi_TEST_UNIT_READY
20653  *
20654  * Description: Issue the scsi TEST UNIT READY command.
20655  *		This routine can be told to set the flag USCSI_DIAGNOSE to
20656  *		prevent retrying failed commands. Use this when the intent
20657  *		is either to check for device readiness, to clear a Unit
20658  *		Attention, or to clear any outstanding sense data.
20659  *		However under specific conditions the expected behavior
20660  *		is for retries to bring a device ready, so use the flag
20661  *		with caution.
20662  *
20663  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20664  *                      structure for this target.
20665  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
20666  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
20667  *			0: dont check for media present, do retries on cmd.
20668  *
20669  * Return Code: 0   - Success
20670  *		EIO - IO error
20671  *		EACCES - Reservation conflict detected
20672  *		ENXIO  - Not Ready, medium not present
20673  *		errno return code from sd_ssc_send()
20674  *
20675  *     Context: Can sleep. Does not return until command is completed.
20676  */
20677 
20678 static int
20679 sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag)
20680 {
20681 	struct	scsi_extended_sense	sense_buf;
20682 	union scsi_cdb		cdb;
20683 	struct uscsi_cmd	ucmd_buf;
20684 	int			status;
20685 	struct sd_lun		*un;
20686 
20687 	ASSERT(ssc != NULL);
20688 	un = ssc->ssc_un;
20689 	ASSERT(un != NULL);
20690 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20691 
20692 	SD_TRACE(SD_LOG_IO, un,
20693 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
20694 
20695 	/*
20696 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
20697 	 * timeouts when they receive a TUR and the queue is not empty. Check
20698 	 * the configuration flag set during attach (indicating the drive has
20699 	 * this firmware bug) and un_ncmds_in_transport before issuing the
20700 	 * TUR. If there are
20701 	 * pending commands return success, this is a bit arbitrary but is ok
20702 	 * for non-removables (i.e. the eliteI disks) and non-clustering
20703 	 * configurations.
20704 	 */
20705 	if (un->un_f_cfg_tur_check == TRUE) {
20706 		mutex_enter(SD_MUTEX(un));
20707 		if (un->un_ncmds_in_transport != 0) {
20708 			mutex_exit(SD_MUTEX(un));
20709 			return (0);
20710 		}
20711 		mutex_exit(SD_MUTEX(un));
20712 	}
20713 
20714 	bzero(&cdb, sizeof (cdb));
20715 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20716 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20717 
20718 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
20719 
20720 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20721 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20722 	ucmd_buf.uscsi_bufaddr	= NULL;
20723 	ucmd_buf.uscsi_buflen	= 0;
20724 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20725 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20726 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20727 
20728 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
20729 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
20730 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
20731 	}
20732 	ucmd_buf.uscsi_timeout	= 60;
20733 
20734 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20735 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
20736 	    SD_PATH_STANDARD));
20737 
20738 	switch (status) {
20739 	case 0:
20740 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20741 		break;	/* Success! */
20742 	case EIO:
20743 		switch (ucmd_buf.uscsi_status) {
20744 		case STATUS_RESERVATION_CONFLICT:
20745 			status = EACCES;
20746 			break;
20747 		case STATUS_CHECK:
20748 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
20749 				break;
20750 			}
20751 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20752 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20753 			    KEY_NOT_READY) &&
20754 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
20755 				status = ENXIO;
20756 			}
20757 			break;
20758 		default:
20759 			break;
20760 		}
20761 		break;
20762 	default:
20763 		break;
20764 	}
20765 
20766 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
20767 
20768 	return (status);
20769 }
20770 
20771 /*
20772  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
20773  *
20774  * Description: Issue the scsi PERSISTENT RESERVE IN command.
20775  *
20776  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20777  *                      structure for this target.
20778  *
20779  * Return Code: 0   - Success
20780  *		EACCES
20781  *		ENOTSUP
20782  *		errno return code from sd_ssc_send()
20783  *
20784  *     Context: Can sleep. Does not return until command is completed.
20785  */
20786 
20787 static int
20788 sd_send_scsi_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc, uchar_t usr_cmd,
20789     uint16_t data_len, uchar_t *data_bufp)
20790 {
20791 	struct scsi_extended_sense	sense_buf;
20792 	union scsi_cdb		cdb;
20793 	struct uscsi_cmd	ucmd_buf;
20794 	int			status;
20795 	int			no_caller_buf = FALSE;
20796 	struct sd_lun		*un;
20797 
20798 	ASSERT(ssc != NULL);
20799 	un = ssc->ssc_un;
20800 	ASSERT(un != NULL);
20801 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20802 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
20803 
20804 	SD_TRACE(SD_LOG_IO, un,
20805 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
20806 
20807 	bzero(&cdb, sizeof (cdb));
20808 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20809 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20810 	if (data_bufp == NULL) {
20811 		/* Allocate a default buf if the caller did not give one */
20812 		ASSERT(data_len == 0);
20813 		data_len  = MHIOC_RESV_KEY_SIZE;
20814 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
20815 		no_caller_buf = TRUE;
20816 	}
20817 
20818 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
20819 	cdb.cdb_opaque[1] = usr_cmd;
20820 	FORMG1COUNT(&cdb, data_len);
20821 
20822 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20823 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20824 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
20825 	ucmd_buf.uscsi_buflen	= data_len;
20826 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20827 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20828 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20829 	ucmd_buf.uscsi_timeout	= 60;
20830 
20831 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20832 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20833 
20834 	switch (status) {
20835 	case 0:
20836 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20837 
20838 		break;	/* Success! */
20839 	case EIO:
20840 		switch (ucmd_buf.uscsi_status) {
20841 		case STATUS_RESERVATION_CONFLICT:
20842 			status = EACCES;
20843 			break;
20844 		case STATUS_CHECK:
20845 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20846 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20847 			    KEY_ILLEGAL_REQUEST)) {
20848 				status = ENOTSUP;
20849 			}
20850 			break;
20851 		default:
20852 			break;
20853 		}
20854 		break;
20855 	default:
20856 		break;
20857 	}
20858 
20859 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
20860 
20861 	if (no_caller_buf == TRUE) {
20862 		kmem_free(data_bufp, data_len);
20863 	}
20864 
20865 	return (status);
20866 }
20867 
20868 
20869 /*
20870  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
20871  *
20872  * Description: This routine is the driver entry point for handling CD-ROM
20873  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
20874  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
20875  *		device.
20876  *
20877  *   Arguments: ssc  -  ssc contains un - pointer to soft state struct
20878  *                      for the target.
20879  *		usr_cmd SCSI-3 reservation facility command (one of
20880  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
20881  *			SD_SCSI3_PREEMPTANDABORT, SD_SCSI3_CLEAR)
20882  *		usr_bufp - user provided pointer register, reserve descriptor or
20883  *			preempt and abort structure (mhioc_register_t,
20884  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
20885  *
20886  * Return Code: 0   - Success
20887  *		EACCES
20888  *		ENOTSUP
20889  *		errno return code from sd_ssc_send()
20890  *
20891  *     Context: Can sleep. Does not return until command is completed.
20892  */
20893 
20894 static int
20895 sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc, uchar_t usr_cmd,
20896     uchar_t *usr_bufp)
20897 {
20898 	struct scsi_extended_sense	sense_buf;
20899 	union scsi_cdb		cdb;
20900 	struct uscsi_cmd	ucmd_buf;
20901 	int			status;
20902 	uchar_t			data_len = sizeof (sd_prout_t);
20903 	sd_prout_t		*prp;
20904 	struct sd_lun		*un;
20905 
20906 	ASSERT(ssc != NULL);
20907 	un = ssc->ssc_un;
20908 	ASSERT(un != NULL);
20909 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20910 	ASSERT(data_len == 24);	/* required by scsi spec */
20911 
20912 	SD_TRACE(SD_LOG_IO, un,
20913 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
20914 
20915 	if (usr_bufp == NULL) {
20916 		return (EINVAL);
20917 	}
20918 
20919 	bzero(&cdb, sizeof (cdb));
20920 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20921 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20922 	prp = kmem_zalloc(data_len, KM_SLEEP);
20923 
20924 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
20925 	cdb.cdb_opaque[1] = usr_cmd;
20926 	FORMG1COUNT(&cdb, data_len);
20927 
20928 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20929 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20930 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
20931 	ucmd_buf.uscsi_buflen	= data_len;
20932 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20933 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20934 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
20935 	ucmd_buf.uscsi_timeout	= 60;
20936 
20937 	switch (usr_cmd) {
20938 	case SD_SCSI3_REGISTER: {
20939 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
20940 
20941 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20942 		bcopy(ptr->newkey.key, prp->service_key,
20943 		    MHIOC_RESV_KEY_SIZE);
20944 		prp->aptpl = ptr->aptpl;
20945 		break;
20946 	}
20947 	case SD_SCSI3_CLEAR: {
20948 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
20949 
20950 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20951 		break;
20952 	}
20953 	case SD_SCSI3_RESERVE:
20954 	case SD_SCSI3_RELEASE: {
20955 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
20956 
20957 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20958 		prp->scope_address = BE_32(ptr->scope_specific_addr);
20959 		cdb.cdb_opaque[2] = ptr->type;
20960 		break;
20961 	}
20962 	case SD_SCSI3_PREEMPTANDABORT: {
20963 		mhioc_preemptandabort_t *ptr =
20964 		    (mhioc_preemptandabort_t *)usr_bufp;
20965 
20966 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20967 		bcopy(ptr->victim_key.key, prp->service_key,
20968 		    MHIOC_RESV_KEY_SIZE);
20969 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
20970 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
20971 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
20972 		break;
20973 	}
20974 	case SD_SCSI3_REGISTERANDIGNOREKEY:
20975 	{
20976 		mhioc_registerandignorekey_t *ptr;
20977 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
20978 		bcopy(ptr->newkey.key,
20979 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
20980 		prp->aptpl = ptr->aptpl;
20981 		break;
20982 	}
20983 	default:
20984 		ASSERT(FALSE);
20985 		break;
20986 	}
20987 
20988 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20989 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20990 
20991 	switch (status) {
20992 	case 0:
20993 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20994 		break;	/* Success! */
20995 	case EIO:
20996 		switch (ucmd_buf.uscsi_status) {
20997 		case STATUS_RESERVATION_CONFLICT:
20998 			status = EACCES;
20999 			break;
21000 		case STATUS_CHECK:
21001 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
21002 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
21003 			    KEY_ILLEGAL_REQUEST)) {
21004 				status = ENOTSUP;
21005 			}
21006 			break;
21007 		default:
21008 			break;
21009 		}
21010 		break;
21011 	default:
21012 		break;
21013 	}
21014 
21015 	kmem_free(prp, data_len);
21016 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
21017 	return (status);
21018 }
21019 
21020 
21021 /*
21022  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
21023  *
21024  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
21025  *
21026  *   Arguments: un - pointer to the target's soft state struct
21027  *              dkc - pointer to the callback structure
21028  *
21029  * Return Code: 0 - success
21030  *		errno-type error code
21031  *
21032  *     Context: kernel thread context only.
21033  *
21034  *  _______________________________________________________________
21035  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
21036  * |FLUSH_VOLATILE|              | operation                       |
21037  * |______________|______________|_________________________________|
21038  * | 0            | NULL         | Synchronous flush on both       |
21039  * |              |              | volatile and non-volatile cache |
21040  * |______________|______________|_________________________________|
21041  * | 1            | NULL         | Synchronous flush on volatile   |
21042  * |              |              | cache; disk drivers may suppress|
21043  * |              |              | flush if disk table indicates   |
21044  * |              |              | non-volatile cache              |
21045  * |______________|______________|_________________________________|
21046  * | 0            | !NULL        | Asynchronous flush on both      |
21047  * |              |              | volatile and non-volatile cache;|
21048  * |______________|______________|_________________________________|
21049  * | 1            | !NULL        | Asynchronous flush on volatile  |
21050  * |              |              | cache; disk drivers may suppress|
21051  * |              |              | flush if disk table indicates   |
21052  * |              |              | non-volatile cache              |
21053  * |______________|______________|_________________________________|
21054  *
21055  */
21056 
21057 static int
21058 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
21059 {
21060 	struct sd_uscsi_info	*uip;
21061 	struct uscsi_cmd	*uscmd;
21062 	union scsi_cdb		*cdb;
21063 	struct buf		*bp;
21064 	int			rval = 0;
21065 	int			is_async;
21066 
21067 	SD_TRACE(SD_LOG_IO, un,
21068 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
21069 
21070 	ASSERT(un != NULL);
21071 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21072 
21073 	if (dkc == NULL || dkc->dkc_callback == NULL) {
21074 		is_async = FALSE;
21075 	} else {
21076 		is_async = TRUE;
21077 	}
21078 
21079 	mutex_enter(SD_MUTEX(un));
21080 	/* check whether cache flush should be suppressed */
21081 	if (un->un_f_suppress_cache_flush == TRUE) {
21082 		mutex_exit(SD_MUTEX(un));
21083 		/*
21084 		 * suppress the cache flush if the device is told to do
21085 		 * so by sd.conf or disk table
21086 		 */
21087 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
21088 		    skip the cache flush since suppress_cache_flush is %d!\n",
21089 		    un->un_f_suppress_cache_flush);
21090 
21091 		if (is_async == TRUE) {
21092 			/* invoke callback for asynchronous flush */
21093 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
21094 		}
21095 		return (rval);
21096 	}
21097 	mutex_exit(SD_MUTEX(un));
21098 
21099 	/*
21100 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
21101 	 * set properly
21102 	 */
21103 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
21104 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
21105 
21106 	mutex_enter(SD_MUTEX(un));
21107 	if (dkc != NULL && un->un_f_sync_nv_supported &&
21108 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
21109 		/*
21110 		 * if the device supports SYNC_NV bit, turn on
21111 		 * the SYNC_NV bit to only flush volatile cache
21112 		 */
21113 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
21114 	}
21115 	mutex_exit(SD_MUTEX(un));
21116 
21117 	/*
21118 	 * First get some memory for the uscsi_cmd struct and cdb
21119 	 * and initialize for SYNCHRONIZE_CACHE cmd.
21120 	 */
21121 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
21122 	uscmd->uscsi_cdblen = CDB_GROUP1;
21123 	uscmd->uscsi_cdb = (caddr_t)cdb;
21124 	uscmd->uscsi_bufaddr = NULL;
21125 	uscmd->uscsi_buflen = 0;
21126 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
21127 	uscmd->uscsi_rqlen = SENSE_LENGTH;
21128 	uscmd->uscsi_rqresid = SENSE_LENGTH;
21129 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
21130 	uscmd->uscsi_timeout = sd_io_time;
21131 
21132 	/*
21133 	 * Allocate an sd_uscsi_info struct and fill it with the info
21134 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
21135 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
21136 	 * since we allocate the buf here in this function, we do not
21137 	 * need to preserve the prior contents of b_private.
21138 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
21139 	 */
21140 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
21141 	uip->ui_flags = SD_PATH_DIRECT;
21142 	uip->ui_cmdp  = uscmd;
21143 
21144 	bp = getrbuf(KM_SLEEP);
21145 	bp->b_private = uip;
21146 
21147 	/*
21148 	 * Setup buffer to carry uscsi request.
21149 	 */
21150 	bp->b_flags  = B_BUSY;
21151 	bp->b_bcount = 0;
21152 	bp->b_blkno  = 0;
21153 
21154 	if (is_async == TRUE) {
21155 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
21156 		uip->ui_dkc = *dkc;
21157 	}
21158 
21159 	bp->b_edev = SD_GET_DEV(un);
21160 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
21161 
21162 	/*
21163 	 * Unset un_f_sync_cache_required flag
21164 	 */
21165 	mutex_enter(SD_MUTEX(un));
21166 	un->un_f_sync_cache_required = FALSE;
21167 	mutex_exit(SD_MUTEX(un));
21168 
21169 	(void) sd_uscsi_strategy(bp);
21170 
21171 	/*
21172 	 * If synchronous request, wait for completion
21173 	 * If async just return and let b_iodone callback
21174 	 * cleanup.
21175 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
21176 	 * but it was also incremented in sd_uscsi_strategy(), so
21177 	 * we should be ok.
21178 	 */
21179 	if (is_async == FALSE) {
21180 		(void) biowait(bp);
21181 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
21182 	}
21183 
21184 	return (rval);
21185 }
21186 
21187 
21188 static int
21189 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
21190 {
21191 	struct sd_uscsi_info *uip;
21192 	struct uscsi_cmd *uscmd;
21193 	uint8_t *sense_buf;
21194 	struct sd_lun *un;
21195 	int status;
21196 	union scsi_cdb *cdb;
21197 
21198 	uip = (struct sd_uscsi_info *)(bp->b_private);
21199 	ASSERT(uip != NULL);
21200 
21201 	uscmd = uip->ui_cmdp;
21202 	ASSERT(uscmd != NULL);
21203 
21204 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
21205 	ASSERT(sense_buf != NULL);
21206 
21207 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
21208 	ASSERT(un != NULL);
21209 
21210 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
21211 
21212 	status = geterror(bp);
21213 	switch (status) {
21214 	case 0:
21215 		break;	/* Success! */
21216 	case EIO:
21217 		switch (uscmd->uscsi_status) {
21218 		case STATUS_RESERVATION_CONFLICT:
21219 			/* Ignore reservation conflict */
21220 			status = 0;
21221 			goto done;
21222 
21223 		case STATUS_CHECK:
21224 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
21225 			    (scsi_sense_key(sense_buf) ==
21226 			    KEY_ILLEGAL_REQUEST)) {
21227 				/* Ignore Illegal Request error */
21228 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
21229 					mutex_enter(SD_MUTEX(un));
21230 					un->un_f_sync_nv_supported = FALSE;
21231 					mutex_exit(SD_MUTEX(un));
21232 					status = 0;
21233 					SD_TRACE(SD_LOG_IO, un,
21234 					    "un_f_sync_nv_supported \
21235 					    is set to false.\n");
21236 					goto done;
21237 				}
21238 
21239 				mutex_enter(SD_MUTEX(un));
21240 				un->un_f_sync_cache_supported = FALSE;
21241 				mutex_exit(SD_MUTEX(un));
21242 				SD_TRACE(SD_LOG_IO, un,
21243 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
21244 				    un_f_sync_cache_supported set to false \
21245 				    with asc = %x, ascq = %x\n",
21246 				    scsi_sense_asc(sense_buf),
21247 				    scsi_sense_ascq(sense_buf));
21248 				status = ENOTSUP;
21249 				goto done;
21250 			}
21251 			break;
21252 		default:
21253 			break;
21254 		}
21255 		/* FALLTHRU */
21256 	default:
21257 		/*
21258 		 * Turn on the un_f_sync_cache_required flag
21259 		 * since the SYNC CACHE command failed
21260 		 */
21261 		mutex_enter(SD_MUTEX(un));
21262 		un->un_f_sync_cache_required = TRUE;
21263 		mutex_exit(SD_MUTEX(un));
21264 
21265 		/*
21266 		 * Don't log an error message if this device
21267 		 * has removable media.
21268 		 */
21269 		if (!un->un_f_has_removable_media) {
21270 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
21271 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
21272 		}
21273 		break;
21274 	}
21275 
21276 done:
21277 	if (uip->ui_dkc.dkc_callback != NULL) {
21278 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
21279 	}
21280 
21281 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
21282 	freerbuf(bp);
21283 	kmem_free(uip, sizeof (struct sd_uscsi_info));
21284 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
21285 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
21286 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
21287 
21288 	return (status);
21289 }
21290 
21291 /*
21292  * Issues a single SCSI UNMAP command with a prepared UNMAP parameter list.
21293  * Returns zero on success, or the non-zero command error code on failure.
21294  */
21295 static int
21296 sd_send_scsi_UNMAP_issue_one(sd_ssc_t *ssc, unmap_param_hdr_t *uph,
21297     uint64_t num_descr, uint64_t bytes)
21298 {
21299 	struct sd_lun		*un = ssc->ssc_un;
21300 	struct scsi_extended_sense	sense_buf;
21301 	union scsi_cdb		cdb;
21302 	struct uscsi_cmd	ucmd_buf;
21303 	int			status;
21304 	const uint64_t		param_size = sizeof (unmap_param_hdr_t) +
21305 	    num_descr * sizeof (unmap_blk_descr_t);
21306 
21307 	ASSERT3U(param_size - 2, <=, UINT16_MAX);
21308 	uph->uph_data_len = BE_16(param_size - 2);
21309 	uph->uph_descr_data_len = BE_16(param_size - 8);
21310 
21311 	bzero(&cdb, sizeof (cdb));
21312 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21313 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21314 
21315 	cdb.scc_cmd = SCMD_UNMAP;
21316 	FORMG1COUNT(&cdb, param_size);
21317 
21318 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21319 	ucmd_buf.uscsi_cdblen	= (uchar_t)CDB_GROUP1;
21320 	ucmd_buf.uscsi_bufaddr	= (caddr_t)uph;
21321 	ucmd_buf.uscsi_buflen	= param_size;
21322 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21323 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21324 	ucmd_buf.uscsi_flags	= USCSI_WRITE | USCSI_RQENABLE | USCSI_SILENT;
21325 	ucmd_buf.uscsi_timeout	= un->un_cmd_timeout;
21326 
21327 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL, UIO_SYSSPACE,
21328 	    SD_PATH_STANDARD);
21329 
21330 	switch (status) {
21331 	case 0:
21332 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21333 
21334 		if (un->un_unmapstats) {
21335 			atomic_inc_64(&un->un_unmapstats->us_cmds.value.ui64);
21336 			atomic_add_64(&un->un_unmapstats->us_extents.value.ui64,
21337 			    num_descr);
21338 			atomic_add_64(&un->un_unmapstats->us_bytes.value.ui64,
21339 			    bytes);
21340 		}
21341 		break;	/* Success! */
21342 	case EIO:
21343 		if (un->un_unmapstats)
21344 			atomic_inc_64(&un->un_unmapstats->us_errs.value.ui64);
21345 		switch (ucmd_buf.uscsi_status) {
21346 		case STATUS_RESERVATION_CONFLICT:
21347 			status = EACCES;
21348 			break;
21349 		default:
21350 			break;
21351 		}
21352 		break;
21353 	default:
21354 		if (un->un_unmapstats)
21355 			atomic_inc_64(&un->un_unmapstats->us_errs.value.ui64);
21356 		break;
21357 	}
21358 
21359 	return (status);
21360 }
21361 
21362 /*
21363  * Returns a pointer to the i'th block descriptor inside an UNMAP param list.
21364  */
21365 static inline unmap_blk_descr_t *
21366 UNMAP_blk_descr_i(void *buf, size_t i)
21367 {
21368 	return ((unmap_blk_descr_t *)((uintptr_t)buf +
21369 	    sizeof (unmap_param_hdr_t) + (i * sizeof (unmap_blk_descr_t))));
21370 }
21371 
21372 /*
21373  * Takes the list of extents from sd_send_scsi_UNMAP, chops it up, prepares
21374  * UNMAP block descriptors and issues individual SCSI UNMAP commands. While
21375  * doing so we consult the block limits to determine at most how many
21376  * extents and LBAs we can UNMAP in one command.
21377  * If a command fails for whatever, reason, extent list processing is aborted
21378  * and the failed command's status is returned. Otherwise returns 0 on
21379  * success.
21380  */
21381 static int
21382 sd_send_scsi_UNMAP_issue(dev_t dev, sd_ssc_t *ssc, const dkioc_free_list_t *dfl)
21383 {
21384 	struct sd_lun		*un = ssc->ssc_un;
21385 	unmap_param_hdr_t	*uph;
21386 	sd_blk_limits_t		*lim = &un->un_blk_lim;
21387 	int			rval = 0;
21388 	int			partition;
21389 	/* partition offset & length in system blocks */
21390 	diskaddr_t		part_off_sysblks = 0, part_len_sysblks = 0;
21391 	uint64_t		part_off, part_len;
21392 	uint64_t		descr_cnt_lim, byte_cnt_lim;
21393 	uint64_t		descr_issued = 0, bytes_issued = 0;
21394 
21395 	uph = kmem_zalloc(SD_UNMAP_PARAM_LIST_MAXSZ, KM_SLEEP);
21396 
21397 	partition = SDPART(dev);
21398 	rval = cmlb_partinfo(un->un_cmlbhandle, partition, &part_len_sysblks,
21399 	    &part_off_sysblks, NULL, NULL, (void *)SD_PATH_DIRECT);
21400 	if (rval != 0)
21401 		goto out;
21402 	part_off = SD_SYSBLOCKS2BYTES(part_off_sysblks);
21403 	part_len = SD_SYSBLOCKS2BYTES(part_len_sysblks);
21404 
21405 	ASSERT(un->un_blk_lim.lim_max_unmap_lba_cnt != 0);
21406 	ASSERT(un->un_blk_lim.lim_max_unmap_descr_cnt != 0);
21407 	/* Spec says 0xffffffff are special values, so compute maximums. */
21408 	byte_cnt_lim = lim->lim_max_unmap_lba_cnt < UINT32_MAX ?
21409 	    (uint64_t)lim->lim_max_unmap_lba_cnt * un->un_tgt_blocksize :
21410 	    UINT64_MAX;
21411 	descr_cnt_lim = MIN(lim->lim_max_unmap_descr_cnt, SD_UNMAP_MAX_DESCR);
21412 
21413 	if (dfl->dfl_offset >= part_len) {
21414 		rval = SET_ERROR(EINVAL);
21415 		goto out;
21416 	}
21417 
21418 	for (size_t i = 0; i < dfl->dfl_num_exts; i++) {
21419 		const dkioc_free_list_ext_t *ext = &dfl->dfl_exts[i];
21420 		uint64_t ext_start = ext->dfle_start;
21421 		uint64_t ext_length = ext->dfle_length;
21422 
21423 		while (ext_length > 0) {
21424 			unmap_blk_descr_t *ubd;
21425 			/* Respect device limit on LBA count per command */
21426 			uint64_t len = MIN(MIN(ext_length, byte_cnt_lim -
21427 			    bytes_issued), SD_TGTBLOCKS2BYTES(un, UINT32_MAX));
21428 
21429 			/* check partition limits */
21430 			if (ext_start >= part_len ||
21431 			    ext_start + len < ext_start ||
21432 			    dfl->dfl_offset + ext_start + len <
21433 			    dfl->dfl_offset ||
21434 			    dfl->dfl_offset + ext_start + len > part_len) {
21435 				rval = SET_ERROR(EINVAL);
21436 				goto out;
21437 			}
21438 
21439 			ASSERT3U(descr_issued, <, descr_cnt_lim);
21440 			ASSERT3U(bytes_issued, <, byte_cnt_lim);
21441 			ubd = UNMAP_blk_descr_i(uph, descr_issued);
21442 
21443 			/* adjust in-partition addresses to be device-global */
21444 			ubd->ubd_lba = BE_64(SD_BYTES2TGTBLOCKS(un,
21445 			    dfl->dfl_offset + ext_start + part_off));
21446 			ubd->ubd_lba_cnt = BE_32(SD_BYTES2TGTBLOCKS(un, len));
21447 
21448 			descr_issued++;
21449 			bytes_issued += len;
21450 
21451 			/* Issue command when device limits reached */
21452 			if (descr_issued == descr_cnt_lim ||
21453 			    bytes_issued == byte_cnt_lim) {
21454 				rval = sd_send_scsi_UNMAP_issue_one(ssc, uph,
21455 				    descr_issued, bytes_issued);
21456 				if (rval != 0)
21457 					goto out;
21458 				descr_issued = 0;
21459 				bytes_issued = 0;
21460 			}
21461 
21462 			ext_start += len;
21463 			ext_length -= len;
21464 		}
21465 	}
21466 
21467 	if (descr_issued > 0) {
21468 		/* issue last command */
21469 		rval = sd_send_scsi_UNMAP_issue_one(ssc, uph, descr_issued,
21470 		    bytes_issued);
21471 	}
21472 
21473 out:
21474 	kmem_free(uph, SD_UNMAP_PARAM_LIST_MAXSZ);
21475 	return (rval);
21476 }
21477 
21478 /*
21479  * Issues one or several UNMAP commands based on a list of extents to be
21480  * unmapped. The internal multi-command processing is hidden, as the exact
21481  * number of commands and extents per command is limited by both SCSI
21482  * command syntax and device limits (as expressed in the SCSI Block Limits
21483  * VPD page and un_blk_lim in struct sd_lun).
21484  * Returns zero on success, or the error code of the first failed SCSI UNMAP
21485  * command.
21486  */
21487 static int
21488 sd_send_scsi_UNMAP(dev_t dev, sd_ssc_t *ssc, dkioc_free_list_t *dfl, int flag)
21489 {
21490 	struct sd_lun		*un = ssc->ssc_un;
21491 	int			rval = 0;
21492 
21493 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21494 	ASSERT(dfl != NULL);
21495 
21496 	/* Per spec, any of these conditions signals lack of UNMAP support. */
21497 	if (!(un->un_thin_flags & SD_THIN_PROV_ENABLED) ||
21498 	    un->un_blk_lim.lim_max_unmap_descr_cnt == 0 ||
21499 	    un->un_blk_lim.lim_max_unmap_lba_cnt == 0) {
21500 		return (SET_ERROR(ENOTSUP));
21501 	}
21502 
21503 	/* For userspace calls we must copy in. */
21504 	if (!(flag & FKIOCTL)) {
21505 		int err = dfl_copyin(dfl, &dfl, flag, KM_SLEEP);
21506 		if (err != 0)
21507 			return (err);
21508 	} else if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
21509 		ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
21510 		return (SET_ERROR(EINVAL));
21511 	}
21512 
21513 	rval = sd_send_scsi_UNMAP_issue(dev, ssc, dfl);
21514 
21515 	if (!(flag & FKIOCTL)) {
21516 		dfl_free(dfl);
21517 		dfl = NULL;
21518 	}
21519 
21520 	return (rval);
21521 }
21522 
21523 /*
21524  *    Function: sd_send_scsi_GET_CONFIGURATION
21525  *
21526  * Description: Issues the get configuration command to the device.
21527  *		Called from sd_check_for_writable_cd & sd_get_media_info
21528  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
21529  *   Arguments: ssc
21530  *		ucmdbuf
21531  *		rqbuf
21532  *		rqbuflen
21533  *		bufaddr
21534  *		buflen
21535  *		path_flag
21536  *
21537  * Return Code: 0   - Success
21538  *		errno return code from sd_ssc_send()
21539  *
21540  *     Context: Can sleep. Does not return until command is completed.
21541  *
21542  */
21543 
21544 static int
21545 sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21546     uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21547     int path_flag)
21548 {
21549 	char	cdb[CDB_GROUP1];
21550 	int	status;
21551 	struct sd_lun	*un;
21552 
21553 	ASSERT(ssc != NULL);
21554 	un = ssc->ssc_un;
21555 	ASSERT(un != NULL);
21556 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21557 	ASSERT(bufaddr != NULL);
21558 	ASSERT(ucmdbuf != NULL);
21559 	ASSERT(rqbuf != NULL);
21560 
21561 	SD_TRACE(SD_LOG_IO, un,
21562 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
21563 
21564 	bzero(cdb, sizeof (cdb));
21565 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21566 	bzero(rqbuf, rqbuflen);
21567 	bzero(bufaddr, buflen);
21568 
21569 	/*
21570 	 * Set up cdb field for the get configuration command.
21571 	 */
21572 	cdb[0] = SCMD_GET_CONFIGURATION;
21573 	cdb[1] = 0x02;  /* Requested Type */
21574 	cdb[8] = SD_PROFILE_HEADER_LEN;
21575 	ucmdbuf->uscsi_cdb = cdb;
21576 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21577 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21578 	ucmdbuf->uscsi_buflen = buflen;
21579 	ucmdbuf->uscsi_timeout = sd_io_time;
21580 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21581 	ucmdbuf->uscsi_rqlen = rqbuflen;
21582 	ucmdbuf->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT | USCSI_READ;
21583 
21584 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21585 	    UIO_SYSSPACE, path_flag);
21586 
21587 	switch (status) {
21588 	case 0:
21589 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21590 		break;  /* Success! */
21591 	case EIO:
21592 		switch (ucmdbuf->uscsi_status) {
21593 		case STATUS_RESERVATION_CONFLICT:
21594 			status = EACCES;
21595 			break;
21596 		default:
21597 			break;
21598 		}
21599 		break;
21600 	default:
21601 		break;
21602 	}
21603 
21604 	if (status == 0) {
21605 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21606 		    "sd_send_scsi_GET_CONFIGURATION: data",
21607 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21608 	}
21609 
21610 	SD_TRACE(SD_LOG_IO, un,
21611 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
21612 
21613 	return (status);
21614 }
21615 
21616 /*
21617  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
21618  *
21619  * Description: Issues the get configuration command to the device to
21620  *              retrieve a specific feature. Called from
21621  *		sd_check_for_writable_cd & sd_set_mmc_caps.
21622  *   Arguments: ssc
21623  *              ucmdbuf
21624  *              rqbuf
21625  *              rqbuflen
21626  *              bufaddr
21627  *              buflen
21628  *		feature
21629  *
21630  * Return Code: 0   - Success
21631  *              errno return code from sd_ssc_send()
21632  *
21633  *     Context: Can sleep. Does not return until command is completed.
21634  *
21635  */
21636 static int
21637 sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21638     uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21639     char feature, int path_flag)
21640 {
21641 	char    cdb[CDB_GROUP1];
21642 	int	status;
21643 	struct sd_lun	*un;
21644 
21645 	ASSERT(ssc != NULL);
21646 	un = ssc->ssc_un;
21647 	ASSERT(un != NULL);
21648 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21649 	ASSERT(bufaddr != NULL);
21650 	ASSERT(ucmdbuf != NULL);
21651 	ASSERT(rqbuf != NULL);
21652 
21653 	SD_TRACE(SD_LOG_IO, un,
21654 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
21655 
21656 	bzero(cdb, sizeof (cdb));
21657 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21658 	bzero(rqbuf, rqbuflen);
21659 	bzero(bufaddr, buflen);
21660 
21661 	/*
21662 	 * Set up cdb field for the get configuration command.
21663 	 */
21664 	cdb[0] = SCMD_GET_CONFIGURATION;
21665 	cdb[1] = 0x02;  /* Requested Type */
21666 	cdb[3] = feature;
21667 	cdb[8] = buflen;
21668 	ucmdbuf->uscsi_cdb = cdb;
21669 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21670 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21671 	ucmdbuf->uscsi_buflen = buflen;
21672 	ucmdbuf->uscsi_timeout = sd_io_time;
21673 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21674 	ucmdbuf->uscsi_rqlen = rqbuflen;
21675 	ucmdbuf->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT | USCSI_READ;
21676 
21677 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21678 	    UIO_SYSSPACE, path_flag);
21679 
21680 	switch (status) {
21681 	case 0:
21682 
21683 		break;  /* Success! */
21684 	case EIO:
21685 		switch (ucmdbuf->uscsi_status) {
21686 		case STATUS_RESERVATION_CONFLICT:
21687 			status = EACCES;
21688 			break;
21689 		default:
21690 			break;
21691 		}
21692 		break;
21693 	default:
21694 		break;
21695 	}
21696 
21697 	if (status == 0) {
21698 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21699 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
21700 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21701 	}
21702 
21703 	SD_TRACE(SD_LOG_IO, un,
21704 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
21705 
21706 	return (status);
21707 }
21708 
21709 
21710 /*
21711  *    Function: sd_send_scsi_MODE_SENSE
21712  *
21713  * Description: Utility function for issuing a scsi MODE SENSE command.
21714  *		Note: This routine uses a consistent implementation for Group0,
21715  *		Group1, and Group2 commands across all platforms. ATAPI devices
21716  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21717  *
21718  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21719  *                      structure for this target.
21720  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21721  *			  CDB_GROUP[1|2] (10 byte).
21722  *		bufaddr - buffer for page data retrieved from the target.
21723  *		buflen - size of page to be retrieved.
21724  *		page_code - page code of data to be retrieved from the target.
21725  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21726  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21727  *			to use the USCSI "direct" chain and bypass the normal
21728  *			command waitq.
21729  *
21730  * Return Code: 0   - Success
21731  *		errno return code from sd_ssc_send()
21732  *
21733  *     Context: Can sleep. Does not return until command is completed.
21734  */
21735 
21736 static int
21737 sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21738     size_t buflen,  uchar_t page_code, int path_flag)
21739 {
21740 	struct	scsi_extended_sense	sense_buf;
21741 	union scsi_cdb		cdb;
21742 	struct uscsi_cmd	ucmd_buf;
21743 	int			status;
21744 	int			headlen;
21745 	struct sd_lun		*un;
21746 
21747 	ASSERT(ssc != NULL);
21748 	un = ssc->ssc_un;
21749 	ASSERT(un != NULL);
21750 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21751 	ASSERT(bufaddr != NULL);
21752 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21753 	    (cdbsize == CDB_GROUP2));
21754 
21755 	SD_TRACE(SD_LOG_IO, un,
21756 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
21757 
21758 	bzero(&cdb, sizeof (cdb));
21759 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21760 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21761 	bzero(bufaddr, buflen);
21762 
21763 	if (cdbsize == CDB_GROUP0) {
21764 		cdb.scc_cmd = SCMD_MODE_SENSE;
21765 		cdb.cdb_opaque[2] = page_code;
21766 		FORMG0COUNT(&cdb, buflen);
21767 		headlen = MODE_HEADER_LENGTH;
21768 	} else {
21769 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
21770 		cdb.cdb_opaque[2] = page_code;
21771 		FORMG1COUNT(&cdb, buflen);
21772 		headlen = MODE_HEADER_LENGTH_GRP2;
21773 	}
21774 
21775 	ASSERT(headlen <= buflen);
21776 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21777 
21778 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21779 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21780 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21781 	ucmd_buf.uscsi_buflen	= buflen;
21782 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21783 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21784 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21785 	ucmd_buf.uscsi_timeout	= 60;
21786 
21787 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21788 	    UIO_SYSSPACE, path_flag);
21789 
21790 	switch (status) {
21791 	case 0:
21792 		/*
21793 		 * sr_check_wp() uses 0x3f page code and check the header of
21794 		 * mode page to determine if target device is write-protected.
21795 		 * But some USB devices return 0 bytes for 0x3f page code. For
21796 		 * this case, make sure that mode page header is returned at
21797 		 * least.
21798 		 */
21799 		if (buflen - ucmd_buf.uscsi_resid <  headlen) {
21800 			status = EIO;
21801 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
21802 			    "mode page header is not returned");
21803 		}
21804 		break;	/* Success! */
21805 	case EIO:
21806 		switch (ucmd_buf.uscsi_status) {
21807 		case STATUS_RESERVATION_CONFLICT:
21808 			status = EACCES;
21809 			break;
21810 		default:
21811 			break;
21812 		}
21813 		break;
21814 	default:
21815 		break;
21816 	}
21817 
21818 	if (status == 0) {
21819 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
21820 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21821 	}
21822 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
21823 
21824 	return (status);
21825 }
21826 
21827 
21828 /*
21829  *    Function: sd_send_scsi_MODE_SELECT
21830  *
21831  * Description: Utility function for issuing a scsi MODE SELECT command.
21832  *		Note: This routine uses a consistent implementation for Group0,
21833  *		Group1, and Group2 commands across all platforms. ATAPI devices
21834  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21835  *
21836  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21837  *                      structure for this target.
21838  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21839  *			  CDB_GROUP[1|2] (10 byte).
21840  *		bufaddr - buffer for page data retrieved from the target.
21841  *		buflen - size of page to be retrieved.
21842  *		save_page - boolean to determin if SP bit should be set.
21843  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21844  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21845  *			to use the USCSI "direct" chain and bypass the normal
21846  *			command waitq.
21847  *
21848  * Return Code: 0   - Success
21849  *		errno return code from sd_ssc_send()
21850  *
21851  *     Context: Can sleep. Does not return until command is completed.
21852  */
21853 
21854 static int
21855 sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21856     size_t buflen,  uchar_t save_page, int path_flag)
21857 {
21858 	struct	scsi_extended_sense	sense_buf;
21859 	union scsi_cdb		cdb;
21860 	struct uscsi_cmd	ucmd_buf;
21861 	int			status;
21862 	struct sd_lun		*un;
21863 
21864 	ASSERT(ssc != NULL);
21865 	un = ssc->ssc_un;
21866 	ASSERT(un != NULL);
21867 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21868 	ASSERT(bufaddr != NULL);
21869 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21870 	    (cdbsize == CDB_GROUP2));
21871 
21872 	SD_TRACE(SD_LOG_IO, un,
21873 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
21874 
21875 	bzero(&cdb, sizeof (cdb));
21876 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21877 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21878 
21879 	/* Set the PF bit for many third party drives */
21880 	cdb.cdb_opaque[1] = 0x10;
21881 
21882 	/* Set the savepage(SP) bit if given */
21883 	if (save_page == SD_SAVE_PAGE) {
21884 		cdb.cdb_opaque[1] |= 0x01;
21885 	}
21886 
21887 	if (cdbsize == CDB_GROUP0) {
21888 		cdb.scc_cmd = SCMD_MODE_SELECT;
21889 		FORMG0COUNT(&cdb, buflen);
21890 	} else {
21891 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
21892 		FORMG1COUNT(&cdb, buflen);
21893 	}
21894 
21895 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21896 
21897 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21898 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21899 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21900 	ucmd_buf.uscsi_buflen	= buflen;
21901 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21902 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21903 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
21904 	ucmd_buf.uscsi_timeout	= 60;
21905 
21906 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21907 	    UIO_SYSSPACE, path_flag);
21908 
21909 	switch (status) {
21910 	case 0:
21911 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21912 		break;	/* Success! */
21913 	case EIO:
21914 		switch (ucmd_buf.uscsi_status) {
21915 		case STATUS_RESERVATION_CONFLICT:
21916 			status = EACCES;
21917 			break;
21918 		default:
21919 			break;
21920 		}
21921 		break;
21922 	default:
21923 		break;
21924 	}
21925 
21926 	if (status == 0) {
21927 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
21928 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21929 	}
21930 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
21931 
21932 	return (status);
21933 }
21934 
21935 
21936 /*
21937  *    Function: sd_send_scsi_RDWR
21938  *
21939  * Description: Issue a scsi READ or WRITE command with the given parameters.
21940  *
21941  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21942  *                      structure for this target.
21943  *		cmd:	 SCMD_READ or SCMD_WRITE
21944  *		bufaddr: Address of caller's buffer to receive the RDWR data
21945  *		buflen:  Length of caller's buffer receive the RDWR data.
21946  *		start_block: Block number for the start of the RDWR operation.
21947  *			 (Assumes target-native block size.)
21948  *		residp:  Pointer to variable to receive the redisual of the
21949  *			 RDWR operation (may be NULL of no residual requested).
21950  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21951  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21952  *			to use the USCSI "direct" chain and bypass the normal
21953  *			command waitq.
21954  *
21955  * Return Code: 0   - Success
21956  *		errno return code from sd_ssc_send()
21957  *
21958  *     Context: Can sleep. Does not return until command is completed.
21959  */
21960 
21961 static int
21962 sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
21963     size_t buflen, daddr_t start_block, int path_flag)
21964 {
21965 	struct	scsi_extended_sense	sense_buf;
21966 	union scsi_cdb		cdb;
21967 	struct uscsi_cmd	ucmd_buf;
21968 	uint32_t		block_count;
21969 	int			status;
21970 	int			cdbsize;
21971 	uchar_t			flag;
21972 	struct sd_lun		*un;
21973 
21974 	ASSERT(ssc != NULL);
21975 	un = ssc->ssc_un;
21976 	ASSERT(un != NULL);
21977 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21978 	ASSERT(bufaddr != NULL);
21979 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
21980 
21981 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
21982 
21983 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
21984 		return (EINVAL);
21985 	}
21986 
21987 	mutex_enter(SD_MUTEX(un));
21988 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
21989 	mutex_exit(SD_MUTEX(un));
21990 
21991 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
21992 
21993 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
21994 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
21995 	    bufaddr, buflen, start_block, block_count);
21996 
21997 	bzero(&cdb, sizeof (cdb));
21998 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21999 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
22000 
22001 	/* Compute CDB size to use */
22002 	if (start_block > 0xffffffff)
22003 		cdbsize = CDB_GROUP4;
22004 	else if ((start_block & 0xFFE00000) ||
22005 	    (un->un_f_cfg_is_atapi == TRUE))
22006 		cdbsize = CDB_GROUP1;
22007 	else
22008 		cdbsize = CDB_GROUP0;
22009 
22010 	switch (cdbsize) {
22011 	case CDB_GROUP0:	/* 6-byte CDBs */
22012 		cdb.scc_cmd = cmd;
22013 		FORMG0ADDR(&cdb, start_block);
22014 		FORMG0COUNT(&cdb, block_count);
22015 		break;
22016 	case CDB_GROUP1:	/* 10-byte CDBs */
22017 		cdb.scc_cmd = cmd | SCMD_GROUP1;
22018 		FORMG1ADDR(&cdb, start_block);
22019 		FORMG1COUNT(&cdb, block_count);
22020 		break;
22021 	case CDB_GROUP4:	/* 16-byte CDBs */
22022 		cdb.scc_cmd = cmd | SCMD_GROUP4;
22023 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
22024 		FORMG4COUNT(&cdb, block_count);
22025 		break;
22026 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
22027 	default:
22028 		/* All others reserved */
22029 		return (EINVAL);
22030 	}
22031 
22032 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
22033 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
22034 
22035 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22036 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
22037 	ucmd_buf.uscsi_bufaddr	= bufaddr;
22038 	ucmd_buf.uscsi_buflen	= buflen;
22039 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
22040 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
22041 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
22042 	ucmd_buf.uscsi_timeout	= 60;
22043 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22044 	    UIO_SYSSPACE, path_flag);
22045 
22046 	switch (status) {
22047 	case 0:
22048 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22049 		break;	/* Success! */
22050 	case EIO:
22051 		switch (ucmd_buf.uscsi_status) {
22052 		case STATUS_RESERVATION_CONFLICT:
22053 			status = EACCES;
22054 			break;
22055 		default:
22056 			break;
22057 		}
22058 		break;
22059 	default:
22060 		break;
22061 	}
22062 
22063 	if (status == 0) {
22064 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
22065 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22066 	}
22067 
22068 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
22069 
22070 	return (status);
22071 }
22072 
22073 
22074 /*
22075  *    Function: sd_send_scsi_LOG_SENSE
22076  *
22077  * Description: Issue a scsi LOG_SENSE command with the given parameters.
22078  *
22079  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22080  *                      structure for this target.
22081  *
22082  * Return Code: 0   - Success
22083  *		errno return code from sd_ssc_send()
22084  *
22085  *     Context: Can sleep. Does not return until command is completed.
22086  */
22087 
22088 static int
22089 sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr, uint16_t buflen,
22090     uchar_t page_code, uchar_t page_control, uint16_t param_ptr, int path_flag)
22091 {
22092 	struct scsi_extended_sense	sense_buf;
22093 	union scsi_cdb		cdb;
22094 	struct uscsi_cmd	ucmd_buf;
22095 	int			status;
22096 	struct sd_lun		*un;
22097 
22098 	ASSERT(ssc != NULL);
22099 	un = ssc->ssc_un;
22100 	ASSERT(un != NULL);
22101 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22102 
22103 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
22104 
22105 	bzero(&cdb, sizeof (cdb));
22106 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22107 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
22108 
22109 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
22110 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
22111 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
22112 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
22113 	FORMG1COUNT(&cdb, buflen);
22114 
22115 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22116 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22117 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22118 	ucmd_buf.uscsi_buflen	= buflen;
22119 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
22120 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
22121 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
22122 	ucmd_buf.uscsi_timeout	= 60;
22123 
22124 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22125 	    UIO_SYSSPACE, path_flag);
22126 
22127 	switch (status) {
22128 	case 0:
22129 		break;
22130 	case EIO:
22131 		switch (ucmd_buf.uscsi_status) {
22132 		case STATUS_RESERVATION_CONFLICT:
22133 			status = EACCES;
22134 			break;
22135 		case STATUS_CHECK:
22136 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
22137 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
22138 			    KEY_ILLEGAL_REQUEST) &&
22139 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
22140 				/*
22141 				 * ASC 0x24: INVALID FIELD IN CDB
22142 				 */
22143 				switch (page_code) {
22144 				case START_STOP_CYCLE_PAGE:
22145 					/*
22146 					 * The start stop cycle counter is
22147 					 * implemented as page 0x31 in earlier
22148 					 * generation disks. In new generation
22149 					 * disks the start stop cycle counter is
22150 					 * implemented as page 0xE. To properly
22151 					 * handle this case if an attempt for
22152 					 * log page 0xE is made and fails we
22153 					 * will try again using page 0x31.
22154 					 *
22155 					 * Network storage BU committed to
22156 					 * maintain the page 0x31 for this
22157 					 * purpose and will not have any other
22158 					 * page implemented with page code 0x31
22159 					 * until all disks transition to the
22160 					 * standard page.
22161 					 */
22162 					mutex_enter(SD_MUTEX(un));
22163 					un->un_start_stop_cycle_page =
22164 					    START_STOP_CYCLE_VU_PAGE;
22165 					cdb.cdb_opaque[2] =
22166 					    (char)(page_control << 6) |
22167 					    un->un_start_stop_cycle_page;
22168 					mutex_exit(SD_MUTEX(un));
22169 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22170 					status = sd_ssc_send(
22171 					    ssc, &ucmd_buf, FKIOCTL,
22172 					    UIO_SYSSPACE, path_flag);
22173 
22174 					break;
22175 				case TEMPERATURE_PAGE:
22176 					status = ENOTTY;
22177 					break;
22178 				default:
22179 					break;
22180 				}
22181 			}
22182 			break;
22183 		default:
22184 			break;
22185 		}
22186 		break;
22187 	default:
22188 		break;
22189 	}
22190 
22191 	if (status == 0) {
22192 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22193 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
22194 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22195 	}
22196 
22197 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
22198 
22199 	return (status);
22200 }
22201 
22202 
22203 /*
22204  *    Function: sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
22205  *
22206  * Description: Issue the scsi GET EVENT STATUS NOTIFICATION command.
22207  *
22208  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22209  *                      structure for this target.
22210  *		bufaddr
22211  *		buflen
22212  *		class_req
22213  *
22214  * Return Code: 0   - Success
22215  *		errno return code from sd_ssc_send()
22216  *
22217  *     Context: Can sleep. Does not return until command is completed.
22218  */
22219 
22220 static int
22221 sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc, uchar_t *bufaddr,
22222     size_t buflen, uchar_t class_req)
22223 {
22224 	union scsi_cdb		cdb;
22225 	struct uscsi_cmd	ucmd_buf;
22226 	int			status;
22227 	struct sd_lun		*un;
22228 
22229 	ASSERT(ssc != NULL);
22230 	un = ssc->ssc_un;
22231 	ASSERT(un != NULL);
22232 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22233 	ASSERT(bufaddr != NULL);
22234 
22235 	SD_TRACE(SD_LOG_IO, un,
22236 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: entry: un:0x%p\n", un);
22237 
22238 	bzero(&cdb, sizeof (cdb));
22239 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22240 	bzero(bufaddr, buflen);
22241 
22242 	cdb.scc_cmd = SCMD_GET_EVENT_STATUS_NOTIFICATION;
22243 	cdb.cdb_opaque[1] = 1; /* polled */
22244 	cdb.cdb_opaque[4] = class_req;
22245 	FORMG1COUNT(&cdb, buflen);
22246 
22247 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22248 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22249 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22250 	ucmd_buf.uscsi_buflen	= buflen;
22251 	ucmd_buf.uscsi_rqbuf	= NULL;
22252 	ucmd_buf.uscsi_rqlen	= 0;
22253 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
22254 	ucmd_buf.uscsi_timeout	= 60;
22255 
22256 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22257 	    UIO_SYSSPACE, SD_PATH_DIRECT);
22258 
22259 	/*
22260 	 * Only handle status == 0, the upper-level caller
22261 	 * will put different assessment based on the context.
22262 	 */
22263 	if (status == 0) {
22264 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22265 
22266 		if (ucmd_buf.uscsi_resid != 0) {
22267 			status = EIO;
22268 		}
22269 	}
22270 
22271 	SD_TRACE(SD_LOG_IO, un,
22272 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: exit\n");
22273 
22274 	return (status);
22275 }
22276 
22277 
22278 static boolean_t
22279 sd_gesn_media_data_valid(uchar_t *data)
22280 {
22281 	uint16_t			len;
22282 
22283 	len = (data[1] << 8) | data[0];
22284 	return ((len >= 6) &&
22285 	    ((data[2] & SD_GESN_HEADER_NEA) == 0) &&
22286 	    ((data[2] & SD_GESN_HEADER_CLASS) == SD_GESN_MEDIA_CLASS) &&
22287 	    ((data[3] & (1 << SD_GESN_MEDIA_CLASS)) != 0));
22288 }
22289 
22290 
22291 /*
22292  *    Function: sdioctl
22293  *
22294  * Description: Driver's ioctl(9e) entry point function.
22295  *
22296  *   Arguments: dev     - device number
22297  *		cmd     - ioctl operation to be performed
22298  *		arg     - user argument, contains data to be set or reference
22299  *			  parameter for get
22300  *		flag    - bit flag, indicating open settings, 32/64 bit type
22301  *		cred_p  - user credential pointer
22302  *		rval_p  - calling process return value (OPT)
22303  *
22304  * Return Code: EINVAL
22305  *		ENOTTY
22306  *		ENXIO
22307  *		EIO
22308  *		EFAULT
22309  *		ENOTSUP
22310  *		EPERM
22311  *
22312  *     Context: Called from the device switch at normal priority.
22313  */
22314 
22315 static int
22316 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
22317 {
22318 	struct sd_lun	*un = NULL;
22319 	int		err = 0;
22320 	int		i = 0;
22321 	cred_t		*cr;
22322 	int		tmprval = EINVAL;
22323 	boolean_t	is_valid;
22324 	sd_ssc_t	*ssc;
22325 
22326 	/*
22327 	 * All device accesses go thru sdstrategy where we check on suspend
22328 	 * status
22329 	 */
22330 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22331 		return (ENXIO);
22332 	}
22333 
22334 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22335 
22336 	/* Initialize sd_ssc_t for internal uscsi commands */
22337 	ssc = sd_ssc_init(un);
22338 
22339 	is_valid = SD_IS_VALID_LABEL(un);
22340 
22341 	/*
22342 	 * Moved this wait from sd_uscsi_strategy to here for
22343 	 * reasons of deadlock prevention. Internal driver commands,
22344 	 * specifically those to change a devices power level, result
22345 	 * in a call to sd_uscsi_strategy.
22346 	 */
22347 	mutex_enter(SD_MUTEX(un));
22348 	while ((un->un_state == SD_STATE_SUSPENDED) ||
22349 	    (un->un_state == SD_STATE_PM_CHANGING)) {
22350 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
22351 	}
22352 	/*
22353 	 * Twiddling the counter here protects commands from now
22354 	 * through to the top of sd_uscsi_strategy. Without the
22355 	 * counter inc. a power down, for example, could get in
22356 	 * after the above check for state is made and before
22357 	 * execution gets to the top of sd_uscsi_strategy.
22358 	 * That would cause problems.
22359 	 */
22360 	un->un_ncmds_in_driver++;
22361 
22362 	if (!is_valid &&
22363 	    (flag & (FNDELAY | FNONBLOCK))) {
22364 		switch (cmd) {
22365 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
22366 		case DKIOCGVTOC:
22367 		case DKIOCGEXTVTOC:
22368 		case DKIOCGAPART:
22369 		case DKIOCPARTINFO:
22370 		case DKIOCEXTPARTINFO:
22371 		case DKIOCSGEOM:
22372 		case DKIOCSAPART:
22373 		case DKIOCGETEFI:
22374 		case DKIOCPARTITION:
22375 		case DKIOCSVTOC:
22376 		case DKIOCSEXTVTOC:
22377 		case DKIOCSETEFI:
22378 		case DKIOCGMBOOT:
22379 		case DKIOCSMBOOT:
22380 		case DKIOCG_PHYGEOM:
22381 		case DKIOCG_VIRTGEOM:
22382 #if defined(__x86)
22383 		case DKIOCSETEXTPART:
22384 #endif
22385 			/* let cmlb handle it */
22386 			goto skip_ready_valid;
22387 
22388 		case CDROMPAUSE:
22389 		case CDROMRESUME:
22390 		case CDROMPLAYMSF:
22391 		case CDROMPLAYTRKIND:
22392 		case CDROMREADTOCHDR:
22393 		case CDROMREADTOCENTRY:
22394 		case CDROMSTOP:
22395 		case CDROMSTART:
22396 		case CDROMVOLCTRL:
22397 		case CDROMSUBCHNL:
22398 		case CDROMREADMODE2:
22399 		case CDROMREADMODE1:
22400 		case CDROMREADOFFSET:
22401 		case CDROMSBLKMODE:
22402 		case CDROMGBLKMODE:
22403 		case CDROMGDRVSPEED:
22404 		case CDROMSDRVSPEED:
22405 		case CDROMCDDA:
22406 		case CDROMCDXA:
22407 		case CDROMSUBCODE:
22408 			if (!ISCD(un)) {
22409 				un->un_ncmds_in_driver--;
22410 				ASSERT(un->un_ncmds_in_driver >= 0);
22411 				mutex_exit(SD_MUTEX(un));
22412 				err = ENOTTY;
22413 				goto done_without_assess;
22414 			}
22415 			break;
22416 		case FDEJECT:
22417 		case DKIOCEJECT:
22418 		case CDROMEJECT:
22419 			if (!un->un_f_eject_media_supported) {
22420 				un->un_ncmds_in_driver--;
22421 				ASSERT(un->un_ncmds_in_driver >= 0);
22422 				mutex_exit(SD_MUTEX(un));
22423 				err = ENOTTY;
22424 				goto done_without_assess;
22425 			}
22426 			break;
22427 		case DKIOCFLUSHWRITECACHE:
22428 			mutex_exit(SD_MUTEX(un));
22429 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22430 			if (err != 0) {
22431 				mutex_enter(SD_MUTEX(un));
22432 				un->un_ncmds_in_driver--;
22433 				ASSERT(un->un_ncmds_in_driver >= 0);
22434 				mutex_exit(SD_MUTEX(un));
22435 				err = EIO;
22436 				goto done_quick_assess;
22437 			}
22438 			mutex_enter(SD_MUTEX(un));
22439 			/* FALLTHROUGH */
22440 		case DKIOCREMOVABLE:
22441 		case DKIOCHOTPLUGGABLE:
22442 		case DKIOCINFO:
22443 		case DKIOCGMEDIAINFO:
22444 		case DKIOCGMEDIAINFOEXT:
22445 		case DKIOCSOLIDSTATE:
22446 		case DKIOC_CANFREE:
22447 		case MHIOCENFAILFAST:
22448 		case MHIOCSTATUS:
22449 		case MHIOCTKOWN:
22450 		case MHIOCRELEASE:
22451 		case MHIOCGRP_INKEYS:
22452 		case MHIOCGRP_INRESV:
22453 		case MHIOCGRP_REGISTER:
22454 		case MHIOCGRP_CLEAR:
22455 		case MHIOCGRP_RESERVE:
22456 		case MHIOCGRP_PREEMPTANDABORT:
22457 		case MHIOCGRP_REGISTERANDIGNOREKEY:
22458 		case CDROMCLOSETRAY:
22459 		case USCSICMD:
22460 		case USCSIMAXXFER:
22461 			goto skip_ready_valid;
22462 		default:
22463 			break;
22464 		}
22465 
22466 		mutex_exit(SD_MUTEX(un));
22467 		err = sd_ready_and_valid(ssc, SDPART(dev));
22468 		mutex_enter(SD_MUTEX(un));
22469 
22470 		if (err != SD_READY_VALID) {
22471 			switch (cmd) {
22472 			case DKIOCSTATE:
22473 			case CDROMGDRVSPEED:
22474 			case CDROMSDRVSPEED:
22475 			case FDEJECT:	/* for eject command */
22476 			case DKIOCEJECT:
22477 			case CDROMEJECT:
22478 			case DKIOCREMOVABLE:
22479 			case DKIOCHOTPLUGGABLE:
22480 				break;
22481 			default:
22482 				if (un->un_f_has_removable_media) {
22483 					err = ENXIO;
22484 				} else {
22485 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
22486 					if (err == SD_RESERVED_BY_OTHERS) {
22487 						err = EACCES;
22488 					} else {
22489 						err = EIO;
22490 					}
22491 				}
22492 				un->un_ncmds_in_driver--;
22493 				ASSERT(un->un_ncmds_in_driver >= 0);
22494 				mutex_exit(SD_MUTEX(un));
22495 
22496 				goto done_without_assess;
22497 			}
22498 		}
22499 	}
22500 
22501 skip_ready_valid:
22502 	mutex_exit(SD_MUTEX(un));
22503 
22504 	switch (cmd) {
22505 	case DKIOCINFO:
22506 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
22507 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
22508 		break;
22509 
22510 	case DKIOCGMEDIAINFO:
22511 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
22512 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
22513 		break;
22514 
22515 	case DKIOCGMEDIAINFOEXT:
22516 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFOEXT\n");
22517 		err = sd_get_media_info_ext(dev, (caddr_t)arg, flag);
22518 		break;
22519 
22520 	case DKIOCGGEOM:
22521 	case DKIOCGVTOC:
22522 	case DKIOCGEXTVTOC:
22523 	case DKIOCGAPART:
22524 	case DKIOCPARTINFO:
22525 	case DKIOCEXTPARTINFO:
22526 	case DKIOCSGEOM:
22527 	case DKIOCSAPART:
22528 	case DKIOCGETEFI:
22529 	case DKIOCPARTITION:
22530 	case DKIOCSVTOC:
22531 	case DKIOCSEXTVTOC:
22532 	case DKIOCSETEFI:
22533 	case DKIOCGMBOOT:
22534 	case DKIOCSMBOOT:
22535 	case DKIOCG_PHYGEOM:
22536 	case DKIOCG_VIRTGEOM:
22537 #if defined(__x86)
22538 	case DKIOCSETEXTPART:
22539 #endif
22540 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
22541 
22542 		/* TUR should spin up */
22543 
22544 		if (un->un_f_has_removable_media)
22545 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
22546 			    SD_CHECK_FOR_MEDIA);
22547 
22548 		else
22549 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22550 
22551 		if (err != 0)
22552 			goto done_with_assess;
22553 
22554 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
22555 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
22556 
22557 		if ((err == 0) &&
22558 		    ((cmd == DKIOCSETEFI) ||
22559 		    ((un->un_f_pkstats_enabled) &&
22560 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
22561 		    cmd == DKIOCSEXTVTOC)))) {
22562 
22563 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
22564 			    (void *)SD_PATH_DIRECT);
22565 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
22566 				sd_set_pstats(un);
22567 				SD_TRACE(SD_LOG_IO_PARTITION, un,
22568 				    "sd_ioctl: un:0x%p pstats created and "
22569 				    "set\n", un);
22570 			}
22571 		}
22572 
22573 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
22574 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
22575 
22576 			mutex_enter(SD_MUTEX(un));
22577 			if (un->un_f_devid_supported &&
22578 			    (un->un_f_opt_fab_devid == TRUE)) {
22579 				if (un->un_devid == NULL) {
22580 					sd_register_devid(ssc, SD_DEVINFO(un),
22581 					    SD_TARGET_IS_UNRESERVED);
22582 				} else {
22583 					/*
22584 					 * The device id for this disk
22585 					 * has been fabricated. The
22586 					 * device id must be preserved
22587 					 * by writing it back out to
22588 					 * disk.
22589 					 */
22590 					if (sd_write_deviceid(ssc) != 0) {
22591 						ddi_devid_free(un->un_devid);
22592 						un->un_devid = NULL;
22593 					}
22594 				}
22595 			}
22596 			mutex_exit(SD_MUTEX(un));
22597 		}
22598 
22599 		break;
22600 
22601 	case DKIOCLOCK:
22602 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
22603 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22604 		    SD_PATH_STANDARD);
22605 		goto done_with_assess;
22606 
22607 	case DKIOCUNLOCK:
22608 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
22609 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
22610 		    SD_PATH_STANDARD);
22611 		goto done_with_assess;
22612 
22613 	case DKIOCSTATE: {
22614 		enum dkio_state		state;
22615 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
22616 
22617 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
22618 			err = EFAULT;
22619 		} else {
22620 			err = sd_check_media(dev, state);
22621 			if (err == 0) {
22622 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
22623 				    sizeof (int), flag) != 0)
22624 					err = EFAULT;
22625 			}
22626 		}
22627 		break;
22628 	}
22629 
22630 	case DKIOCREMOVABLE:
22631 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
22632 		i = un->un_f_has_removable_media ? 1 : 0;
22633 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22634 			err = EFAULT;
22635 		} else {
22636 			err = 0;
22637 		}
22638 		break;
22639 
22640 	case DKIOCSOLIDSTATE:
22641 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSOLIDSTATE\n");
22642 		i = un->un_f_is_solid_state ? 1 : 0;
22643 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22644 			err = EFAULT;
22645 		} else {
22646 			err = 0;
22647 		}
22648 		break;
22649 
22650 	case DKIOCHOTPLUGGABLE:
22651 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
22652 		i = un->un_f_is_hotpluggable ? 1 : 0;
22653 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22654 			err = EFAULT;
22655 		} else {
22656 			err = 0;
22657 		}
22658 		break;
22659 
22660 	case DKIOCREADONLY:
22661 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREADONLY\n");
22662 		i = 0;
22663 		if ((ISCD(un) && !un->un_f_mmc_writable_media) ||
22664 		    (sr_check_wp(dev) != 0)) {
22665 			i = 1;
22666 		}
22667 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22668 			err = EFAULT;
22669 		} else {
22670 			err = 0;
22671 		}
22672 		break;
22673 
22674 	case DKIOCGTEMPERATURE:
22675 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
22676 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
22677 		break;
22678 
22679 	case MHIOCENFAILFAST:
22680 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
22681 		if ((err = drv_priv(cred_p)) == 0) {
22682 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
22683 		}
22684 		break;
22685 
22686 	case MHIOCTKOWN:
22687 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
22688 		if ((err = drv_priv(cred_p)) == 0) {
22689 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
22690 		}
22691 		break;
22692 
22693 	case MHIOCRELEASE:
22694 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
22695 		if ((err = drv_priv(cred_p)) == 0) {
22696 			err = sd_mhdioc_release(dev);
22697 		}
22698 		break;
22699 
22700 	case MHIOCSTATUS:
22701 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
22702 		if ((err = drv_priv(cred_p)) == 0) {
22703 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
22704 			case 0:
22705 				err = 0;
22706 				break;
22707 			case EACCES:
22708 				*rval_p = 1;
22709 				err = 0;
22710 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22711 				break;
22712 			default:
22713 				err = EIO;
22714 				goto done_with_assess;
22715 			}
22716 		}
22717 		break;
22718 
22719 	case MHIOCQRESERVE:
22720 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
22721 		if ((err = drv_priv(cred_p)) == 0) {
22722 			err = sd_reserve_release(dev, SD_RESERVE);
22723 		}
22724 		break;
22725 
22726 	case MHIOCREREGISTERDEVID:
22727 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
22728 		if (drv_priv(cred_p) == EPERM) {
22729 			err = EPERM;
22730 		} else if (!un->un_f_devid_supported) {
22731 			err = ENOTTY;
22732 		} else {
22733 			err = sd_mhdioc_register_devid(dev);
22734 		}
22735 		break;
22736 
22737 	case MHIOCGRP_INKEYS:
22738 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
22739 		if (((err = drv_priv(cred_p)) != EPERM) &&
22740 		    arg != (intptr_t)NULL) {
22741 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22742 				err = ENOTSUP;
22743 			} else {
22744 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
22745 				    flag);
22746 			}
22747 		}
22748 		break;
22749 
22750 	case MHIOCGRP_INRESV:
22751 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
22752 		if (((err = drv_priv(cred_p)) != EPERM) &&
22753 		    arg != (intptr_t)NULL) {
22754 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22755 				err = ENOTSUP;
22756 			} else {
22757 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
22758 			}
22759 		}
22760 		break;
22761 
22762 	case MHIOCGRP_REGISTER:
22763 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
22764 		if ((err = drv_priv(cred_p)) != EPERM) {
22765 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22766 				err = ENOTSUP;
22767 			} else if (arg != (intptr_t)NULL) {
22768 				mhioc_register_t reg;
22769 				if (ddi_copyin((void *)arg, &reg,
22770 				    sizeof (mhioc_register_t), flag) != 0) {
22771 					err = EFAULT;
22772 				} else {
22773 					err =
22774 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22775 					    ssc, SD_SCSI3_REGISTER,
22776 					    (uchar_t *)&reg);
22777 					if (err != 0)
22778 						goto done_with_assess;
22779 				}
22780 			}
22781 		}
22782 		break;
22783 
22784 	case MHIOCGRP_CLEAR:
22785 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_CLEAR\n");
22786 		if ((err = drv_priv(cred_p)) != EPERM) {
22787 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22788 				err = ENOTSUP;
22789 			} else if (arg != (intptr_t)NULL) {
22790 				mhioc_register_t reg;
22791 				if (ddi_copyin((void *)arg, &reg,
22792 				    sizeof (mhioc_register_t), flag) != 0) {
22793 					err = EFAULT;
22794 				} else {
22795 					err =
22796 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22797 					    ssc, SD_SCSI3_CLEAR,
22798 					    (uchar_t *)&reg);
22799 					if (err != 0)
22800 						goto done_with_assess;
22801 				}
22802 			}
22803 		}
22804 		break;
22805 
22806 	case MHIOCGRP_RESERVE:
22807 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
22808 		if ((err = drv_priv(cred_p)) != EPERM) {
22809 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22810 				err = ENOTSUP;
22811 			} else if (arg != (intptr_t)NULL) {
22812 				mhioc_resv_desc_t resv_desc;
22813 				if (ddi_copyin((void *)arg, &resv_desc,
22814 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
22815 					err = EFAULT;
22816 				} else {
22817 					err =
22818 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22819 					    ssc, SD_SCSI3_RESERVE,
22820 					    (uchar_t *)&resv_desc);
22821 					if (err != 0)
22822 						goto done_with_assess;
22823 				}
22824 			}
22825 		}
22826 		break;
22827 
22828 	case MHIOCGRP_PREEMPTANDABORT:
22829 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
22830 		if ((err = drv_priv(cred_p)) != EPERM) {
22831 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22832 				err = ENOTSUP;
22833 			} else if (arg != (intptr_t)NULL) {
22834 				mhioc_preemptandabort_t preempt_abort;
22835 				if (ddi_copyin((void *)arg, &preempt_abort,
22836 				    sizeof (mhioc_preemptandabort_t),
22837 				    flag) != 0) {
22838 					err = EFAULT;
22839 				} else {
22840 					err =
22841 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22842 					    ssc, SD_SCSI3_PREEMPTANDABORT,
22843 					    (uchar_t *)&preempt_abort);
22844 					if (err != 0)
22845 						goto done_with_assess;
22846 				}
22847 			}
22848 		}
22849 		break;
22850 
22851 	case MHIOCGRP_REGISTERANDIGNOREKEY:
22852 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
22853 		if ((err = drv_priv(cred_p)) != EPERM) {
22854 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22855 				err = ENOTSUP;
22856 			} else if (arg != (intptr_t)NULL) {
22857 				mhioc_registerandignorekey_t r_and_i;
22858 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
22859 				    sizeof (mhioc_registerandignorekey_t),
22860 				    flag) != 0) {
22861 					err = EFAULT;
22862 				} else {
22863 					err =
22864 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22865 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
22866 					    (uchar_t *)&r_and_i);
22867 					if (err != 0)
22868 						goto done_with_assess;
22869 				}
22870 			}
22871 		}
22872 		break;
22873 
22874 	case USCSICMD:
22875 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
22876 		cr = ddi_get_cred();
22877 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
22878 			err = EPERM;
22879 		} else {
22880 			enum uio_seg	uioseg;
22881 
22882 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
22883 			    UIO_USERSPACE;
22884 			if (un->un_f_format_in_progress == TRUE) {
22885 				err = EAGAIN;
22886 				break;
22887 			}
22888 
22889 			err = sd_ssc_send(ssc,
22890 			    (struct uscsi_cmd *)arg,
22891 			    flag, uioseg, SD_PATH_STANDARD);
22892 			if (err != 0)
22893 				goto done_with_assess;
22894 			else
22895 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22896 		}
22897 		break;
22898 
22899 	case USCSIMAXXFER:
22900 		SD_TRACE(SD_LOG_IOCTL, un, "USCSIMAXXFER\n");
22901 		cr = ddi_get_cred();
22902 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
22903 			err = EPERM;
22904 		} else {
22905 			const uscsi_xfer_t xfer = un->un_max_xfer_size;
22906 
22907 			if (ddi_copyout(&xfer, (void *)arg, sizeof (xfer),
22908 			    flag) != 0) {
22909 				err = EFAULT;
22910 			} else {
22911 				err = 0;
22912 			}
22913 		}
22914 		break;
22915 
22916 	case CDROMPAUSE:
22917 	case CDROMRESUME:
22918 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
22919 		if (!ISCD(un)) {
22920 			err = ENOTTY;
22921 		} else {
22922 			err = sr_pause_resume(dev, cmd);
22923 		}
22924 		break;
22925 
22926 	case CDROMPLAYMSF:
22927 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
22928 		if (!ISCD(un)) {
22929 			err = ENOTTY;
22930 		} else {
22931 			err = sr_play_msf(dev, (caddr_t)arg, flag);
22932 		}
22933 		break;
22934 
22935 	case CDROMPLAYTRKIND:
22936 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
22937 #if defined(__x86)
22938 		/*
22939 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
22940 		 */
22941 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22942 #else
22943 		if (!ISCD(un)) {
22944 #endif
22945 			err = ENOTTY;
22946 		} else {
22947 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
22948 		}
22949 		break;
22950 
22951 	case CDROMREADTOCHDR:
22952 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
22953 		if (!ISCD(un)) {
22954 			err = ENOTTY;
22955 		} else {
22956 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
22957 		}
22958 		break;
22959 
22960 	case CDROMREADTOCENTRY:
22961 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
22962 		if (!ISCD(un)) {
22963 			err = ENOTTY;
22964 		} else {
22965 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
22966 		}
22967 		break;
22968 
22969 	case CDROMSTOP:
22970 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
22971 		if (!ISCD(un)) {
22972 			err = ENOTTY;
22973 		} else {
22974 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22975 			    SD_TARGET_STOP, SD_PATH_STANDARD);
22976 			goto done_with_assess;
22977 		}
22978 		break;
22979 
22980 	case CDROMSTART:
22981 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
22982 		if (!ISCD(un)) {
22983 			err = ENOTTY;
22984 		} else {
22985 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22986 			    SD_TARGET_START, SD_PATH_STANDARD);
22987 			goto done_with_assess;
22988 		}
22989 		break;
22990 
22991 	case CDROMCLOSETRAY:
22992 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
22993 		if (!ISCD(un)) {
22994 			err = ENOTTY;
22995 		} else {
22996 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22997 			    SD_TARGET_CLOSE, SD_PATH_STANDARD);
22998 			goto done_with_assess;
22999 		}
23000 		break;
23001 
23002 	case FDEJECT:	/* for eject command */
23003 	case DKIOCEJECT:
23004 	case CDROMEJECT:
23005 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
23006 		if (!un->un_f_eject_media_supported) {
23007 			err = ENOTTY;
23008 		} else {
23009 			err = sr_eject(dev);
23010 		}
23011 		break;
23012 
23013 	case CDROMVOLCTRL:
23014 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
23015 		if (!ISCD(un)) {
23016 			err = ENOTTY;
23017 		} else {
23018 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
23019 		}
23020 		break;
23021 
23022 	case CDROMSUBCHNL:
23023 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
23024 		if (!ISCD(un)) {
23025 			err = ENOTTY;
23026 		} else {
23027 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
23028 		}
23029 		break;
23030 
23031 	case CDROMREADMODE2:
23032 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
23033 		if (!ISCD(un)) {
23034 			err = ENOTTY;
23035 		} else if (un->un_f_cfg_is_atapi == TRUE) {
23036 			/*
23037 			 * If the drive supports READ CD, use that instead of
23038 			 * switching the LBA size via a MODE SELECT
23039 			 * Block Descriptor
23040 			 */
23041 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
23042 		} else {
23043 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
23044 		}
23045 		break;
23046 
23047 	case CDROMREADMODE1:
23048 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
23049 		if (!ISCD(un)) {
23050 			err = ENOTTY;
23051 		} else {
23052 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
23053 		}
23054 		break;
23055 
23056 	case CDROMREADOFFSET:
23057 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
23058 		if (!ISCD(un)) {
23059 			err = ENOTTY;
23060 		} else {
23061 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
23062 			    flag);
23063 		}
23064 		break;
23065 
23066 	case CDROMSBLKMODE:
23067 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
23068 		/*
23069 		 * There is no means of changing block size in case of atapi
23070 		 * drives, thus return ENOTTY if drive type is atapi
23071 		 */
23072 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
23073 			err = ENOTTY;
23074 		} else if (un->un_f_mmc_cap == TRUE) {
23075 
23076 			/*
23077 			 * MMC Devices do not support changing the
23078 			 * logical block size
23079 			 *
23080 			 * Note: EINVAL is being returned instead of ENOTTY to
23081 			 * maintain consistancy with the original mmc
23082 			 * driver update.
23083 			 */
23084 			err = EINVAL;
23085 		} else {
23086 			mutex_enter(SD_MUTEX(un));
23087 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
23088 			    (un->un_ncmds_in_transport > 0)) {
23089 				mutex_exit(SD_MUTEX(un));
23090 				err = EINVAL;
23091 			} else {
23092 				mutex_exit(SD_MUTEX(un));
23093 				err = sr_change_blkmode(dev, cmd, arg, flag);
23094 			}
23095 		}
23096 		break;
23097 
23098 	case CDROMGBLKMODE:
23099 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
23100 		if (!ISCD(un)) {
23101 			err = ENOTTY;
23102 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
23103 		    (un->un_f_blockcount_is_valid != FALSE)) {
23104 			/*
23105 			 * Drive is an ATAPI drive so return target block
23106 			 * size for ATAPI drives since we cannot change the
23107 			 * blocksize on ATAPI drives. Used primarily to detect
23108 			 * if an ATAPI cdrom is present.
23109 			 */
23110 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
23111 			    sizeof (int), flag) != 0) {
23112 				err = EFAULT;
23113 			} else {
23114 				err = 0;
23115 			}
23116 
23117 		} else {
23118 			/*
23119 			 * Drive supports changing block sizes via a Mode
23120 			 * Select.
23121 			 */
23122 			err = sr_change_blkmode(dev, cmd, arg, flag);
23123 		}
23124 		break;
23125 
23126 	case CDROMGDRVSPEED:
23127 	case CDROMSDRVSPEED:
23128 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
23129 		if (!ISCD(un)) {
23130 			err = ENOTTY;
23131 		} else if (un->un_f_mmc_cap == TRUE) {
23132 			/*
23133 			 * Note: In the future the driver implementation
23134 			 * for getting and
23135 			 * setting cd speed should entail:
23136 			 * 1) If non-mmc try the Toshiba mode page
23137 			 *    (sr_change_speed)
23138 			 * 2) If mmc but no support for Real Time Streaming try
23139 			 *    the SET CD SPEED (0xBB) command
23140 			 *   (sr_atapi_change_speed)
23141 			 * 3) If mmc and support for Real Time Streaming
23142 			 *    try the GET PERFORMANCE and SET STREAMING
23143 			 *    commands (not yet implemented, 4380808)
23144 			 */
23145 			/*
23146 			 * As per recent MMC spec, CD-ROM speed is variable
23147 			 * and changes with LBA. Since there is no such
23148 			 * things as drive speed now, fail this ioctl.
23149 			 *
23150 			 * Note: EINVAL is returned for consistancy of original
23151 			 * implementation which included support for getting
23152 			 * the drive speed of mmc devices but not setting
23153 			 * the drive speed. Thus EINVAL would be returned
23154 			 * if a set request was made for an mmc device.
23155 			 * We no longer support get or set speed for
23156 			 * mmc but need to remain consistent with regard
23157 			 * to the error code returned.
23158 			 */
23159 			err = EINVAL;
23160 		} else if (un->un_f_cfg_is_atapi == TRUE) {
23161 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
23162 		} else {
23163 			err = sr_change_speed(dev, cmd, arg, flag);
23164 		}
23165 		break;
23166 
23167 	case CDROMCDDA:
23168 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
23169 		if (!ISCD(un)) {
23170 			err = ENOTTY;
23171 		} else {
23172 			err = sr_read_cdda(dev, (void *)arg, flag);
23173 		}
23174 		break;
23175 
23176 	case CDROMCDXA:
23177 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
23178 		if (!ISCD(un)) {
23179 			err = ENOTTY;
23180 		} else {
23181 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
23182 		}
23183 		break;
23184 
23185 	case CDROMSUBCODE:
23186 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
23187 		if (!ISCD(un)) {
23188 			err = ENOTTY;
23189 		} else {
23190 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
23191 		}
23192 		break;
23193 
23194 
23195 #ifdef SDDEBUG
23196 /* RESET/ABORTS testing ioctls */
23197 	case DKIOCRESET: {
23198 		int	reset_level;
23199 
23200 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
23201 			err = EFAULT;
23202 		} else {
23203 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
23204 			    "reset_level = 0x%lx\n", reset_level);
23205 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
23206 				err = 0;
23207 			} else {
23208 				err = EIO;
23209 			}
23210 		}
23211 		break;
23212 	}
23213 
23214 	case DKIOCABORT:
23215 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
23216 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
23217 			err = 0;
23218 		} else {
23219 			err = EIO;
23220 		}
23221 		break;
23222 #endif
23223 
23224 #ifdef SD_FAULT_INJECTION
23225 /* SDIOC FaultInjection testing ioctls */
23226 	case SDIOCSTART:
23227 	case SDIOCSTOP:
23228 	case SDIOCINSERTPKT:
23229 	case SDIOCINSERTXB:
23230 	case SDIOCINSERTUN:
23231 	case SDIOCINSERTARQ:
23232 	case SDIOCPUSH:
23233 	case SDIOCRETRIEVE:
23234 	case SDIOCRUN:
23235 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
23236 		    "SDIOC detected cmd:0x%X:\n", cmd);
23237 		/* call error generator */
23238 		sd_faultinjection_ioctl(cmd, arg, un);
23239 		err = 0;
23240 		break;
23241 
23242 #endif /* SD_FAULT_INJECTION */
23243 
23244 	case DKIOCFLUSHWRITECACHE:
23245 		{
23246 			struct dk_callback *dkc = (struct dk_callback *)arg;
23247 
23248 			mutex_enter(SD_MUTEX(un));
23249 			if (!un->un_f_sync_cache_supported ||
23250 			    !un->un_f_write_cache_enabled) {
23251 				err = un->un_f_sync_cache_supported ?
23252 				    0 : ENOTSUP;
23253 				mutex_exit(SD_MUTEX(un));
23254 				if ((flag & FKIOCTL) && dkc != NULL &&
23255 				    dkc->dkc_callback != NULL) {
23256 					(*dkc->dkc_callback)(dkc->dkc_cookie,
23257 					    err);
23258 					/*
23259 					 * Did callback and reported error.
23260 					 * Since we did a callback, ioctl
23261 					 * should return 0.
23262 					 */
23263 					err = 0;
23264 				}
23265 				break;
23266 			}
23267 			mutex_exit(SD_MUTEX(un));
23268 
23269 			if ((flag & FKIOCTL) && dkc != NULL &&
23270 			    dkc->dkc_callback != NULL) {
23271 				/* async SYNC CACHE request */
23272 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
23273 			} else {
23274 				/* synchronous SYNC CACHE request */
23275 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
23276 			}
23277 		}
23278 		break;
23279 
23280 	case DKIOCFREE:
23281 		{
23282 			dkioc_free_list_t *dfl = (dkioc_free_list_t *)arg;
23283 
23284 			/* bad ioctls shouldn't panic */
23285 			if (dfl == NULL) {
23286 				/* check kernel callers strictly in debug */
23287 				ASSERT0(flag & FKIOCTL);
23288 				err = SET_ERROR(EINVAL);
23289 				break;
23290 			}
23291 			/* synchronous UNMAP request */
23292 			err = sd_send_scsi_UNMAP(dev, ssc, dfl, flag);
23293 		}
23294 		break;
23295 
23296 	case DKIOC_CANFREE:
23297 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC_CANFREE\n");
23298 		i = (un->un_thin_flags & SD_THIN_PROV_ENABLED) ? 1 : 0;
23299 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
23300 			err = EFAULT;
23301 		} else {
23302 			err = 0;
23303 		}
23304 		break;
23305 
23306 	case DKIOCGETWCE: {
23307 
23308 		int wce;
23309 
23310 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
23311 			break;
23312 		}
23313 
23314 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
23315 			err = EFAULT;
23316 		}
23317 		break;
23318 	}
23319 
23320 	case DKIOCSETWCE: {
23321 
23322 		int wce, sync_supported;
23323 		int cur_wce = 0;
23324 
23325 		if (!un->un_f_cache_mode_changeable) {
23326 			err = EINVAL;
23327 			break;
23328 		}
23329 
23330 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
23331 			err = EFAULT;
23332 			break;
23333 		}
23334 
23335 		/*
23336 		 * Synchronize multiple threads trying to enable
23337 		 * or disable the cache via the un_f_wcc_cv
23338 		 * condition variable.
23339 		 */
23340 		mutex_enter(SD_MUTEX(un));
23341 
23342 		/*
23343 		 * Don't allow the cache to be enabled if the
23344 		 * config file has it disabled.
23345 		 */
23346 		if (un->un_f_opt_disable_cache && wce) {
23347 			mutex_exit(SD_MUTEX(un));
23348 			err = EINVAL;
23349 			break;
23350 		}
23351 
23352 		/*
23353 		 * Wait for write cache change in progress
23354 		 * bit to be clear before proceeding.
23355 		 */
23356 		while (un->un_f_wcc_inprog)
23357 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
23358 
23359 		un->un_f_wcc_inprog = 1;
23360 
23361 		mutex_exit(SD_MUTEX(un));
23362 
23363 		/*
23364 		 * Get the current write cache state
23365 		 */
23366 		if ((err = sd_get_write_cache_enabled(ssc, &cur_wce)) != 0) {
23367 			mutex_enter(SD_MUTEX(un));
23368 			un->un_f_wcc_inprog = 0;
23369 			cv_broadcast(&un->un_wcc_cv);
23370 			mutex_exit(SD_MUTEX(un));
23371 			break;
23372 		}
23373 
23374 		mutex_enter(SD_MUTEX(un));
23375 		un->un_f_write_cache_enabled = (cur_wce != 0);
23376 
23377 		if (un->un_f_write_cache_enabled && wce == 0) {
23378 			/*
23379 			 * Disable the write cache.  Don't clear
23380 			 * un_f_write_cache_enabled until after
23381 			 * the mode select and flush are complete.
23382 			 */
23383 			sync_supported = un->un_f_sync_cache_supported;
23384 
23385 			/*
23386 			 * If cache flush is suppressed, we assume that the
23387 			 * controller firmware will take care of managing the
23388 			 * write cache for us: no need to explicitly
23389 			 * disable it.
23390 			 */
23391 			if (!un->un_f_suppress_cache_flush) {
23392 				mutex_exit(SD_MUTEX(un));
23393 				if ((err = sd_cache_control(ssc,
23394 				    SD_CACHE_NOCHANGE,
23395 				    SD_CACHE_DISABLE)) == 0 &&
23396 				    sync_supported) {
23397 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
23398 					    NULL);
23399 				}
23400 			} else {
23401 				mutex_exit(SD_MUTEX(un));
23402 			}
23403 
23404 			mutex_enter(SD_MUTEX(un));
23405 			if (err == 0) {
23406 				un->un_f_write_cache_enabled = 0;
23407 			}
23408 
23409 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
23410 			/*
23411 			 * Set un_f_write_cache_enabled first, so there is
23412 			 * no window where the cache is enabled, but the
23413 			 * bit says it isn't.
23414 			 */
23415 			un->un_f_write_cache_enabled = 1;
23416 
23417 			/*
23418 			 * If cache flush is suppressed, we assume that the
23419 			 * controller firmware will take care of managing the
23420 			 * write cache for us: no need to explicitly
23421 			 * enable it.
23422 			 */
23423 			if (!un->un_f_suppress_cache_flush) {
23424 				mutex_exit(SD_MUTEX(un));
23425 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
23426 				    SD_CACHE_ENABLE);
23427 			} else {
23428 				mutex_exit(SD_MUTEX(un));
23429 			}
23430 
23431 			mutex_enter(SD_MUTEX(un));
23432 
23433 			if (err) {
23434 				un->un_f_write_cache_enabled = 0;
23435 			}
23436 		}
23437 
23438 		un->un_f_wcc_inprog = 0;
23439 		cv_broadcast(&un->un_wcc_cv);
23440 		mutex_exit(SD_MUTEX(un));
23441 		break;
23442 	}
23443 
23444 	default:
23445 		err = ENOTTY;
23446 		break;
23447 	}
23448 	mutex_enter(SD_MUTEX(un));
23449 	un->un_ncmds_in_driver--;
23450 	ASSERT(un->un_ncmds_in_driver >= 0);
23451 	mutex_exit(SD_MUTEX(un));
23452 
23453 
23454 done_without_assess:
23455 	sd_ssc_fini(ssc);
23456 
23457 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23458 	return (err);
23459 
23460 done_with_assess:
23461 	mutex_enter(SD_MUTEX(un));
23462 	un->un_ncmds_in_driver--;
23463 	ASSERT(un->un_ncmds_in_driver >= 0);
23464 	mutex_exit(SD_MUTEX(un));
23465 
23466 done_quick_assess:
23467 	if (err != 0)
23468 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23469 	/* Uninitialize sd_ssc_t pointer */
23470 	sd_ssc_fini(ssc);
23471 
23472 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23473 	return (err);
23474 }
23475 
23476 
23477 /*
23478  *    Function: sd_dkio_ctrl_info
23479  *
23480  * Description: This routine is the driver entry point for handling controller
23481  *		information ioctl requests (DKIOCINFO).
23482  *
23483  *   Arguments: dev  - the device number
23484  *		arg  - pointer to user provided dk_cinfo structure
23485  *		       specifying the controller type and attributes.
23486  *		flag - this argument is a pass through to ddi_copyxxx()
23487  *		       directly from the mode argument of ioctl().
23488  *
23489  * Return Code: 0
23490  *		EFAULT
23491  *		ENXIO
23492  */
23493 
23494 static int
23495 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
23496 {
23497 	struct sd_lun	*un = NULL;
23498 	struct dk_cinfo	*info;
23499 	dev_info_t	*pdip;
23500 	int		lun, tgt;
23501 
23502 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23503 		return (ENXIO);
23504 	}
23505 
23506 	info = (struct dk_cinfo *)
23507 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
23508 
23509 	switch (un->un_ctype) {
23510 	case CTYPE_CDROM:
23511 		info->dki_ctype = DKC_CDROM;
23512 		break;
23513 	default:
23514 		info->dki_ctype = DKC_SCSI_CCS;
23515 		break;
23516 	}
23517 	pdip = ddi_get_parent(SD_DEVINFO(un));
23518 	info->dki_cnum = ddi_get_instance(pdip);
23519 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
23520 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
23521 	} else {
23522 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
23523 		    DK_DEVLEN - 1);
23524 	}
23525 
23526 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23527 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
23528 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23529 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
23530 
23531 	/* Unit Information */
23532 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
23533 	info->dki_slave = ((tgt << 3) | lun);
23534 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
23535 	    DK_DEVLEN - 1);
23536 	info->dki_flags = DKI_FMTVOL;
23537 	info->dki_partition = SDPART(dev);
23538 
23539 	/* Max Transfer size of this device in blocks */
23540 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
23541 	info->dki_addr = 0;
23542 	info->dki_space = 0;
23543 	info->dki_prio = 0;
23544 	info->dki_vec = 0;
23545 
23546 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
23547 		kmem_free(info, sizeof (struct dk_cinfo));
23548 		return (EFAULT);
23549 	} else {
23550 		kmem_free(info, sizeof (struct dk_cinfo));
23551 		return (0);
23552 	}
23553 }
23554 
23555 /*
23556  *    Function: sd_get_media_info_com
23557  *
23558  * Description: This routine returns the information required to populate
23559  *		the fields for the dk_minfo/dk_minfo_ext structures.
23560  *
23561  *   Arguments: dev		- the device number
23562  *		dki_media_type	- media_type
23563  *		dki_lbsize	- logical block size
23564  *		dki_capacity	- capacity in blocks
23565  *		dki_pbsize	- physical block size (if requested)
23566  *
23567  * Return Code: 0
23568  *		EACCESS
23569  *		EFAULT
23570  *		ENXIO
23571  *		EIO
23572  */
23573 static int
23574 sd_get_media_info_com(dev_t dev, uint_t *dki_media_type, uint_t *dki_lbsize,
23575     diskaddr_t *dki_capacity, uint_t *dki_pbsize)
23576 {
23577 	struct sd_lun		*un = NULL;
23578 	struct uscsi_cmd	com;
23579 	struct scsi_inquiry	*sinq;
23580 	u_longlong_t		media_capacity;
23581 	uint64_t		capacity;
23582 	uint_t			lbasize;
23583 	uint_t			pbsize;
23584 	uchar_t			*out_data;
23585 	uchar_t			*rqbuf;
23586 	int			rval = 0;
23587 	int			rtn;
23588 	sd_ssc_t		*ssc;
23589 
23590 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
23591 	    (un->un_state == SD_STATE_OFFLINE)) {
23592 		return (ENXIO);
23593 	}
23594 
23595 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info_com: entry\n");
23596 
23597 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
23598 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
23599 	ssc = sd_ssc_init(un);
23600 
23601 	/* Issue a TUR to determine if the drive is ready with media present */
23602 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
23603 	if (rval == ENXIO) {
23604 		goto done;
23605 	} else if (rval != 0) {
23606 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23607 	}
23608 
23609 	/* Now get configuration data */
23610 	if (ISCD(un)) {
23611 		*dki_media_type = DK_CDROM;
23612 
23613 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
23614 		if (un->un_f_mmc_cap == TRUE) {
23615 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
23616 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
23617 			    SD_PATH_STANDARD);
23618 
23619 			if (rtn) {
23620 				/*
23621 				 * We ignore all failures for CD and need to
23622 				 * put the assessment before processing code
23623 				 * to avoid missing assessment for FMA.
23624 				 */
23625 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23626 				/*
23627 				 * Failed for other than an illegal request
23628 				 * or command not supported
23629 				 */
23630 				if ((com.uscsi_status == STATUS_CHECK) &&
23631 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
23632 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
23633 					    (rqbuf[12] != 0x20)) {
23634 						rval = EIO;
23635 						goto no_assessment;
23636 					}
23637 				}
23638 			} else {
23639 				/*
23640 				 * The GET CONFIGURATION command succeeded
23641 				 * so set the media type according to the
23642 				 * returned data
23643 				 */
23644 				*dki_media_type = out_data[6];
23645 				*dki_media_type <<= 8;
23646 				*dki_media_type |= out_data[7];
23647 			}
23648 		}
23649 	} else {
23650 		/*
23651 		 * The profile list is not available, so we attempt to identify
23652 		 * the media type based on the inquiry data
23653 		 */
23654 		sinq = un->un_sd->sd_inq;
23655 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
23656 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
23657 			/* This is a direct access device  or optical disk */
23658 			*dki_media_type = DK_FIXED_DISK;
23659 
23660 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
23661 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
23662 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
23663 					*dki_media_type = DK_ZIP;
23664 				} else if (
23665 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
23666 					*dki_media_type = DK_JAZ;
23667 				}
23668 			}
23669 		} else {
23670 			/*
23671 			 * Not a CD, direct access or optical disk so return
23672 			 * unknown media
23673 			 */
23674 			*dki_media_type = DK_UNKNOWN;
23675 		}
23676 	}
23677 
23678 	/*
23679 	 * Now read the capacity so we can provide the lbasize,
23680 	 * pbsize and capacity.
23681 	 */
23682 	if (dki_pbsize && un->un_f_descr_format_supported) {
23683 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
23684 		    &pbsize, SD_PATH_DIRECT);
23685 
23686 		/*
23687 		 * Override the physical blocksize if the instance already
23688 		 * has a larger value.
23689 		 */
23690 		pbsize = MAX(pbsize, un->un_phy_blocksize);
23691 	}
23692 
23693 	if (dki_pbsize == NULL || rval != 0 ||
23694 	    !un->un_f_descr_format_supported) {
23695 		rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
23696 		    SD_PATH_DIRECT);
23697 
23698 		switch (rval) {
23699 		case 0:
23700 			if (un->un_f_enable_rmw &&
23701 			    un->un_phy_blocksize != 0) {
23702 				pbsize = un->un_phy_blocksize;
23703 			} else {
23704 				pbsize = lbasize;
23705 			}
23706 			media_capacity = capacity;
23707 
23708 			/*
23709 			 * sd_send_scsi_READ_CAPACITY() reports capacity in
23710 			 * un->un_sys_blocksize chunks. So we need to convert
23711 			 * it into cap.lbsize chunks.
23712 			 */
23713 			if (un->un_f_has_removable_media) {
23714 				media_capacity *= un->un_sys_blocksize;
23715 				media_capacity /= lbasize;
23716 			}
23717 			break;
23718 		case EACCES:
23719 			rval = EACCES;
23720 			goto done;
23721 		default:
23722 			rval = EIO;
23723 			goto done;
23724 		}
23725 	} else {
23726 		if (un->un_f_enable_rmw &&
23727 		    !ISP2(pbsize % DEV_BSIZE)) {
23728 			pbsize = SSD_SECSIZE;
23729 		} else if (!ISP2(lbasize % DEV_BSIZE) ||
23730 		    !ISP2(pbsize % DEV_BSIZE)) {
23731 			pbsize = lbasize = DEV_BSIZE;
23732 		}
23733 		media_capacity = capacity;
23734 	}
23735 
23736 	/*
23737 	 * If lun is expanded dynamically, update the un structure.
23738 	 */
23739 	mutex_enter(SD_MUTEX(un));
23740 	if ((un->un_f_blockcount_is_valid == TRUE) &&
23741 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
23742 	    (capacity > un->un_blockcount)) {
23743 		un->un_f_expnevent = B_FALSE;
23744 		sd_update_block_info(un, lbasize, capacity);
23745 	}
23746 	mutex_exit(SD_MUTEX(un));
23747 
23748 	*dki_lbsize = lbasize;
23749 	*dki_capacity = media_capacity;
23750 	if (dki_pbsize)
23751 		*dki_pbsize = pbsize;
23752 
23753 done:
23754 	if (rval != 0) {
23755 		if (rval == EIO)
23756 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23757 		else
23758 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23759 	}
23760 no_assessment:
23761 	sd_ssc_fini(ssc);
23762 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
23763 	kmem_free(rqbuf, SENSE_LENGTH);
23764 	return (rval);
23765 }
23766 
23767 /*
23768  *    Function: sd_get_media_info
23769  *
23770  * Description: This routine is the driver entry point for handling ioctl
23771  *		requests for the media type or command set profile used by the
23772  *		drive to operate on the media (DKIOCGMEDIAINFO).
23773  *
23774  *   Arguments: dev	- the device number
23775  *		arg	- pointer to user provided dk_minfo structure
23776  *			  specifying the media type, logical block size and
23777  *			  drive capacity.
23778  *		flag	- this argument is a pass through to ddi_copyxxx()
23779  *			  directly from the mode argument of ioctl().
23780  *
23781  * Return Code: returns the value from sd_get_media_info_com
23782  */
23783 static int
23784 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
23785 {
23786 	struct dk_minfo		mi;
23787 	int			rval;
23788 
23789 	rval = sd_get_media_info_com(dev, &mi.dki_media_type,
23790 	    &mi.dki_lbsize, &mi.dki_capacity, NULL);
23791 
23792 	if (rval)
23793 		return (rval);
23794 	if (ddi_copyout(&mi, arg, sizeof (struct dk_minfo), flag))
23795 		rval = EFAULT;
23796 	return (rval);
23797 }
23798 
23799 /*
23800  *    Function: sd_get_media_info_ext
23801  *
23802  * Description: This routine is the driver entry point for handling ioctl
23803  *		requests for the media type or command set profile used by the
23804  *		drive to operate on the media (DKIOCGMEDIAINFOEXT). The
23805  *		difference this ioctl and DKIOCGMEDIAINFO is the return value
23806  *		of this ioctl contains both logical block size and physical
23807  *		block size.
23808  *
23809  *
23810  *   Arguments: dev	- the device number
23811  *		arg	- pointer to user provided dk_minfo_ext structure
23812  *			  specifying the media type, logical block size,
23813  *			  physical block size and disk capacity.
23814  *		flag	- this argument is a pass through to ddi_copyxxx()
23815  *			  directly from the mode argument of ioctl().
23816  *
23817  * Return Code: returns the value from sd_get_media_info_com
23818  */
23819 static int
23820 sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag)
23821 {
23822 	struct dk_minfo_ext	mie;
23823 	int			rval = 0;
23824 	size_t			len;
23825 
23826 	rval = sd_get_media_info_com(dev, &mie.dki_media_type,
23827 	    &mie.dki_lbsize, &mie.dki_capacity, &mie.dki_pbsize);
23828 
23829 	if (rval)
23830 		return (rval);
23831 
23832 	switch (ddi_model_convert_from(flag & FMODELS)) {
23833 	case DDI_MODEL_ILP32:
23834 		len = sizeof (struct dk_minfo_ext32);
23835 		break;
23836 	default:
23837 		len = sizeof (struct dk_minfo_ext);
23838 		break;
23839 	}
23840 
23841 	if (ddi_copyout(&mie, arg, len, flag))
23842 		rval = EFAULT;
23843 	return (rval);
23844 
23845 }
23846 
23847 /*
23848  *    Function: sd_watch_request_submit
23849  *
23850  * Description: Call scsi_watch_request_submit or scsi_mmc_watch_request_submit
23851  *		depending on which is supported by device.
23852  */
23853 static opaque_t
23854 sd_watch_request_submit(struct sd_lun *un)
23855 {
23856 	dev_t			dev;
23857 
23858 	/* All submissions are unified to use same device number */
23859 	dev = sd_make_device(SD_DEVINFO(un));
23860 
23861 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
23862 		return (scsi_mmc_watch_request_submit(SD_SCSI_DEVP(un),
23863 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23864 		    (caddr_t)dev));
23865 	} else {
23866 		return (scsi_watch_request_submit(SD_SCSI_DEVP(un),
23867 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23868 		    (caddr_t)dev));
23869 	}
23870 }
23871 
23872 
23873 /*
23874  *    Function: sd_check_media
23875  *
23876  * Description: This utility routine implements the functionality for the
23877  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
23878  *		driver state changes from that specified by the user
23879  *		(inserted or ejected). For example, if the user specifies
23880  *		DKIO_EJECTED and the current media state is inserted this
23881  *		routine will immediately return DKIO_INSERTED. However, if the
23882  *		current media state is not inserted the user thread will be
23883  *		blocked until the drive state changes. If DKIO_NONE is specified
23884  *		the user thread will block until a drive state change occurs.
23885  *
23886  *   Arguments: dev  - the device number
23887  *		state  - user pointer to a dkio_state, updated with the current
23888  *			drive state at return.
23889  *
23890  * Return Code: ENXIO
23891  *		EIO
23892  *		EAGAIN
23893  *		EINTR
23894  */
23895 
23896 static int
23897 sd_check_media(dev_t dev, enum dkio_state state)
23898 {
23899 	struct sd_lun		*un = NULL;
23900 	enum dkio_state		prev_state;
23901 	opaque_t		token = NULL;
23902 	int			rval = 0;
23903 	sd_ssc_t		*ssc;
23904 
23905 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23906 		return (ENXIO);
23907 	}
23908 
23909 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
23910 
23911 	ssc = sd_ssc_init(un);
23912 
23913 	mutex_enter(SD_MUTEX(un));
23914 
23915 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
23916 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
23917 
23918 	prev_state = un->un_mediastate;
23919 
23920 	/* is there anything to do? */
23921 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
23922 		/*
23923 		 * submit the request to the scsi_watch service;
23924 		 * scsi_media_watch_cb() does the real work
23925 		 */
23926 		mutex_exit(SD_MUTEX(un));
23927 
23928 		/*
23929 		 * This change handles the case where a scsi watch request is
23930 		 * added to a device that is powered down. To accomplish this
23931 		 * we power up the device before adding the scsi watch request,
23932 		 * since the scsi watch sends a TUR directly to the device
23933 		 * which the device cannot handle if it is powered down.
23934 		 */
23935 		if (sd_pm_entry(un) != DDI_SUCCESS) {
23936 			mutex_enter(SD_MUTEX(un));
23937 			goto done;
23938 		}
23939 
23940 		token = sd_watch_request_submit(un);
23941 
23942 		sd_pm_exit(un);
23943 
23944 		mutex_enter(SD_MUTEX(un));
23945 		if (token == NULL) {
23946 			rval = EAGAIN;
23947 			goto done;
23948 		}
23949 
23950 		/*
23951 		 * This is a special case IOCTL that doesn't return
23952 		 * until the media state changes. Routine sdpower
23953 		 * knows about and handles this so don't count it
23954 		 * as an active cmd in the driver, which would
23955 		 * keep the device busy to the pm framework.
23956 		 * If the count isn't decremented the device can't
23957 		 * be powered down.
23958 		 */
23959 		un->un_ncmds_in_driver--;
23960 		ASSERT(un->un_ncmds_in_driver >= 0);
23961 
23962 		/*
23963 		 * if a prior request had been made, this will be the same
23964 		 * token, as scsi_watch was designed that way.
23965 		 */
23966 		un->un_swr_token = token;
23967 		un->un_specified_mediastate = state;
23968 
23969 		/*
23970 		 * now wait for media change
23971 		 * we will not be signalled unless mediastate == state but it is
23972 		 * still better to test for this condition, since there is a
23973 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
23974 		 */
23975 		SD_TRACE(SD_LOG_COMMON, un,
23976 		    "sd_check_media: waiting for media state change\n");
23977 		while (un->un_mediastate == state) {
23978 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
23979 				SD_TRACE(SD_LOG_COMMON, un,
23980 				    "sd_check_media: waiting for media state "
23981 				    "was interrupted\n");
23982 				un->un_ncmds_in_driver++;
23983 				rval = EINTR;
23984 				goto done;
23985 			}
23986 			SD_TRACE(SD_LOG_COMMON, un,
23987 			    "sd_check_media: received signal, state=%x\n",
23988 			    un->un_mediastate);
23989 		}
23990 		/*
23991 		 * Inc the counter to indicate the device once again
23992 		 * has an active outstanding cmd.
23993 		 */
23994 		un->un_ncmds_in_driver++;
23995 	}
23996 
23997 	/* invalidate geometry */
23998 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
23999 		sr_ejected(un);
24000 	}
24001 
24002 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
24003 		uint64_t	capacity;
24004 		uint_t		lbasize;
24005 
24006 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
24007 		mutex_exit(SD_MUTEX(un));
24008 		/*
24009 		 * Since the following routines use SD_PATH_DIRECT, we must
24010 		 * call PM directly before the upcoming disk accesses. This
24011 		 * may cause the disk to be power/spin up.
24012 		 */
24013 
24014 		if (sd_pm_entry(un) == DDI_SUCCESS) {
24015 			rval = sd_send_scsi_READ_CAPACITY(ssc,
24016 			    &capacity, &lbasize, SD_PATH_DIRECT);
24017 			if (rval != 0) {
24018 				sd_pm_exit(un);
24019 				if (rval == EIO)
24020 					sd_ssc_assessment(ssc,
24021 					    SD_FMT_STATUS_CHECK);
24022 				else
24023 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24024 				mutex_enter(SD_MUTEX(un));
24025 				goto done;
24026 			}
24027 		} else {
24028 			rval = EIO;
24029 			mutex_enter(SD_MUTEX(un));
24030 			goto done;
24031 		}
24032 		mutex_enter(SD_MUTEX(un));
24033 
24034 		sd_update_block_info(un, lbasize, capacity);
24035 
24036 		/*
24037 		 *  Check if the media in the device is writable or not
24038 		 */
24039 		if (ISCD(un)) {
24040 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
24041 		}
24042 
24043 		mutex_exit(SD_MUTEX(un));
24044 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
24045 		if ((cmlb_validate(un->un_cmlbhandle, 0,
24046 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
24047 			sd_set_pstats(un);
24048 			SD_TRACE(SD_LOG_IO_PARTITION, un,
24049 			    "sd_check_media: un:0x%p pstats created and "
24050 			    "set\n", un);
24051 		}
24052 
24053 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
24054 		    SD_PATH_DIRECT);
24055 
24056 		sd_pm_exit(un);
24057 
24058 		if (rval != 0) {
24059 			if (rval == EIO)
24060 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24061 			else
24062 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24063 		}
24064 
24065 		mutex_enter(SD_MUTEX(un));
24066 	}
24067 done:
24068 	sd_ssc_fini(ssc);
24069 	un->un_f_watcht_stopped = FALSE;
24070 	if (token != NULL && un->un_swr_token != NULL) {
24071 		/*
24072 		 * Use of this local token and the mutex ensures that we avoid
24073 		 * some race conditions associated with terminating the
24074 		 * scsi watch.
24075 		 */
24076 		token = un->un_swr_token;
24077 		mutex_exit(SD_MUTEX(un));
24078 		(void) scsi_watch_request_terminate(token,
24079 		    SCSI_WATCH_TERMINATE_WAIT);
24080 		if (scsi_watch_get_ref_count(token) == 0) {
24081 			mutex_enter(SD_MUTEX(un));
24082 			un->un_swr_token = (opaque_t)NULL;
24083 		} else {
24084 			mutex_enter(SD_MUTEX(un));
24085 		}
24086 	}
24087 
24088 	/*
24089 	 * Update the capacity kstat value, if no media previously
24090 	 * (capacity kstat is 0) and a media has been inserted
24091 	 * (un_f_blockcount_is_valid == TRUE)
24092 	 */
24093 	if (un->un_errstats) {
24094 		struct sd_errstats	*stp = NULL;
24095 
24096 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
24097 		if ((stp->sd_capacity.value.ui64 == 0) &&
24098 		    (un->un_f_blockcount_is_valid == TRUE)) {
24099 			stp->sd_capacity.value.ui64 =
24100 			    (uint64_t)((uint64_t)un->un_blockcount *
24101 			    un->un_sys_blocksize);
24102 		}
24103 	}
24104 	mutex_exit(SD_MUTEX(un));
24105 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
24106 	return (rval);
24107 }
24108 
24109 
24110 /*
24111  *    Function: sd_delayed_cv_broadcast
24112  *
24113  * Description: Delayed cv_broadcast to allow for target to recover from media
24114  *		insertion.
24115  *
24116  *   Arguments: arg - driver soft state (unit) structure
24117  */
24118 
24119 static void
24120 sd_delayed_cv_broadcast(void *arg)
24121 {
24122 	struct sd_lun *un = arg;
24123 
24124 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
24125 
24126 	mutex_enter(SD_MUTEX(un));
24127 	un->un_dcvb_timeid = NULL;
24128 	cv_broadcast(&un->un_state_cv);
24129 	mutex_exit(SD_MUTEX(un));
24130 }
24131 
24132 
24133 /*
24134  *    Function: sd_media_watch_cb
24135  *
24136  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
24137  *		routine processes the TUR sense data and updates the driver
24138  *		state if a transition has occurred. The user thread
24139  *		(sd_check_media) is then signalled.
24140  *
24141  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24142  *			among multiple watches that share this callback function
24143  *		resultp - scsi watch facility result packet containing scsi
24144  *			  packet, status byte and sense data
24145  *
24146  * Return Code: 0 for success, -1 for failure
24147  */
24148 
24149 static int
24150 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
24151 {
24152 	struct sd_lun			*un;
24153 	struct scsi_status		*statusp = resultp->statusp;
24154 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
24155 	enum dkio_state			state = DKIO_NONE;
24156 	dev_t				dev = (dev_t)arg;
24157 	uchar_t				actual_sense_length;
24158 	uint8_t				skey, asc, ascq;
24159 
24160 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24161 		return (-1);
24162 	}
24163 	actual_sense_length = resultp->actual_sense_length;
24164 
24165 	mutex_enter(SD_MUTEX(un));
24166 	SD_TRACE(SD_LOG_COMMON, un,
24167 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
24168 	    *((char *)statusp), (void *)sensep, actual_sense_length);
24169 
24170 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
24171 		un->un_mediastate = DKIO_DEV_GONE;
24172 		cv_broadcast(&un->un_state_cv);
24173 		mutex_exit(SD_MUTEX(un));
24174 
24175 		return (0);
24176 	}
24177 
24178 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
24179 		if (sd_gesn_media_data_valid(resultp->mmc_data)) {
24180 			if ((resultp->mmc_data[5] &
24181 			    SD_GESN_MEDIA_EVENT_STATUS_PRESENT) != 0) {
24182 				state = DKIO_INSERTED;
24183 			} else {
24184 				state = DKIO_EJECTED;
24185 			}
24186 			if ((resultp->mmc_data[4] & SD_GESN_MEDIA_EVENT_CODE) ==
24187 			    SD_GESN_MEDIA_EVENT_EJECTREQUEST) {
24188 				sd_log_eject_request_event(un, KM_NOSLEEP);
24189 			}
24190 		}
24191 	} else if (sensep != NULL) {
24192 		/*
24193 		 * If there was a check condition then sensep points to valid
24194 		 * sense data. If status was not a check condition but a
24195 		 * reservation or busy status then the new state is DKIO_NONE.
24196 		 */
24197 		skey = scsi_sense_key(sensep);
24198 		asc = scsi_sense_asc(sensep);
24199 		ascq = scsi_sense_ascq(sensep);
24200 
24201 		SD_INFO(SD_LOG_COMMON, un,
24202 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
24203 		    skey, asc, ascq);
24204 		/* This routine only uses up to 13 bytes of sense data. */
24205 		if (actual_sense_length >= 13) {
24206 			if (skey == KEY_UNIT_ATTENTION) {
24207 				if (asc == 0x28) {
24208 					state = DKIO_INSERTED;
24209 				}
24210 			} else if (skey == KEY_NOT_READY) {
24211 				/*
24212 				 * Sense data of 02/06/00 means that the
24213 				 * drive could not read the media (No
24214 				 * reference position found). In this case
24215 				 * to prevent a hang on the DKIOCSTATE IOCTL
24216 				 * we set the media state to DKIO_INSERTED.
24217 				 */
24218 				if (asc == 0x06 && ascq == 0x00)
24219 					state = DKIO_INSERTED;
24220 
24221 				/*
24222 				 * if 02/04/02  means that the host
24223 				 * should send start command. Explicitly
24224 				 * leave the media state as is
24225 				 * (inserted) as the media is inserted
24226 				 * and host has stopped device for PM
24227 				 * reasons. Upon next true read/write
24228 				 * to this media will bring the
24229 				 * device to the right state good for
24230 				 * media access.
24231 				 */
24232 				if (asc == 0x3a) {
24233 					state = DKIO_EJECTED;
24234 				} else {
24235 					/*
24236 					 * If the drive is busy with an
24237 					 * operation or long write, keep the
24238 					 * media in an inserted state.
24239 					 */
24240 
24241 					if ((asc == 0x04) &&
24242 					    ((ascq == 0x02) ||
24243 					    (ascq == 0x07) ||
24244 					    (ascq == 0x08))) {
24245 						state = DKIO_INSERTED;
24246 					}
24247 				}
24248 			} else if (skey == KEY_NO_SENSE) {
24249 				if ((asc == 0x00) && (ascq == 0x00)) {
24250 					/*
24251 					 * Sense Data 00/00/00 does not provide
24252 					 * any information about the state of
24253 					 * the media. Ignore it.
24254 					 */
24255 					mutex_exit(SD_MUTEX(un));
24256 					return (0);
24257 				}
24258 			}
24259 		}
24260 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
24261 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
24262 		state = DKIO_INSERTED;
24263 	}
24264 
24265 	SD_TRACE(SD_LOG_COMMON, un,
24266 	    "sd_media_watch_cb: state=%x, specified=%x\n",
24267 	    state, un->un_specified_mediastate);
24268 
24269 	/*
24270 	 * now signal the waiting thread if this is *not* the specified state;
24271 	 * delay the signal if the state is DKIO_INSERTED to allow the target
24272 	 * to recover
24273 	 */
24274 	if (state != un->un_specified_mediastate) {
24275 		un->un_mediastate = state;
24276 		if (state == DKIO_INSERTED) {
24277 			/*
24278 			 * delay the signal to give the drive a chance
24279 			 * to do what it apparently needs to do
24280 			 */
24281 			SD_TRACE(SD_LOG_COMMON, un,
24282 			    "sd_media_watch_cb: delayed cv_broadcast\n");
24283 			if (un->un_dcvb_timeid == NULL) {
24284 				un->un_dcvb_timeid =
24285 				    timeout(sd_delayed_cv_broadcast, un,
24286 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
24287 			}
24288 		} else {
24289 			SD_TRACE(SD_LOG_COMMON, un,
24290 			    "sd_media_watch_cb: immediate cv_broadcast\n");
24291 			cv_broadcast(&un->un_state_cv);
24292 		}
24293 	}
24294 	mutex_exit(SD_MUTEX(un));
24295 	return (0);
24296 }
24297 
24298 
24299 /*
24300  *    Function: sd_dkio_get_temp
24301  *
24302  * Description: This routine is the driver entry point for handling ioctl
24303  *		requests to get the disk temperature.
24304  *
24305  *   Arguments: dev  - the device number
24306  *		arg  - pointer to user provided dk_temperature structure.
24307  *		flag - this argument is a pass through to ddi_copyxxx()
24308  *		       directly from the mode argument of ioctl().
24309  *
24310  * Return Code: 0
24311  *		EFAULT
24312  *		ENXIO
24313  *		EAGAIN
24314  */
24315 
24316 static int
24317 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
24318 {
24319 	struct sd_lun		*un = NULL;
24320 	struct dk_temperature	*dktemp = NULL;
24321 	uchar_t			*temperature_page;
24322 	int			rval = 0;
24323 	int			path_flag = SD_PATH_STANDARD;
24324 	sd_ssc_t		*ssc;
24325 
24326 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24327 		return (ENXIO);
24328 	}
24329 
24330 	ssc = sd_ssc_init(un);
24331 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
24332 
24333 	/* copyin the disk temp argument to get the user flags */
24334 	if (ddi_copyin((void *)arg, dktemp,
24335 	    sizeof (struct dk_temperature), flag) != 0) {
24336 		rval = EFAULT;
24337 		goto done;
24338 	}
24339 
24340 	/* Initialize the temperature to invalid. */
24341 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24342 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24343 
24344 	/*
24345 	 * Note: Investigate removing the "bypass pm" semantic.
24346 	 * Can we just bypass PM always?
24347 	 */
24348 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
24349 		path_flag = SD_PATH_DIRECT;
24350 		ASSERT(!mutex_owned(&un->un_pm_mutex));
24351 		mutex_enter(&un->un_pm_mutex);
24352 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24353 			/*
24354 			 * If DKT_BYPASS_PM is set, and the drive happens to be
24355 			 * in low power mode, we can not wake it up, Need to
24356 			 * return EAGAIN.
24357 			 */
24358 			mutex_exit(&un->un_pm_mutex);
24359 			rval = EAGAIN;
24360 			goto done;
24361 		} else {
24362 			/*
24363 			 * Indicate to PM the device is busy. This is required
24364 			 * to avoid a race - i.e. the ioctl is issuing a
24365 			 * command and the pm framework brings down the device
24366 			 * to low power mode (possible power cut-off on some
24367 			 * platforms).
24368 			 */
24369 			mutex_exit(&un->un_pm_mutex);
24370 			if (sd_pm_entry(un) != DDI_SUCCESS) {
24371 				rval = EAGAIN;
24372 				goto done;
24373 			}
24374 		}
24375 	}
24376 
24377 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
24378 
24379 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
24380 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
24381 	if (rval != 0)
24382 		goto done2;
24383 
24384 	/*
24385 	 * For the current temperature verify that the parameter length is 0x02
24386 	 * and the parameter code is 0x00
24387 	 */
24388 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
24389 	    (temperature_page[5] == 0x00)) {
24390 		if (temperature_page[9] == 0xFF) {
24391 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24392 		} else {
24393 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
24394 		}
24395 	}
24396 
24397 	/*
24398 	 * For the reference temperature verify that the parameter
24399 	 * length is 0x02 and the parameter code is 0x01
24400 	 */
24401 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
24402 	    (temperature_page[11] == 0x01)) {
24403 		if (temperature_page[15] == 0xFF) {
24404 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24405 		} else {
24406 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
24407 		}
24408 	}
24409 
24410 	/* Do the copyout regardless of the temperature commands status. */
24411 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
24412 	    flag) != 0) {
24413 		rval = EFAULT;
24414 		goto done1;
24415 	}
24416 
24417 done2:
24418 	if (rval != 0) {
24419 		if (rval == EIO)
24420 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24421 		else
24422 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24423 	}
24424 done1:
24425 	if (path_flag == SD_PATH_DIRECT) {
24426 		sd_pm_exit(un);
24427 	}
24428 
24429 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
24430 done:
24431 	sd_ssc_fini(ssc);
24432 	if (dktemp != NULL) {
24433 		kmem_free(dktemp, sizeof (struct dk_temperature));
24434 	}
24435 
24436 	return (rval);
24437 }
24438 
24439 
24440 /*
24441  *    Function: sd_log_page_supported
24442  *
24443  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
24444  *		supported log pages.
24445  *
24446  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
24447  *                      structure for this target.
24448  *		log_page -
24449  *
24450  * Return Code: -1 - on error (log sense is optional and may not be supported).
24451  *		0  - log page not found.
24452  *		1  - log page found.
24453  */
24454 
24455 static int
24456 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
24457 {
24458 	uchar_t *log_page_data;
24459 	int	i;
24460 	int	match = 0;
24461 	int	log_size;
24462 	int	status = 0;
24463 	struct sd_lun	*un;
24464 
24465 	ASSERT(ssc != NULL);
24466 	un = ssc->ssc_un;
24467 	ASSERT(un != NULL);
24468 
24469 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
24470 
24471 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
24472 	    SD_PATH_DIRECT);
24473 
24474 	if (status != 0) {
24475 		if (status == EIO) {
24476 			/*
24477 			 * Some disks do not support log sense, we
24478 			 * should ignore this kind of error(sense key is
24479 			 * 0x5 - illegal request).
24480 			 */
24481 			uint8_t *sensep;
24482 			int senlen;
24483 
24484 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
24485 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
24486 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
24487 
24488 			if (senlen > 0 &&
24489 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
24490 				sd_ssc_assessment(ssc,
24491 				    SD_FMT_IGNORE_COMPROMISE);
24492 			} else {
24493 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24494 			}
24495 		} else {
24496 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24497 		}
24498 
24499 		SD_ERROR(SD_LOG_COMMON, un,
24500 		    "sd_log_page_supported: failed log page retrieval\n");
24501 		kmem_free(log_page_data, 0xFF);
24502 		return (-1);
24503 	}
24504 
24505 	log_size = log_page_data[3];
24506 
24507 	/*
24508 	 * The list of supported log pages start from the fourth byte. Check
24509 	 * until we run out of log pages or a match is found.
24510 	 */
24511 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
24512 		if (log_page_data[i] == log_page) {
24513 			match++;
24514 		}
24515 	}
24516 	kmem_free(log_page_data, 0xFF);
24517 	return (match);
24518 }
24519 
24520 
24521 /*
24522  *    Function: sd_mhdioc_failfast
24523  *
24524  * Description: This routine is the driver entry point for handling ioctl
24525  *		requests to enable/disable the multihost failfast option.
24526  *		(MHIOCENFAILFAST)
24527  *
24528  *   Arguments: dev	- the device number
24529  *		arg	- user specified probing interval.
24530  *		flag	- this argument is a pass through to ddi_copyxxx()
24531  *			  directly from the mode argument of ioctl().
24532  *
24533  * Return Code: 0
24534  *		EFAULT
24535  *		ENXIO
24536  */
24537 
24538 static int
24539 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
24540 {
24541 	struct sd_lun	*un = NULL;
24542 	int		mh_time;
24543 	int		rval = 0;
24544 
24545 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24546 		return (ENXIO);
24547 	}
24548 
24549 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
24550 		return (EFAULT);
24551 
24552 	if (mh_time) {
24553 		mutex_enter(SD_MUTEX(un));
24554 		un->un_resvd_status |= SD_FAILFAST;
24555 		mutex_exit(SD_MUTEX(un));
24556 		/*
24557 		 * If mh_time is INT_MAX, then this ioctl is being used for
24558 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
24559 		 */
24560 		if (mh_time != INT_MAX) {
24561 			rval = sd_check_mhd(dev, mh_time);
24562 		}
24563 	} else {
24564 		(void) sd_check_mhd(dev, 0);
24565 		mutex_enter(SD_MUTEX(un));
24566 		un->un_resvd_status &= ~SD_FAILFAST;
24567 		mutex_exit(SD_MUTEX(un));
24568 	}
24569 	return (rval);
24570 }
24571 
24572 
24573 /*
24574  *    Function: sd_mhdioc_takeown
24575  *
24576  * Description: This routine is the driver entry point for handling ioctl
24577  *		requests to forcefully acquire exclusive access rights to the
24578  *		multihost disk (MHIOCTKOWN).
24579  *
24580  *   Arguments: dev	- the device number
24581  *		arg	- user provided structure specifying the delay
24582  *			  parameters in milliseconds
24583  *		flag	- this argument is a pass through to ddi_copyxxx()
24584  *			  directly from the mode argument of ioctl().
24585  *
24586  * Return Code: 0
24587  *		EFAULT
24588  *		ENXIO
24589  */
24590 
24591 static int
24592 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
24593 {
24594 	struct sd_lun		*un = NULL;
24595 	struct mhioctkown	*tkown = NULL;
24596 	int			rval = 0;
24597 
24598 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24599 		return (ENXIO);
24600 	}
24601 
24602 	if (arg != NULL) {
24603 		tkown = (struct mhioctkown *)
24604 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
24605 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
24606 		if (rval != 0) {
24607 			rval = EFAULT;
24608 			goto error;
24609 		}
24610 	}
24611 
24612 	rval = sd_take_ownership(dev, tkown);
24613 	mutex_enter(SD_MUTEX(un));
24614 	if (rval == 0) {
24615 		un->un_resvd_status |= SD_RESERVE;
24616 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
24617 			sd_reinstate_resv_delay =
24618 			    tkown->reinstate_resv_delay * 1000;
24619 		} else {
24620 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
24621 		}
24622 		/*
24623 		 * Give the scsi_watch routine interval set by
24624 		 * the MHIOCENFAILFAST ioctl precedence here.
24625 		 */
24626 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
24627 			mutex_exit(SD_MUTEX(un));
24628 			(void) sd_check_mhd(dev,
24629 			    sd_reinstate_resv_delay / 1000);
24630 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
24631 			    "sd_mhdioc_takeown : %d\n",
24632 			    sd_reinstate_resv_delay);
24633 		} else {
24634 			mutex_exit(SD_MUTEX(un));
24635 		}
24636 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
24637 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24638 	} else {
24639 		un->un_resvd_status &= ~SD_RESERVE;
24640 		mutex_exit(SD_MUTEX(un));
24641 	}
24642 
24643 error:
24644 	if (tkown != NULL) {
24645 		kmem_free(tkown, sizeof (struct mhioctkown));
24646 	}
24647 	return (rval);
24648 }
24649 
24650 
24651 /*
24652  *    Function: sd_mhdioc_release
24653  *
24654  * Description: This routine is the driver entry point for handling ioctl
24655  *		requests to release exclusive access rights to the multihost
24656  *		disk (MHIOCRELEASE).
24657  *
24658  *   Arguments: dev	- the device number
24659  *
24660  * Return Code: 0
24661  *		ENXIO
24662  */
24663 
24664 static int
24665 sd_mhdioc_release(dev_t dev)
24666 {
24667 	struct sd_lun		*un = NULL;
24668 	timeout_id_t		resvd_timeid_save;
24669 	int			resvd_status_save;
24670 	int			rval = 0;
24671 
24672 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24673 		return (ENXIO);
24674 	}
24675 
24676 	mutex_enter(SD_MUTEX(un));
24677 	resvd_status_save = un->un_resvd_status;
24678 	un->un_resvd_status &=
24679 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
24680 	if (un->un_resvd_timeid) {
24681 		resvd_timeid_save = un->un_resvd_timeid;
24682 		un->un_resvd_timeid = NULL;
24683 		mutex_exit(SD_MUTEX(un));
24684 		(void) untimeout(resvd_timeid_save);
24685 	} else {
24686 		mutex_exit(SD_MUTEX(un));
24687 	}
24688 
24689 	/*
24690 	 * destroy any pending timeout thread that may be attempting to
24691 	 * reinstate reservation on this device.
24692 	 */
24693 	sd_rmv_resv_reclaim_req(dev);
24694 
24695 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
24696 		mutex_enter(SD_MUTEX(un));
24697 		if ((un->un_mhd_token) &&
24698 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
24699 			mutex_exit(SD_MUTEX(un));
24700 			(void) sd_check_mhd(dev, 0);
24701 		} else {
24702 			mutex_exit(SD_MUTEX(un));
24703 		}
24704 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
24705 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24706 	} else {
24707 		/*
24708 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
24709 		 */
24710 		mutex_enter(SD_MUTEX(un));
24711 		un->un_resvd_status = resvd_status_save;
24712 		mutex_exit(SD_MUTEX(un));
24713 	}
24714 	return (rval);
24715 }
24716 
24717 
24718 /*
24719  *    Function: sd_mhdioc_register_devid
24720  *
24721  * Description: This routine is the driver entry point for handling ioctl
24722  *		requests to register the device id (MHIOCREREGISTERDEVID).
24723  *
24724  *		Note: The implementation for this ioctl has been updated to
24725  *		be consistent with the original PSARC case (1999/357)
24726  *		(4375899, 4241671, 4220005)
24727  *
24728  *   Arguments: dev	- the device number
24729  *
24730  * Return Code: 0
24731  *		ENXIO
24732  */
24733 
24734 static int
24735 sd_mhdioc_register_devid(dev_t dev)
24736 {
24737 	struct sd_lun	*un = NULL;
24738 	int		rval = 0;
24739 	sd_ssc_t	*ssc;
24740 
24741 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24742 		return (ENXIO);
24743 	}
24744 
24745 	ASSERT(!mutex_owned(SD_MUTEX(un)));
24746 
24747 	mutex_enter(SD_MUTEX(un));
24748 
24749 	/* If a devid already exists, de-register it */
24750 	if (un->un_devid != NULL) {
24751 		ddi_devid_unregister(SD_DEVINFO(un));
24752 		/*
24753 		 * After unregister devid, needs to free devid memory
24754 		 */
24755 		ddi_devid_free(un->un_devid);
24756 		un->un_devid = NULL;
24757 	}
24758 
24759 	/* Check for reservation conflict */
24760 	mutex_exit(SD_MUTEX(un));
24761 	ssc = sd_ssc_init(un);
24762 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
24763 	mutex_enter(SD_MUTEX(un));
24764 
24765 	switch (rval) {
24766 	case 0:
24767 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
24768 		break;
24769 	case EACCES:
24770 		break;
24771 	default:
24772 		rval = EIO;
24773 	}
24774 
24775 	mutex_exit(SD_MUTEX(un));
24776 	if (rval != 0) {
24777 		if (rval == EIO)
24778 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24779 		else
24780 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24781 	}
24782 	sd_ssc_fini(ssc);
24783 	return (rval);
24784 }
24785 
24786 
24787 /*
24788  *    Function: sd_mhdioc_inkeys
24789  *
24790  * Description: This routine is the driver entry point for handling ioctl
24791  *		requests to issue the SCSI-3 Persistent In Read Keys command
24792  *		to the device (MHIOCGRP_INKEYS).
24793  *
24794  *   Arguments: dev	- the device number
24795  *		arg	- user provided in_keys structure
24796  *		flag	- this argument is a pass through to ddi_copyxxx()
24797  *			  directly from the mode argument of ioctl().
24798  *
24799  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
24800  *		ENXIO
24801  *		EFAULT
24802  */
24803 
24804 static int
24805 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
24806 {
24807 	struct sd_lun		*un;
24808 	mhioc_inkeys_t		inkeys;
24809 	int			rval = 0;
24810 
24811 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24812 		return (ENXIO);
24813 	}
24814 
24815 #ifdef _MULTI_DATAMODEL
24816 	switch (ddi_model_convert_from(flag & FMODELS)) {
24817 	case DDI_MODEL_ILP32: {
24818 		struct mhioc_inkeys32	inkeys32;
24819 
24820 		if (ddi_copyin(arg, &inkeys32,
24821 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
24822 			return (EFAULT);
24823 		}
24824 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
24825 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24826 		    &inkeys, flag)) != 0) {
24827 			return (rval);
24828 		}
24829 		inkeys32.generation = inkeys.generation;
24830 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
24831 		    flag) != 0) {
24832 			return (EFAULT);
24833 		}
24834 		break;
24835 	}
24836 	case DDI_MODEL_NONE:
24837 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
24838 		    flag) != 0) {
24839 			return (EFAULT);
24840 		}
24841 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24842 		    &inkeys, flag)) != 0) {
24843 			return (rval);
24844 		}
24845 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
24846 		    flag) != 0) {
24847 			return (EFAULT);
24848 		}
24849 		break;
24850 	}
24851 
24852 #else /* ! _MULTI_DATAMODEL */
24853 
24854 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
24855 		return (EFAULT);
24856 	}
24857 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
24858 	if (rval != 0) {
24859 		return (rval);
24860 	}
24861 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
24862 		return (EFAULT);
24863 	}
24864 
24865 #endif /* _MULTI_DATAMODEL */
24866 
24867 	return (rval);
24868 }
24869 
24870 
24871 /*
24872  *    Function: sd_mhdioc_inresv
24873  *
24874  * Description: This routine is the driver entry point for handling ioctl
24875  *		requests to issue the SCSI-3 Persistent In Read Reservations
24876  *		command to the device (MHIOCGRP_INKEYS).
24877  *
24878  *   Arguments: dev	- the device number
24879  *		arg	- user provided in_resv structure
24880  *		flag	- this argument is a pass through to ddi_copyxxx()
24881  *			  directly from the mode argument of ioctl().
24882  *
24883  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
24884  *		ENXIO
24885  *		EFAULT
24886  */
24887 
24888 static int
24889 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
24890 {
24891 	struct sd_lun		*un;
24892 	mhioc_inresvs_t		inresvs;
24893 	int			rval = 0;
24894 
24895 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24896 		return (ENXIO);
24897 	}
24898 
24899 #ifdef _MULTI_DATAMODEL
24900 
24901 	switch (ddi_model_convert_from(flag & FMODELS)) {
24902 	case DDI_MODEL_ILP32: {
24903 		struct mhioc_inresvs32	inresvs32;
24904 
24905 		if (ddi_copyin(arg, &inresvs32,
24906 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24907 			return (EFAULT);
24908 		}
24909 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
24910 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24911 		    &inresvs, flag)) != 0) {
24912 			return (rval);
24913 		}
24914 		inresvs32.generation = inresvs.generation;
24915 		if (ddi_copyout(&inresvs32, arg,
24916 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24917 			return (EFAULT);
24918 		}
24919 		break;
24920 	}
24921 	case DDI_MODEL_NONE:
24922 		if (ddi_copyin(arg, &inresvs,
24923 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24924 			return (EFAULT);
24925 		}
24926 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24927 		    &inresvs, flag)) != 0) {
24928 			return (rval);
24929 		}
24930 		if (ddi_copyout(&inresvs, arg,
24931 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24932 			return (EFAULT);
24933 		}
24934 		break;
24935 	}
24936 
24937 #else /* ! _MULTI_DATAMODEL */
24938 
24939 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
24940 		return (EFAULT);
24941 	}
24942 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
24943 	if (rval != 0) {
24944 		return (rval);
24945 	}
24946 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
24947 		return (EFAULT);
24948 	}
24949 
24950 #endif /* ! _MULTI_DATAMODEL */
24951 
24952 	return (rval);
24953 }
24954 
24955 
24956 /*
24957  * The following routines support the clustering functionality described below
24958  * and implement lost reservation reclaim functionality.
24959  *
24960  * Clustering
24961  * ----------
24962  * The clustering code uses two different, independent forms of SCSI
24963  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
24964  * Persistent Group Reservations. For any particular disk, it will use either
24965  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
24966  *
24967  * SCSI-2
24968  * The cluster software takes ownership of a multi-hosted disk by issuing the
24969  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
24970  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
24971  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
24972  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
24973  * driver. The meaning of failfast is that if the driver (on this host) ever
24974  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
24975  * it should immediately panic the host. The motivation for this ioctl is that
24976  * if this host does encounter reservation conflict, the underlying cause is
24977  * that some other host of the cluster has decided that this host is no longer
24978  * in the cluster and has seized control of the disks for itself. Since this
24979  * host is no longer in the cluster, it ought to panic itself. The
24980  * MHIOCENFAILFAST ioctl does two things:
24981  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
24982  *      error to panic the host
24983  *      (b) it sets up a periodic timer to test whether this host still has
24984  *      "access" (in that no other host has reserved the device):  if the
24985  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
24986  *      purpose of that periodic timer is to handle scenarios where the host is
24987  *      otherwise temporarily quiescent, temporarily doing no real i/o.
24988  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
24989  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
24990  * the device itself.
24991  *
24992  * SCSI-3 PGR
24993  * A direct semantic implementation of the SCSI-3 Persistent Reservation
24994  * facility is supported through the shared multihost disk ioctls
24995  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
24996  * MHIOCGRP_PREEMPTANDABORT, MHIOCGRP_CLEAR)
24997  *
24998  * Reservation Reclaim:
24999  * --------------------
25000  * To support the lost reservation reclaim operations this driver creates a
25001  * single thread to handle reinstating reservations on all devices that have
25002  * lost reservations sd_resv_reclaim_requests are logged for all devices that
25003  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
25004  * and the reservation reclaim thread loops through the requests to regain the
25005  * lost reservations.
25006  */
25007 
25008 /*
25009  *    Function: sd_check_mhd()
25010  *
25011  * Description: This function sets up and submits a scsi watch request or
25012  *		terminates an existing watch request. This routine is used in
25013  *		support of reservation reclaim.
25014  *
25015  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
25016  *			 among multiple watches that share the callback function
25017  *		interval - the number of microseconds specifying the watch
25018  *			   interval for issuing TEST UNIT READY commands. If
25019  *			   set to 0 the watch should be terminated. If the
25020  *			   interval is set to 0 and if the device is required
25021  *			   to hold reservation while disabling failfast, the
25022  *			   watch is restarted with an interval of
25023  *			   reinstate_resv_delay.
25024  *
25025  * Return Code: 0	   - Successful submit/terminate of scsi watch request
25026  *		ENXIO      - Indicates an invalid device was specified
25027  *		EAGAIN     - Unable to submit the scsi watch request
25028  */
25029 
25030 static int
25031 sd_check_mhd(dev_t dev, int interval)
25032 {
25033 	struct sd_lun	*un;
25034 	opaque_t	token;
25035 
25036 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25037 		return (ENXIO);
25038 	}
25039 
25040 	/* is this a watch termination request? */
25041 	if (interval == 0) {
25042 		mutex_enter(SD_MUTEX(un));
25043 		/* if there is an existing watch task then terminate it */
25044 		if (un->un_mhd_token) {
25045 			token = un->un_mhd_token;
25046 			un->un_mhd_token = NULL;
25047 			mutex_exit(SD_MUTEX(un));
25048 			(void) scsi_watch_request_terminate(token,
25049 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
25050 			mutex_enter(SD_MUTEX(un));
25051 		} else {
25052 			mutex_exit(SD_MUTEX(un));
25053 			/*
25054 			 * Note: If we return here we don't check for the
25055 			 * failfast case. This is the original legacy
25056 			 * implementation but perhaps we should be checking
25057 			 * the failfast case.
25058 			 */
25059 			return (0);
25060 		}
25061 		/*
25062 		 * If the device is required to hold reservation while
25063 		 * disabling failfast, we need to restart the scsi_watch
25064 		 * routine with an interval of reinstate_resv_delay.
25065 		 */
25066 		if (un->un_resvd_status & SD_RESERVE) {
25067 			interval = sd_reinstate_resv_delay / 1000;
25068 		} else {
25069 			/* no failfast so bail */
25070 			mutex_exit(SD_MUTEX(un));
25071 			return (0);
25072 		}
25073 		mutex_exit(SD_MUTEX(un));
25074 	}
25075 
25076 	/*
25077 	 * adjust minimum time interval to 1 second,
25078 	 * and convert from msecs to usecs
25079 	 */
25080 	if (interval > 0 && interval < 1000) {
25081 		interval = 1000;
25082 	}
25083 	interval *= 1000;
25084 
25085 	/*
25086 	 * submit the request to the scsi_watch service
25087 	 */
25088 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
25089 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
25090 	if (token == NULL) {
25091 		return (EAGAIN);
25092 	}
25093 
25094 	/*
25095 	 * save token for termination later on
25096 	 */
25097 	mutex_enter(SD_MUTEX(un));
25098 	un->un_mhd_token = token;
25099 	mutex_exit(SD_MUTEX(un));
25100 	return (0);
25101 }
25102 
25103 
25104 /*
25105  *    Function: sd_mhd_watch_cb()
25106  *
25107  * Description: This function is the call back function used by the scsi watch
25108  *		facility. The scsi watch facility sends the "Test Unit Ready"
25109  *		and processes the status. If applicable (i.e. a "Unit Attention"
25110  *		status and automatic "Request Sense" not used) the scsi watch
25111  *		facility will send a "Request Sense" and retrieve the sense data
25112  *		to be passed to this callback function. In either case the
25113  *		automatic "Request Sense" or the facility submitting one, this
25114  *		callback is passed the status and sense data.
25115  *
25116  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25117  *			among multiple watches that share this callback function
25118  *		resultp - scsi watch facility result packet containing scsi
25119  *			  packet, status byte and sense data
25120  *
25121  * Return Code: 0 - continue the watch task
25122  *		non-zero - terminate the watch task
25123  */
25124 
25125 static int
25126 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
25127 {
25128 	struct sd_lun			*un;
25129 	struct scsi_status		*statusp;
25130 	uint8_t				*sensep;
25131 	struct scsi_pkt			*pkt;
25132 	uchar_t				actual_sense_length;
25133 	dev_t				dev = (dev_t)arg;
25134 
25135 	ASSERT(resultp != NULL);
25136 	statusp			= resultp->statusp;
25137 	sensep			= (uint8_t *)resultp->sensep;
25138 	pkt			= resultp->pkt;
25139 	actual_sense_length	= resultp->actual_sense_length;
25140 
25141 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25142 		return (ENXIO);
25143 	}
25144 
25145 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25146 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
25147 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
25148 
25149 	/* Begin processing of the status and/or sense data */
25150 	if (pkt->pkt_reason != CMD_CMPLT) {
25151 		/* Handle the incomplete packet */
25152 		sd_mhd_watch_incomplete(un, pkt);
25153 		return (0);
25154 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
25155 		if (*((unsigned char *)statusp)
25156 		    == STATUS_RESERVATION_CONFLICT) {
25157 			/*
25158 			 * Handle a reservation conflict by panicking if
25159 			 * configured for failfast or by logging the conflict
25160 			 * and updating the reservation status
25161 			 */
25162 			mutex_enter(SD_MUTEX(un));
25163 			if ((un->un_resvd_status & SD_FAILFAST) &&
25164 			    (sd_failfast_enable)) {
25165 				sd_panic_for_res_conflict(un);
25166 				/*NOTREACHED*/
25167 			}
25168 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25169 			    "sd_mhd_watch_cb: Reservation Conflict\n");
25170 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
25171 			mutex_exit(SD_MUTEX(un));
25172 		}
25173 	}
25174 
25175 	if (sensep != NULL) {
25176 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
25177 			mutex_enter(SD_MUTEX(un));
25178 			if ((scsi_sense_asc(sensep) ==
25179 			    SD_SCSI_RESET_SENSE_CODE) &&
25180 			    (un->un_resvd_status & SD_RESERVE)) {
25181 				/*
25182 				 * The additional sense code indicates a power
25183 				 * on or bus device reset has occurred; update
25184 				 * the reservation status.
25185 				 */
25186 				un->un_resvd_status |=
25187 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25188 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25189 				    "sd_mhd_watch_cb: Lost Reservation\n");
25190 			}
25191 		} else {
25192 			return (0);
25193 		}
25194 	} else {
25195 		mutex_enter(SD_MUTEX(un));
25196 	}
25197 
25198 	if ((un->un_resvd_status & SD_RESERVE) &&
25199 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
25200 		if (un->un_resvd_status & SD_WANT_RESERVE) {
25201 			/*
25202 			 * A reset occurred in between the last probe and this
25203 			 * one so if a timeout is pending cancel it.
25204 			 */
25205 			if (un->un_resvd_timeid) {
25206 				timeout_id_t temp_id = un->un_resvd_timeid;
25207 				un->un_resvd_timeid = NULL;
25208 				mutex_exit(SD_MUTEX(un));
25209 				(void) untimeout(temp_id);
25210 				mutex_enter(SD_MUTEX(un));
25211 			}
25212 			un->un_resvd_status &= ~SD_WANT_RESERVE;
25213 		}
25214 		if (un->un_resvd_timeid == 0) {
25215 			/* Schedule a timeout to handle the lost reservation */
25216 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
25217 			    (void *)dev,
25218 			    drv_usectohz(sd_reinstate_resv_delay));
25219 		}
25220 	}
25221 	mutex_exit(SD_MUTEX(un));
25222 	return (0);
25223 }
25224 
25225 
25226 /*
25227  *    Function: sd_mhd_watch_incomplete()
25228  *
25229  * Description: This function is used to find out why a scsi pkt sent by the
25230  *		scsi watch facility was not completed. Under some scenarios this
25231  *		routine will return. Otherwise it will send a bus reset to see
25232  *		if the drive is still online.
25233  *
25234  *   Arguments: un  - driver soft state (unit) structure
25235  *		pkt - incomplete scsi pkt
25236  */
25237 
25238 static void
25239 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
25240 {
25241 	int	be_chatty;
25242 	int	perr;
25243 
25244 	ASSERT(pkt != NULL);
25245 	ASSERT(un != NULL);
25246 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
25247 	perr		= (pkt->pkt_statistics & STAT_PERR);
25248 
25249 	mutex_enter(SD_MUTEX(un));
25250 	if (un->un_state == SD_STATE_DUMPING) {
25251 		mutex_exit(SD_MUTEX(un));
25252 		return;
25253 	}
25254 
25255 	switch (pkt->pkt_reason) {
25256 	case CMD_UNX_BUS_FREE:
25257 		/*
25258 		 * If we had a parity error that caused the target to drop BSY*,
25259 		 * don't be chatty about it.
25260 		 */
25261 		if (perr && be_chatty) {
25262 			be_chatty = 0;
25263 		}
25264 		break;
25265 	case CMD_TAG_REJECT:
25266 		/*
25267 		 * The SCSI-2 spec states that a tag reject will be sent by the
25268 		 * target if tagged queuing is not supported. A tag reject may
25269 		 * also be sent during certain initialization periods or to
25270 		 * control internal resources. For the latter case the target
25271 		 * may also return Queue Full.
25272 		 *
25273 		 * If this driver receives a tag reject from a target that is
25274 		 * going through an init period or controlling internal
25275 		 * resources tagged queuing will be disabled. This is a less
25276 		 * than optimal behavior but the driver is unable to determine
25277 		 * the target state and assumes tagged queueing is not supported
25278 		 */
25279 		pkt->pkt_flags = 0;
25280 		un->un_tagflags = 0;
25281 
25282 		if (un->un_f_opt_queueing == TRUE) {
25283 			un->un_throttle = min(un->un_throttle, 3);
25284 		} else {
25285 			un->un_throttle = 1;
25286 		}
25287 		mutex_exit(SD_MUTEX(un));
25288 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
25289 		mutex_enter(SD_MUTEX(un));
25290 		break;
25291 	case CMD_INCOMPLETE:
25292 		/*
25293 		 * The transport stopped with an abnormal state, fallthrough and
25294 		 * reset the target and/or bus unless selection did not complete
25295 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
25296 		 * go through a target/bus reset
25297 		 */
25298 		if (pkt->pkt_state == STATE_GOT_BUS) {
25299 			break;
25300 		}
25301 		/*FALLTHROUGH*/
25302 
25303 	case CMD_TIMEOUT:
25304 	default:
25305 		/*
25306 		 * The lun may still be running the command, so a lun reset
25307 		 * should be attempted. If the lun reset fails or cannot be
25308 		 * issued, than try a target reset. Lastly try a bus reset.
25309 		 */
25310 		if ((pkt->pkt_statistics &
25311 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0) {
25312 			int reset_retval = 0;
25313 			mutex_exit(SD_MUTEX(un));
25314 			if (un->un_f_allow_bus_device_reset == TRUE) {
25315 				if (un->un_f_lun_reset_enabled == TRUE) {
25316 					reset_retval =
25317 					    scsi_reset(SD_ADDRESS(un),
25318 					    RESET_LUN);
25319 				}
25320 				if (reset_retval == 0) {
25321 					reset_retval =
25322 					    scsi_reset(SD_ADDRESS(un),
25323 					    RESET_TARGET);
25324 				}
25325 			}
25326 			if (reset_retval == 0) {
25327 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
25328 			}
25329 			mutex_enter(SD_MUTEX(un));
25330 		}
25331 		break;
25332 	}
25333 
25334 	/* A device/bus reset has occurred; update the reservation status. */
25335 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
25336 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
25337 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25338 			un->un_resvd_status |=
25339 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25340 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25341 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
25342 		}
25343 	}
25344 
25345 	/*
25346 	 * The disk has been turned off; Update the device state.
25347 	 *
25348 	 * Note: Should we be offlining the disk here?
25349 	 */
25350 	if (pkt->pkt_state == STATE_GOT_BUS) {
25351 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
25352 		    "Disk not responding to selection\n");
25353 		if (un->un_state != SD_STATE_OFFLINE) {
25354 			New_state(un, SD_STATE_OFFLINE);
25355 		}
25356 	} else if (be_chatty) {
25357 		/*
25358 		 * suppress messages if they are all the same pkt reason;
25359 		 * with TQ, many (up to 256) are returned with the same
25360 		 * pkt_reason
25361 		 */
25362 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
25363 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25364 			    "sd_mhd_watch_incomplete: "
25365 			    "SCSI transport failed: reason '%s'\n",
25366 			    scsi_rname(pkt->pkt_reason));
25367 		}
25368 	}
25369 	un->un_last_pkt_reason = pkt->pkt_reason;
25370 	mutex_exit(SD_MUTEX(un));
25371 }
25372 
25373 
25374 /*
25375  *    Function: sd_sname()
25376  *
25377  * Description: This is a simple little routine to return a string containing
25378  *		a printable description of command status byte for use in
25379  *		logging.
25380  *
25381  *   Arguments: status - pointer to a status byte
25382  *
25383  * Return Code: char * - string containing status description.
25384  */
25385 
25386 static char *
25387 sd_sname(uchar_t status)
25388 {
25389 	switch (status & STATUS_MASK) {
25390 	case STATUS_GOOD:
25391 		return ("good status");
25392 	case STATUS_CHECK:
25393 		return ("check condition");
25394 	case STATUS_MET:
25395 		return ("condition met");
25396 	case STATUS_BUSY:
25397 		return ("busy");
25398 	case STATUS_INTERMEDIATE:
25399 		return ("intermediate");
25400 	case STATUS_INTERMEDIATE_MET:
25401 		return ("intermediate - condition met");
25402 	case STATUS_RESERVATION_CONFLICT:
25403 		return ("reservation_conflict");
25404 	case STATUS_TERMINATED:
25405 		return ("command terminated");
25406 	case STATUS_QFULL:
25407 		return ("queue full");
25408 	default:
25409 		return ("<unknown status>");
25410 	}
25411 }
25412 
25413 
25414 /*
25415  *    Function: sd_mhd_resvd_recover()
25416  *
25417  * Description: This function adds a reservation entry to the
25418  *		sd_resv_reclaim_request list and signals the reservation
25419  *		reclaim thread that there is work pending. If the reservation
25420  *		reclaim thread has not been previously created this function
25421  *		will kick it off.
25422  *
25423  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25424  *			among multiple watches that share this callback function
25425  *
25426  *     Context: This routine is called by timeout() and is run in interrupt
25427  *		context. It must not sleep or call other functions which may
25428  *		sleep.
25429  */
25430 
25431 static void
25432 sd_mhd_resvd_recover(void *arg)
25433 {
25434 	dev_t			dev = (dev_t)arg;
25435 	struct sd_lun		*un;
25436 	struct sd_thr_request	*sd_treq = NULL;
25437 	struct sd_thr_request	*sd_cur = NULL;
25438 	struct sd_thr_request	*sd_prev = NULL;
25439 	int			already_there = 0;
25440 
25441 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25442 		return;
25443 	}
25444 
25445 	mutex_enter(SD_MUTEX(un));
25446 	un->un_resvd_timeid = NULL;
25447 	if (un->un_resvd_status & SD_WANT_RESERVE) {
25448 		/*
25449 		 * There was a reset so don't issue the reserve, allow the
25450 		 * sd_mhd_watch_cb callback function to notice this and
25451 		 * reschedule the timeout for reservation.
25452 		 */
25453 		mutex_exit(SD_MUTEX(un));
25454 		return;
25455 	}
25456 	mutex_exit(SD_MUTEX(un));
25457 
25458 	/*
25459 	 * Add this device to the sd_resv_reclaim_request list and the
25460 	 * sd_resv_reclaim_thread should take care of the rest.
25461 	 *
25462 	 * Note: We can't sleep in this context so if the memory allocation
25463 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
25464 	 * reschedule the timeout for reservation.  (4378460)
25465 	 */
25466 	sd_treq = (struct sd_thr_request *)
25467 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
25468 	if (sd_treq == NULL) {
25469 		return;
25470 	}
25471 
25472 	sd_treq->sd_thr_req_next = NULL;
25473 	sd_treq->dev = dev;
25474 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25475 	if (sd_tr.srq_thr_req_head == NULL) {
25476 		sd_tr.srq_thr_req_head = sd_treq;
25477 	} else {
25478 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
25479 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
25480 			if (sd_cur->dev == dev) {
25481 				/*
25482 				 * already in Queue so don't log
25483 				 * another request for the device
25484 				 */
25485 				already_there = 1;
25486 				break;
25487 			}
25488 			sd_prev = sd_cur;
25489 		}
25490 		if (!already_there) {
25491 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
25492 			    "logging request for %lx\n", dev);
25493 			sd_prev->sd_thr_req_next = sd_treq;
25494 		} else {
25495 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
25496 		}
25497 	}
25498 
25499 	/*
25500 	 * Create a kernel thread to do the reservation reclaim and free up this
25501 	 * thread. We cannot block this thread while we go away to do the
25502 	 * reservation reclaim
25503 	 */
25504 	if (sd_tr.srq_resv_reclaim_thread == NULL)
25505 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
25506 		    sd_resv_reclaim_thread, NULL,
25507 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
25508 
25509 	/* Tell the reservation reclaim thread that it has work to do */
25510 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
25511 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25512 }
25513 
25514 /*
25515  *    Function: sd_resv_reclaim_thread()
25516  *
25517  * Description: This function implements the reservation reclaim operations
25518  *
25519  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
25520  *		      among multiple watches that share this callback function
25521  */
25522 
25523 static void
25524 sd_resv_reclaim_thread()
25525 {
25526 	struct sd_lun		*un;
25527 	struct sd_thr_request	*sd_mhreq;
25528 
25529 	/* Wait for work */
25530 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25531 	if (sd_tr.srq_thr_req_head == NULL) {
25532 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
25533 		    &sd_tr.srq_resv_reclaim_mutex);
25534 	}
25535 
25536 	/* Loop while we have work */
25537 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
25538 		un = ddi_get_soft_state(sd_state,
25539 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
25540 		if (un == NULL) {
25541 			/*
25542 			 * softstate structure is NULL so just
25543 			 * dequeue the request and continue
25544 			 */
25545 			sd_tr.srq_thr_req_head =
25546 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25547 			kmem_free(sd_tr.srq_thr_cur_req,
25548 			    sizeof (struct sd_thr_request));
25549 			continue;
25550 		}
25551 
25552 		/* dequeue the request */
25553 		sd_mhreq = sd_tr.srq_thr_cur_req;
25554 		sd_tr.srq_thr_req_head =
25555 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25556 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25557 
25558 		/*
25559 		 * Reclaim reservation only if SD_RESERVE is still set. There
25560 		 * may have been a call to MHIOCRELEASE before we got here.
25561 		 */
25562 		mutex_enter(SD_MUTEX(un));
25563 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25564 			/*
25565 			 * Note: The SD_LOST_RESERVE flag is cleared before
25566 			 * reclaiming the reservation. If this is done after the
25567 			 * call to sd_reserve_release a reservation loss in the
25568 			 * window between pkt completion of reserve cmd and
25569 			 * mutex_enter below may not be recognized
25570 			 */
25571 			un->un_resvd_status &= ~SD_LOST_RESERVE;
25572 			mutex_exit(SD_MUTEX(un));
25573 
25574 			if (sd_reserve_release(sd_mhreq->dev,
25575 			    SD_RESERVE) == 0) {
25576 				mutex_enter(SD_MUTEX(un));
25577 				un->un_resvd_status |= SD_RESERVE;
25578 				mutex_exit(SD_MUTEX(un));
25579 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25580 				    "sd_resv_reclaim_thread: "
25581 				    "Reservation Recovered\n");
25582 			} else {
25583 				mutex_enter(SD_MUTEX(un));
25584 				un->un_resvd_status |= SD_LOST_RESERVE;
25585 				mutex_exit(SD_MUTEX(un));
25586 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25587 				    "sd_resv_reclaim_thread: Failed "
25588 				    "Reservation Recovery\n");
25589 			}
25590 		} else {
25591 			mutex_exit(SD_MUTEX(un));
25592 		}
25593 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25594 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
25595 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25596 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
25597 		/*
25598 		 * wakeup the destroy thread if anyone is waiting on
25599 		 * us to complete.
25600 		 */
25601 		cv_signal(&sd_tr.srq_inprocess_cv);
25602 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
25603 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
25604 	}
25605 
25606 	/*
25607 	 * cleanup the sd_tr structure now that this thread will not exist
25608 	 */
25609 	ASSERT(sd_tr.srq_thr_req_head == NULL);
25610 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
25611 	sd_tr.srq_resv_reclaim_thread = NULL;
25612 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25613 	thread_exit();
25614 }
25615 
25616 
25617 /*
25618  *    Function: sd_rmv_resv_reclaim_req()
25619  *
25620  * Description: This function removes any pending reservation reclaim requests
25621  *		for the specified device.
25622  *
25623  *   Arguments: dev - the device 'dev_t'
25624  */
25625 
25626 static void
25627 sd_rmv_resv_reclaim_req(dev_t dev)
25628 {
25629 	struct sd_thr_request *sd_mhreq;
25630 	struct sd_thr_request *sd_prev;
25631 
25632 	/* Remove a reservation reclaim request from the list */
25633 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25634 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
25635 		/*
25636 		 * We are attempting to reinstate reservation for
25637 		 * this device. We wait for sd_reserve_release()
25638 		 * to return before we return.
25639 		 */
25640 		cv_wait(&sd_tr.srq_inprocess_cv,
25641 		    &sd_tr.srq_resv_reclaim_mutex);
25642 	} else {
25643 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
25644 		if (sd_mhreq && sd_mhreq->dev == dev) {
25645 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
25646 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25647 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25648 			return;
25649 		}
25650 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
25651 			if (sd_mhreq && sd_mhreq->dev == dev) {
25652 				break;
25653 			}
25654 			sd_prev = sd_mhreq;
25655 		}
25656 		if (sd_mhreq != NULL) {
25657 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
25658 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25659 		}
25660 	}
25661 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25662 }
25663 
25664 
25665 /*
25666  *    Function: sd_mhd_reset_notify_cb()
25667  *
25668  * Description: This is a call back function for scsi_reset_notify. This
25669  *		function updates the softstate reserved status and logs the
25670  *		reset. The driver scsi watch facility callback function
25671  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
25672  *		will reclaim the reservation.
25673  *
25674  *   Arguments: arg  - driver soft state (unit) structure
25675  */
25676 
25677 static void
25678 sd_mhd_reset_notify_cb(caddr_t arg)
25679 {
25680 	struct sd_lun *un = (struct sd_lun *)arg;
25681 
25682 	mutex_enter(SD_MUTEX(un));
25683 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25684 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
25685 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25686 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
25687 	}
25688 	mutex_exit(SD_MUTEX(un));
25689 }
25690 
25691 
25692 /*
25693  *    Function: sd_take_ownership()
25694  *
25695  * Description: This routine implements an algorithm to achieve a stable
25696  *		reservation on disks which don't implement priority reserve,
25697  *		and makes sure that other host lose re-reservation attempts.
25698  *		This algorithm contains of a loop that keeps issuing the RESERVE
25699  *		for some period of time (min_ownership_delay, default 6 seconds)
25700  *		During that loop, it looks to see if there has been a bus device
25701  *		reset or bus reset (both of which cause an existing reservation
25702  *		to be lost). If the reservation is lost issue RESERVE until a
25703  *		period of min_ownership_delay with no resets has gone by, or
25704  *		until max_ownership_delay has expired. This loop ensures that
25705  *		the host really did manage to reserve the device, in spite of
25706  *		resets. The looping for min_ownership_delay (default six
25707  *		seconds) is important to early generation clustering products,
25708  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
25709  *		MHIOCENFAILFAST periodic timer of two seconds. By having
25710  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
25711  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
25712  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
25713  *		have already noticed, via the MHIOCENFAILFAST polling, that it
25714  *		no longer "owns" the disk and will have panicked itself.  Thus,
25715  *		the host issuing the MHIOCTKOWN is assured (with timing
25716  *		dependencies) that by the time it actually starts to use the
25717  *		disk for real work, the old owner is no longer accessing it.
25718  *
25719  *		min_ownership_delay is the minimum amount of time for which the
25720  *		disk must be reserved continuously devoid of resets before the
25721  *		MHIOCTKOWN ioctl will return success.
25722  *
25723  *		max_ownership_delay indicates the amount of time by which the
25724  *		take ownership should succeed or timeout with an error.
25725  *
25726  *   Arguments: dev - the device 'dev_t'
25727  *		*p  - struct containing timing info.
25728  *
25729  * Return Code: 0 for success or error code
25730  */
25731 
25732 static int
25733 sd_take_ownership(dev_t dev, struct mhioctkown *p)
25734 {
25735 	struct sd_lun	*un;
25736 	int		rval;
25737 	int		err;
25738 	int		reservation_count   = 0;
25739 	int		min_ownership_delay =  6000000; /* in usec */
25740 	int		max_ownership_delay = 30000000; /* in usec */
25741 	clock_t		start_time;	/* starting time of this algorithm */
25742 	clock_t		end_time;	/* time limit for giving up */
25743 	clock_t		ownership_time;	/* time limit for stable ownership */
25744 	clock_t		current_time;
25745 	clock_t		previous_current_time;
25746 
25747 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25748 		return (ENXIO);
25749 	}
25750 
25751 	/*
25752 	 * Attempt a device reservation. A priority reservation is requested.
25753 	 */
25754 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
25755 	    != SD_SUCCESS) {
25756 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25757 		    "sd_take_ownership: return(1)=%d\n", rval);
25758 		return (rval);
25759 	}
25760 
25761 	/* Update the softstate reserved status to indicate the reservation */
25762 	mutex_enter(SD_MUTEX(un));
25763 	un->un_resvd_status |= SD_RESERVE;
25764 	un->un_resvd_status &=
25765 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
25766 	mutex_exit(SD_MUTEX(un));
25767 
25768 	if (p != NULL) {
25769 		if (p->min_ownership_delay != 0) {
25770 			min_ownership_delay = p->min_ownership_delay * 1000;
25771 		}
25772 		if (p->max_ownership_delay != 0) {
25773 			max_ownership_delay = p->max_ownership_delay * 1000;
25774 		}
25775 	}
25776 	SD_INFO(SD_LOG_IOCTL_MHD, un,
25777 	    "sd_take_ownership: min, max delays: %d, %d\n",
25778 	    min_ownership_delay, max_ownership_delay);
25779 
25780 	start_time = ddi_get_lbolt();
25781 	current_time	= start_time;
25782 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
25783 	end_time	= start_time + drv_usectohz(max_ownership_delay);
25784 
25785 	while (current_time - end_time < 0) {
25786 		delay(drv_usectohz(500000));
25787 
25788 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
25789 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
25790 				mutex_enter(SD_MUTEX(un));
25791 				rval = (un->un_resvd_status &
25792 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
25793 				mutex_exit(SD_MUTEX(un));
25794 				break;
25795 			}
25796 		}
25797 		previous_current_time = current_time;
25798 		current_time = ddi_get_lbolt();
25799 		mutex_enter(SD_MUTEX(un));
25800 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
25801 			ownership_time = ddi_get_lbolt() +
25802 			    drv_usectohz(min_ownership_delay);
25803 			reservation_count = 0;
25804 		} else {
25805 			reservation_count++;
25806 		}
25807 		un->un_resvd_status |= SD_RESERVE;
25808 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
25809 		mutex_exit(SD_MUTEX(un));
25810 
25811 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25812 		    "sd_take_ownership: ticks for loop iteration=%ld, "
25813 		    "reservation=%s\n", (current_time - previous_current_time),
25814 		    reservation_count ? "ok" : "reclaimed");
25815 
25816 		if (current_time - ownership_time >= 0 &&
25817 		    reservation_count >= 4) {
25818 			rval = 0; /* Achieved a stable ownership */
25819 			break;
25820 		}
25821 		if (current_time - end_time >= 0) {
25822 			rval = EACCES; /* No ownership in max possible time */
25823 			break;
25824 		}
25825 	}
25826 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25827 	    "sd_take_ownership: return(2)=%d\n", rval);
25828 	return (rval);
25829 }
25830 
25831 
25832 /*
25833  *    Function: sd_reserve_release()
25834  *
25835  * Description: This function builds and sends scsi RESERVE, RELEASE, and
25836  *		PRIORITY RESERVE commands based on a user specified command type
25837  *
25838  *   Arguments: dev - the device 'dev_t'
25839  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
25840  *		      SD_RESERVE, SD_RELEASE
25841  *
25842  * Return Code: 0 or Error Code
25843  */
25844 
25845 static int
25846 sd_reserve_release(dev_t dev, int cmd)
25847 {
25848 	struct uscsi_cmd	*com = NULL;
25849 	struct sd_lun		*un = NULL;
25850 	char			cdb[CDB_GROUP0];
25851 	int			rval;
25852 
25853 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
25854 	    (cmd == SD_PRIORITY_RESERVE));
25855 
25856 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25857 		return (ENXIO);
25858 	}
25859 
25860 	/* instantiate and initialize the command and cdb */
25861 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25862 	bzero(cdb, CDB_GROUP0);
25863 	com->uscsi_flags   = USCSI_SILENT;
25864 	com->uscsi_timeout = un->un_reserve_release_time;
25865 	com->uscsi_cdblen  = CDB_GROUP0;
25866 	com->uscsi_cdb	   = cdb;
25867 	if (cmd == SD_RELEASE) {
25868 		cdb[0] = SCMD_RELEASE;
25869 	} else {
25870 		cdb[0] = SCMD_RESERVE;
25871 	}
25872 
25873 	/* Send the command. */
25874 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25875 	    SD_PATH_STANDARD);
25876 
25877 	/*
25878 	 * "break" a reservation that is held by another host, by issuing a
25879 	 * reset if priority reserve is desired, and we could not get the
25880 	 * device.
25881 	 */
25882 	if ((cmd == SD_PRIORITY_RESERVE) &&
25883 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25884 		/*
25885 		 * First try to reset the LUN. If we cannot, then try a target
25886 		 * reset, followed by a bus reset if the target reset fails.
25887 		 */
25888 		int reset_retval = 0;
25889 		if (un->un_f_lun_reset_enabled == TRUE) {
25890 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
25891 		}
25892 		if (reset_retval == 0) {
25893 			/* The LUN reset either failed or was not issued */
25894 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
25895 		}
25896 		if ((reset_retval == 0) &&
25897 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
25898 			rval = EIO;
25899 			kmem_free(com, sizeof (*com));
25900 			return (rval);
25901 		}
25902 
25903 		bzero(com, sizeof (struct uscsi_cmd));
25904 		com->uscsi_flags   = USCSI_SILENT;
25905 		com->uscsi_cdb	   = cdb;
25906 		com->uscsi_cdblen  = CDB_GROUP0;
25907 		com->uscsi_timeout = 5;
25908 
25909 		/*
25910 		 * Reissue the last reserve command, this time without request
25911 		 * sense.  Assume that it is just a regular reserve command.
25912 		 */
25913 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25914 		    SD_PATH_STANDARD);
25915 	}
25916 
25917 	/* Return an error if still getting a reservation conflict. */
25918 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25919 		rval = EACCES;
25920 	}
25921 
25922 	kmem_free(com, sizeof (*com));
25923 	return (rval);
25924 }
25925 
25926 
25927 #define	SD_NDUMP_RETRIES	12
25928 /*
25929  *	System Crash Dump routine
25930  */
25931 
25932 static int
25933 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
25934 {
25935 	int		instance;
25936 	int		partition;
25937 	int		i;
25938 	int		err;
25939 	struct sd_lun	*un;
25940 	struct scsi_pkt *wr_pktp;
25941 	struct buf	*wr_bp;
25942 	struct buf	wr_buf;
25943 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
25944 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
25945 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
25946 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
25947 	size_t		io_start_offset;
25948 	int		doing_rmw = FALSE;
25949 	int		rval;
25950 	ssize_t		dma_resid;
25951 	daddr_t		oblkno;
25952 	diskaddr_t	nblks = 0;
25953 	diskaddr_t	start_block;
25954 
25955 	instance = SDUNIT(dev);
25956 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
25957 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
25958 		return (ENXIO);
25959 	}
25960 
25961 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
25962 
25963 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
25964 
25965 	partition = SDPART(dev);
25966 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
25967 
25968 	if (!(NOT_DEVBSIZE(un))) {
25969 		int secmask = 0;
25970 		int blknomask = 0;
25971 
25972 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
25973 		secmask = un->un_tgt_blocksize - 1;
25974 
25975 		if (blkno & blknomask) {
25976 			SD_TRACE(SD_LOG_DUMP, un,
25977 			    "sddump: dump start block not modulo %d\n",
25978 			    un->un_tgt_blocksize);
25979 			return (EINVAL);
25980 		}
25981 
25982 		if ((nblk * DEV_BSIZE) & secmask) {
25983 			SD_TRACE(SD_LOG_DUMP, un,
25984 			    "sddump: dump length not modulo %d\n",
25985 			    un->un_tgt_blocksize);
25986 			return (EINVAL);
25987 		}
25988 
25989 	}
25990 
25991 	/* Validate blocks to dump at against partition size. */
25992 
25993 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
25994 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
25995 
25996 	if (NOT_DEVBSIZE(un)) {
25997 		if ((blkno + nblk) > nblks) {
25998 			SD_TRACE(SD_LOG_DUMP, un,
25999 			    "sddump: dump range larger than partition: "
26000 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
26001 			    blkno, nblk, nblks);
26002 			return (EINVAL);
26003 		}
26004 	} else {
26005 		if (((blkno / (un->un_tgt_blocksize / DEV_BSIZE)) +
26006 		    (nblk / (un->un_tgt_blocksize / DEV_BSIZE))) > nblks) {
26007 			SD_TRACE(SD_LOG_DUMP, un,
26008 			    "sddump: dump range larger than partition: "
26009 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
26010 			    blkno, nblk, nblks);
26011 			return (EINVAL);
26012 		}
26013 	}
26014 
26015 	mutex_enter(&un->un_pm_mutex);
26016 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
26017 		struct scsi_pkt *start_pktp;
26018 
26019 		mutex_exit(&un->un_pm_mutex);
26020 
26021 		/*
26022 		 * use pm framework to power on HBA 1st
26023 		 */
26024 		(void) pm_raise_power(SD_DEVINFO(un), 0,
26025 		    SD_PM_STATE_ACTIVE(un));
26026 
26027 		/*
26028 		 * Dump no long uses sdpower to power on a device, it's
26029 		 * in-line here so it can be done in polled mode.
26030 		 */
26031 
26032 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
26033 
26034 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
26035 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
26036 
26037 		if (start_pktp == NULL) {
26038 			/* We were not given a SCSI packet, fail. */
26039 			return (EIO);
26040 		}
26041 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
26042 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
26043 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
26044 		start_pktp->pkt_flags = FLAG_NOINTR;
26045 
26046 		mutex_enter(SD_MUTEX(un));
26047 		SD_FILL_SCSI1_LUN(un, start_pktp);
26048 		mutex_exit(SD_MUTEX(un));
26049 		/*
26050 		 * Scsi_poll returns 0 (success) if the command completes and
26051 		 * the status block is STATUS_GOOD.
26052 		 */
26053 		if (sd_scsi_poll(un, start_pktp) != 0) {
26054 			scsi_destroy_pkt(start_pktp);
26055 			return (EIO);
26056 		}
26057 		scsi_destroy_pkt(start_pktp);
26058 		(void) sd_pm_state_change(un, SD_PM_STATE_ACTIVE(un),
26059 		    SD_PM_STATE_CHANGE);
26060 	} else {
26061 		mutex_exit(&un->un_pm_mutex);
26062 	}
26063 
26064 	mutex_enter(SD_MUTEX(un));
26065 	un->un_throttle = 0;
26066 
26067 	/*
26068 	 * The first time through, reset the specific target device.
26069 	 * However, when cpr calls sddump we know that sd is in a
26070 	 * a good state so no bus reset is required.
26071 	 * Clear sense data via Request Sense cmd.
26072 	 * In sddump we don't care about allow_bus_device_reset anymore
26073 	 */
26074 
26075 	if ((un->un_state != SD_STATE_SUSPENDED) &&
26076 	    (un->un_state != SD_STATE_DUMPING)) {
26077 
26078 		New_state(un, SD_STATE_DUMPING);
26079 
26080 		if (un->un_f_is_fibre == FALSE) {
26081 			mutex_exit(SD_MUTEX(un));
26082 			/*
26083 			 * Attempt a bus reset for parallel scsi.
26084 			 *
26085 			 * Note: A bus reset is required because on some host
26086 			 * systems (i.e. E420R) a bus device reset is
26087 			 * insufficient to reset the state of the target.
26088 			 *
26089 			 * Note: Don't issue the reset for fibre-channel,
26090 			 * because this tends to hang the bus (loop) for
26091 			 * too long while everyone is logging out and in
26092 			 * and the deadman timer for dumping will fire
26093 			 * before the dump is complete.
26094 			 */
26095 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
26096 				mutex_enter(SD_MUTEX(un));
26097 				Restore_state(un);
26098 				mutex_exit(SD_MUTEX(un));
26099 				return (EIO);
26100 			}
26101 
26102 			/* Delay to give the device some recovery time. */
26103 			drv_usecwait(10000);
26104 
26105 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
26106 				SD_INFO(SD_LOG_DUMP, un,
26107 				    "sddump: sd_send_polled_RQS failed\n");
26108 			}
26109 			mutex_enter(SD_MUTEX(un));
26110 		}
26111 	}
26112 
26113 	/*
26114 	 * Convert the partition-relative block number to a
26115 	 * disk physical block number.
26116 	 */
26117 	if (NOT_DEVBSIZE(un)) {
26118 		blkno += start_block;
26119 	} else {
26120 		blkno = blkno / (un->un_tgt_blocksize / DEV_BSIZE);
26121 		blkno += start_block;
26122 	}
26123 
26124 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
26125 
26126 
26127 	/*
26128 	 * Check if the device has a non-512 block size.
26129 	 */
26130 	wr_bp = NULL;
26131 	if (NOT_DEVBSIZE(un)) {
26132 		tgt_byte_offset = blkno * un->un_sys_blocksize;
26133 		tgt_byte_count = nblk * un->un_sys_blocksize;
26134 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
26135 		    (tgt_byte_count % un->un_tgt_blocksize)) {
26136 			doing_rmw = TRUE;
26137 			/*
26138 			 * Calculate the block number and number of block
26139 			 * in terms of the media block size.
26140 			 */
26141 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26142 			tgt_nblk =
26143 			    ((tgt_byte_offset + tgt_byte_count +
26144 			    (un->un_tgt_blocksize - 1)) /
26145 			    un->un_tgt_blocksize) - tgt_blkno;
26146 
26147 			/*
26148 			 * Invoke the routine which is going to do read part
26149 			 * of read-modify-write.
26150 			 * Note that this routine returns a pointer to
26151 			 * a valid bp in wr_bp.
26152 			 */
26153 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
26154 			    &wr_bp);
26155 			if (err) {
26156 				mutex_exit(SD_MUTEX(un));
26157 				return (err);
26158 			}
26159 			/*
26160 			 * Offset is being calculated as -
26161 			 * (original block # * system block size) -
26162 			 * (new block # * target block size)
26163 			 */
26164 			io_start_offset =
26165 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
26166 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
26167 
26168 			ASSERT(io_start_offset < un->un_tgt_blocksize);
26169 			/*
26170 			 * Do the modify portion of read modify write.
26171 			 */
26172 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
26173 			    (size_t)nblk * un->un_sys_blocksize);
26174 		} else {
26175 			doing_rmw = FALSE;
26176 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26177 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
26178 		}
26179 
26180 		/* Convert blkno and nblk to target blocks */
26181 		blkno = tgt_blkno;
26182 		nblk = tgt_nblk;
26183 	} else {
26184 		wr_bp = &wr_buf;
26185 		bzero(wr_bp, sizeof (struct buf));
26186 		wr_bp->b_flags		= B_BUSY;
26187 		wr_bp->b_un.b_addr	= addr;
26188 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
26189 		wr_bp->b_resid		= 0;
26190 	}
26191 
26192 	mutex_exit(SD_MUTEX(un));
26193 
26194 	/*
26195 	 * Obtain a SCSI packet for the write command.
26196 	 * It should be safe to call the allocator here without
26197 	 * worrying about being locked for DVMA mapping because
26198 	 * the address we're passed is already a DVMA mapping
26199 	 *
26200 	 * We are also not going to worry about semaphore ownership
26201 	 * in the dump buffer. Dumping is single threaded at present.
26202 	 */
26203 
26204 	wr_pktp = NULL;
26205 
26206 	dma_resid = wr_bp->b_bcount;
26207 	oblkno = blkno;
26208 
26209 	if (!(NOT_DEVBSIZE(un))) {
26210 		nblk = nblk / (un->un_tgt_blocksize / DEV_BSIZE);
26211 	}
26212 
26213 	while (dma_resid != 0) {
26214 
26215 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26216 		wr_bp->b_flags &= ~B_ERROR;
26217 
26218 		if (un->un_partial_dma_supported == 1) {
26219 			blkno = oblkno +
26220 			    ((wr_bp->b_bcount - dma_resid) /
26221 			    un->un_tgt_blocksize);
26222 			nblk = dma_resid / un->un_tgt_blocksize;
26223 
26224 			if (wr_pktp) {
26225 				/*
26226 				 * Partial DMA transfers after initial transfer
26227 				 */
26228 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
26229 				    blkno, nblk);
26230 			} else {
26231 				/* Initial transfer */
26232 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26233 				    un->un_pkt_flags, NULL_FUNC, NULL,
26234 				    blkno, nblk);
26235 			}
26236 		} else {
26237 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26238 			    0, NULL_FUNC, NULL, blkno, nblk);
26239 		}
26240 
26241 		if (rval == 0) {
26242 			/* We were given a SCSI packet, continue. */
26243 			break;
26244 		}
26245 
26246 		if (i == 0) {
26247 			if (wr_bp->b_flags & B_ERROR) {
26248 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26249 				    "no resources for dumping; "
26250 				    "error code: 0x%x, retrying",
26251 				    geterror(wr_bp));
26252 			} else {
26253 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26254 				    "no resources for dumping; retrying");
26255 			}
26256 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
26257 			if (wr_bp->b_flags & B_ERROR) {
26258 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26259 				    "no resources for dumping; error code: "
26260 				    "0x%x, retrying\n", geterror(wr_bp));
26261 			}
26262 		} else {
26263 			if (wr_bp->b_flags & B_ERROR) {
26264 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26265 				    "no resources for dumping; "
26266 				    "error code: 0x%x, retries failed, "
26267 				    "giving up.\n", geterror(wr_bp));
26268 			} else {
26269 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26270 				    "no resources for dumping; "
26271 				    "retries failed, giving up.\n");
26272 			}
26273 			mutex_enter(SD_MUTEX(un));
26274 			Restore_state(un);
26275 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
26276 				mutex_exit(SD_MUTEX(un));
26277 				scsi_free_consistent_buf(wr_bp);
26278 			} else {
26279 				mutex_exit(SD_MUTEX(un));
26280 			}
26281 			return (EIO);
26282 		}
26283 		drv_usecwait(10000);
26284 	}
26285 
26286 	if (un->un_partial_dma_supported == 1) {
26287 		/*
26288 		 * save the resid from PARTIAL_DMA
26289 		 */
26290 		dma_resid = wr_pktp->pkt_resid;
26291 		if (dma_resid != 0)
26292 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
26293 		wr_pktp->pkt_resid = 0;
26294 	} else {
26295 		dma_resid = 0;
26296 	}
26297 
26298 	/* SunBug 1222170 */
26299 	wr_pktp->pkt_flags = FLAG_NOINTR;
26300 
26301 	err = EIO;
26302 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26303 
26304 		/*
26305 		 * Scsi_poll returns 0 (success) if the command completes and
26306 		 * the status block is STATUS_GOOD.  We should only check
26307 		 * errors if this condition is not true.  Even then we should
26308 		 * send our own request sense packet only if we have a check
26309 		 * condition and auto request sense has not been performed by
26310 		 * the hba.
26311 		 */
26312 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
26313 
26314 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
26315 		    (wr_pktp->pkt_resid == 0)) {
26316 			err = SD_SUCCESS;
26317 			break;
26318 		}
26319 
26320 		/*
26321 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
26322 		 */
26323 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
26324 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26325 			    "Error while dumping state...Device is gone\n");
26326 			break;
26327 		}
26328 
26329 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
26330 			SD_INFO(SD_LOG_DUMP, un,
26331 			    "sddump: write failed with CHECK, try # %d\n", i);
26332 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
26333 				(void) sd_send_polled_RQS(un);
26334 			}
26335 
26336 			continue;
26337 		}
26338 
26339 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
26340 			int reset_retval = 0;
26341 
26342 			SD_INFO(SD_LOG_DUMP, un,
26343 			    "sddump: write failed with BUSY, try # %d\n", i);
26344 
26345 			if (un->un_f_lun_reset_enabled == TRUE) {
26346 				reset_retval = scsi_reset(SD_ADDRESS(un),
26347 				    RESET_LUN);
26348 			}
26349 			if (reset_retval == 0) {
26350 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26351 			}
26352 			(void) sd_send_polled_RQS(un);
26353 
26354 		} else {
26355 			SD_INFO(SD_LOG_DUMP, un,
26356 			    "sddump: write failed with 0x%x, try # %d\n",
26357 			    SD_GET_PKT_STATUS(wr_pktp), i);
26358 			mutex_enter(SD_MUTEX(un));
26359 			sd_reset_target(un, wr_pktp);
26360 			mutex_exit(SD_MUTEX(un));
26361 		}
26362 
26363 		/*
26364 		 * If we are not getting anywhere with lun/target resets,
26365 		 * let's reset the bus.
26366 		 */
26367 		if (i == SD_NDUMP_RETRIES / 2) {
26368 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26369 			(void) sd_send_polled_RQS(un);
26370 		}
26371 	}
26372 	}
26373 
26374 	scsi_destroy_pkt(wr_pktp);
26375 	mutex_enter(SD_MUTEX(un));
26376 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
26377 		mutex_exit(SD_MUTEX(un));
26378 		scsi_free_consistent_buf(wr_bp);
26379 	} else {
26380 		mutex_exit(SD_MUTEX(un));
26381 	}
26382 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
26383 	return (err);
26384 }
26385 
26386 /*
26387  *    Function: sd_scsi_poll()
26388  *
26389  * Description: This is a wrapper for the scsi_poll call.
26390  *
26391  *   Arguments: sd_lun - The unit structure
26392  *              scsi_pkt - The scsi packet being sent to the device.
26393  *
26394  * Return Code: 0 - Command completed successfully with good status
26395  *             -1 - Command failed.  This could indicate a check condition
26396  *                  or other status value requiring recovery action.
26397  *
26398  * NOTE: This code is only called off sddump().
26399  */
26400 
26401 static int
26402 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
26403 {
26404 	int status;
26405 
26406 	ASSERT(un != NULL);
26407 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26408 	ASSERT(pktp != NULL);
26409 
26410 	status = SD_SUCCESS;
26411 
26412 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
26413 		pktp->pkt_flags |= un->un_tagflags;
26414 		pktp->pkt_flags &= ~FLAG_NODISCON;
26415 	}
26416 
26417 	status = sd_ddi_scsi_poll(pktp);
26418 	/*
26419 	 * Scsi_poll returns 0 (success) if the command completes and the
26420 	 * status block is STATUS_GOOD.  We should only check errors if this
26421 	 * condition is not true.  Even then we should send our own request
26422 	 * sense packet only if we have a check condition and auto
26423 	 * request sense has not been performed by the hba.
26424 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
26425 	 */
26426 	if ((status != SD_SUCCESS) &&
26427 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
26428 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
26429 	    (pktp->pkt_reason != CMD_DEV_GONE))
26430 		(void) sd_send_polled_RQS(un);
26431 
26432 	return (status);
26433 }
26434 
26435 /*
26436  *    Function: sd_send_polled_RQS()
26437  *
26438  * Description: This sends the request sense command to a device.
26439  *
26440  *   Arguments: sd_lun - The unit structure
26441  *
26442  * Return Code: 0 - Command completed successfully with good status
26443  *             -1 - Command failed.
26444  *
26445  */
26446 
26447 static int
26448 sd_send_polled_RQS(struct sd_lun *un)
26449 {
26450 	int	ret_val;
26451 	struct	scsi_pkt	*rqs_pktp;
26452 	struct	buf		*rqs_bp;
26453 
26454 	ASSERT(un != NULL);
26455 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26456 
26457 	ret_val = SD_SUCCESS;
26458 
26459 	rqs_pktp = un->un_rqs_pktp;
26460 	rqs_bp	 = un->un_rqs_bp;
26461 
26462 	mutex_enter(SD_MUTEX(un));
26463 
26464 	if (un->un_sense_isbusy) {
26465 		ret_val = SD_FAILURE;
26466 		mutex_exit(SD_MUTEX(un));
26467 		return (ret_val);
26468 	}
26469 
26470 	/*
26471 	 * If the request sense buffer (and packet) is not in use,
26472 	 * let's set the un_sense_isbusy and send our packet
26473 	 */
26474 	un->un_sense_isbusy = 1;
26475 	rqs_pktp->pkt_resid = 0;
26476 	rqs_pktp->pkt_reason = 0;
26477 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
26478 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
26479 
26480 	mutex_exit(SD_MUTEX(un));
26481 
26482 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
26483 	    " 0x%p\n", rqs_bp->b_un.b_addr);
26484 
26485 	/*
26486 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
26487 	 * axle - it has a call into us!
26488 	 */
26489 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
26490 		SD_INFO(SD_LOG_COMMON, un,
26491 		    "sd_send_polled_RQS: RQS failed\n");
26492 	}
26493 
26494 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
26495 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
26496 
26497 	mutex_enter(SD_MUTEX(un));
26498 	un->un_sense_isbusy = 0;
26499 	mutex_exit(SD_MUTEX(un));
26500 
26501 	return (ret_val);
26502 }
26503 
26504 /*
26505  * Defines needed for localized version of the scsi_poll routine.
26506  */
26507 #define	CSEC		10000			/* usecs */
26508 #define	SEC_TO_CSEC	(1000000 / CSEC)
26509 
26510 /*
26511  *    Function: sd_ddi_scsi_poll()
26512  *
26513  * Description: Localized version of the scsi_poll routine.  The purpose is to
26514  *		send a scsi_pkt to a device as a polled command.  This version
26515  *		is to ensure more robust handling of transport errors.
26516  *		Specifically this routine cures not ready, coming ready
26517  *		transition for power up and reset of sonoma's.  This can take
26518  *		up to 45 seconds for power-on and 20 seconds for reset of a
26519  *		sonoma lun.
26520  *
26521  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
26522  *
26523  * Return Code: 0 - Command completed successfully with good status
26524  *             -1 - Command failed.
26525  *
26526  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
26527  * be fixed (removing this code), we need to determine how to handle the
26528  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
26529  *
26530  * NOTE: This code is only called off sddump().
26531  */
26532 static int
26533 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
26534 {
26535 	int			rval = -1;
26536 	int			savef;
26537 	long			savet;
26538 	void			(*savec)();
26539 	int			timeout;
26540 	int			busy_count;
26541 	int			poll_delay;
26542 	int			rc;
26543 	uint8_t			*sensep;
26544 	struct scsi_arq_status	*arqstat;
26545 	extern int		do_polled_io;
26546 
26547 	ASSERT(pkt->pkt_scbp);
26548 
26549 	/*
26550 	 * save old flags..
26551 	 */
26552 	savef = pkt->pkt_flags;
26553 	savec = pkt->pkt_comp;
26554 	savet = pkt->pkt_time;
26555 
26556 	pkt->pkt_flags |= FLAG_NOINTR;
26557 
26558 	/*
26559 	 * XXX there is nothing in the SCSA spec that states that we should not
26560 	 * do a callback for polled cmds; however, removing this will break sd
26561 	 * and probably other target drivers
26562 	 */
26563 	pkt->pkt_comp = NULL;
26564 
26565 	/*
26566 	 * we don't like a polled command without timeout.
26567 	 * 60 seconds seems long enough.
26568 	 */
26569 	if (pkt->pkt_time == 0)
26570 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
26571 
26572 	/*
26573 	 * Send polled cmd.
26574 	 *
26575 	 * We do some error recovery for various errors.  Tran_busy,
26576 	 * queue full, and non-dispatched commands are retried every 10 msec.
26577 	 * as they are typically transient failures.  Busy status and Not
26578 	 * Ready are retried every second as this status takes a while to
26579 	 * change.
26580 	 */
26581 	timeout = pkt->pkt_time * SEC_TO_CSEC;
26582 
26583 	for (busy_count = 0; busy_count < timeout; busy_count++) {
26584 		/*
26585 		 * Initialize pkt status variables.
26586 		 */
26587 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
26588 
26589 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
26590 			if (rc != TRAN_BUSY) {
26591 				/* Transport failed - give up. */
26592 				break;
26593 			} else {
26594 				/* Transport busy - try again. */
26595 				poll_delay = 1 * CSEC;		/* 10 msec. */
26596 			}
26597 		} else {
26598 			/*
26599 			 * Transport accepted - check pkt status.
26600 			 */
26601 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
26602 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26603 			    (rc == STATUS_CHECK) &&
26604 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
26605 				arqstat =
26606 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
26607 				sensep = (uint8_t *)&arqstat->sts_sensedata;
26608 			} else {
26609 				sensep = NULL;
26610 			}
26611 
26612 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26613 			    (rc == STATUS_GOOD)) {
26614 				/* No error - we're done */
26615 				rval = 0;
26616 				break;
26617 
26618 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
26619 				/* Lost connection - give up */
26620 				break;
26621 
26622 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
26623 			    (pkt->pkt_state == 0)) {
26624 				/* Pkt not dispatched - try again. */
26625 				poll_delay = 1 * CSEC;		/* 10 msec. */
26626 
26627 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26628 			    (rc == STATUS_QFULL)) {
26629 				/* Queue full - try again. */
26630 				poll_delay = 1 * CSEC;		/* 10 msec. */
26631 
26632 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26633 			    (rc == STATUS_BUSY)) {
26634 				/* Busy - try again. */
26635 				poll_delay = 100 * CSEC;	/* 1 sec. */
26636 				busy_count += (SEC_TO_CSEC - 1);
26637 
26638 			} else if ((sensep != NULL) &&
26639 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
26640 				/*
26641 				 * Unit Attention - try again.
26642 				 * Pretend it took 1 sec.
26643 				 * NOTE: 'continue' avoids poll_delay
26644 				 */
26645 				busy_count += (SEC_TO_CSEC - 1);
26646 				continue;
26647 
26648 			} else if ((sensep != NULL) &&
26649 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
26650 			    (scsi_sense_asc(sensep) == 0x04) &&
26651 			    (scsi_sense_ascq(sensep) == 0x01)) {
26652 				/*
26653 				 * Not ready -> ready - try again.
26654 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
26655 				 * ...same as STATUS_BUSY
26656 				 */
26657 				poll_delay = 100 * CSEC;	/* 1 sec. */
26658 				busy_count += (SEC_TO_CSEC - 1);
26659 
26660 			} else {
26661 				/* BAD status - give up. */
26662 				break;
26663 			}
26664 		}
26665 
26666 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
26667 		    !do_polled_io) {
26668 			delay(drv_usectohz(poll_delay));
26669 		} else {
26670 			/* we busy wait during cpr_dump or interrupt threads */
26671 			drv_usecwait(poll_delay);
26672 		}
26673 	}
26674 
26675 	pkt->pkt_flags = savef;
26676 	pkt->pkt_comp = savec;
26677 	pkt->pkt_time = savet;
26678 
26679 	/* return on error */
26680 	if (rval)
26681 		return (rval);
26682 
26683 	/*
26684 	 * This is not a performance critical code path.
26685 	 *
26686 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
26687 	 * issues associated with looking at DMA memory prior to
26688 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
26689 	 */
26690 	scsi_sync_pkt(pkt);
26691 	return (0);
26692 }
26693 
26694 
26695 
26696 /*
26697  *    Function: sd_persistent_reservation_in_read_keys
26698  *
26699  * Description: This routine is the driver entry point for handling CD-ROM
26700  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
26701  *		by sending the SCSI-3 PRIN commands to the device.
26702  *		Processes the read keys command response by copying the
26703  *		reservation key information into the user provided buffer.
26704  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
26705  *
26706  *   Arguments: un   -  Pointer to soft state struct for the target.
26707  *		usrp -	user provided pointer to multihost Persistent In Read
26708  *			Keys structure (mhioc_inkeys_t)
26709  *		flag -	this argument is a pass through to ddi_copyxxx()
26710  *			directly from the mode argument of ioctl().
26711  *
26712  * Return Code: 0   - Success
26713  *		EACCES
26714  *		ENOTSUP
26715  *		errno return code from sd_send_scsi_cmd()
26716  *
26717  *     Context: Can sleep. Does not return until command is completed.
26718  */
26719 
26720 static int
26721 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
26722     mhioc_inkeys_t *usrp, int flag)
26723 {
26724 #ifdef _MULTI_DATAMODEL
26725 	struct mhioc_key_list32	li32;
26726 #endif
26727 	sd_prin_readkeys_t	*in;
26728 	mhioc_inkeys_t		*ptr;
26729 	mhioc_key_list_t	li;
26730 	uchar_t			*data_bufp = NULL;
26731 	int			data_len = 0;
26732 	int			rval = 0;
26733 	size_t			copysz = 0;
26734 	sd_ssc_t		*ssc;
26735 
26736 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
26737 		return (EINVAL);
26738 	}
26739 	bzero(&li, sizeof (mhioc_key_list_t));
26740 
26741 	ssc = sd_ssc_init(un);
26742 
26743 	/*
26744 	 * Get the listsize from user
26745 	 */
26746 #ifdef _MULTI_DATAMODEL
26747 	switch (ddi_model_convert_from(flag & FMODELS)) {
26748 	case DDI_MODEL_ILP32:
26749 		copysz = sizeof (struct mhioc_key_list32);
26750 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
26751 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26752 			    "sd_persistent_reservation_in_read_keys: "
26753 			    "failed ddi_copyin: mhioc_key_list32_t\n");
26754 			rval = EFAULT;
26755 			goto done;
26756 		}
26757 		li.listsize = li32.listsize;
26758 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
26759 		break;
26760 
26761 	case DDI_MODEL_NONE:
26762 		copysz = sizeof (mhioc_key_list_t);
26763 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26764 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26765 			    "sd_persistent_reservation_in_read_keys: "
26766 			    "failed ddi_copyin: mhioc_key_list_t\n");
26767 			rval = EFAULT;
26768 			goto done;
26769 		}
26770 		break;
26771 	}
26772 
26773 #else /* ! _MULTI_DATAMODEL */
26774 	copysz = sizeof (mhioc_key_list_t);
26775 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26776 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26777 		    "sd_persistent_reservation_in_read_keys: "
26778 		    "failed ddi_copyin: mhioc_key_list_t\n");
26779 		rval = EFAULT;
26780 		goto done;
26781 	}
26782 #endif
26783 
26784 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
26785 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
26786 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26787 
26788 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
26789 	    data_len, data_bufp);
26790 	if (rval != 0) {
26791 		if (rval == EIO)
26792 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26793 		else
26794 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26795 		goto done;
26796 	}
26797 	in = (sd_prin_readkeys_t *)data_bufp;
26798 	ptr->generation = BE_32(in->generation);
26799 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
26800 
26801 	/*
26802 	 * Return the min(listsize, listlen) keys
26803 	 */
26804 #ifdef _MULTI_DATAMODEL
26805 
26806 	switch (ddi_model_convert_from(flag & FMODELS)) {
26807 	case DDI_MODEL_ILP32:
26808 		li32.listlen = li.listlen;
26809 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
26810 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26811 			    "sd_persistent_reservation_in_read_keys: "
26812 			    "failed ddi_copyout: mhioc_key_list32_t\n");
26813 			rval = EFAULT;
26814 			goto done;
26815 		}
26816 		break;
26817 
26818 	case DDI_MODEL_NONE:
26819 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26820 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26821 			    "sd_persistent_reservation_in_read_keys: "
26822 			    "failed ddi_copyout: mhioc_key_list_t\n");
26823 			rval = EFAULT;
26824 			goto done;
26825 		}
26826 		break;
26827 	}
26828 
26829 #else /* ! _MULTI_DATAMODEL */
26830 
26831 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26832 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26833 		    "sd_persistent_reservation_in_read_keys: "
26834 		    "failed ddi_copyout: mhioc_key_list_t\n");
26835 		rval = EFAULT;
26836 		goto done;
26837 	}
26838 
26839 #endif /* _MULTI_DATAMODEL */
26840 
26841 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
26842 	    li.listsize * MHIOC_RESV_KEY_SIZE);
26843 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
26844 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26845 		    "sd_persistent_reservation_in_read_keys: "
26846 		    "failed ddi_copyout: keylist\n");
26847 		rval = EFAULT;
26848 	}
26849 done:
26850 	sd_ssc_fini(ssc);
26851 	kmem_free(data_bufp, data_len);
26852 	return (rval);
26853 }
26854 
26855 
26856 /*
26857  *    Function: sd_persistent_reservation_in_read_resv
26858  *
26859  * Description: This routine is the driver entry point for handling CD-ROM
26860  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
26861  *		by sending the SCSI-3 PRIN commands to the device.
26862  *		Process the read persistent reservations command response by
26863  *		copying the reservation information into the user provided
26864  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
26865  *
26866  *   Arguments: un   -  Pointer to soft state struct for the target.
26867  *		usrp -	user provided pointer to multihost Persistent In Read
26868  *			Keys structure (mhioc_inkeys_t)
26869  *		flag -	this argument is a pass through to ddi_copyxxx()
26870  *			directly from the mode argument of ioctl().
26871  *
26872  * Return Code: 0   - Success
26873  *		EACCES
26874  *		ENOTSUP
26875  *		errno return code from sd_send_scsi_cmd()
26876  *
26877  *     Context: Can sleep. Does not return until command is completed.
26878  */
26879 
26880 static int
26881 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
26882     mhioc_inresvs_t *usrp, int flag)
26883 {
26884 #ifdef _MULTI_DATAMODEL
26885 	struct mhioc_resv_desc_list32 resvlist32;
26886 #endif
26887 	sd_prin_readresv_t	*in;
26888 	mhioc_inresvs_t		*ptr;
26889 	sd_readresv_desc_t	*readresv_ptr;
26890 	mhioc_resv_desc_list_t	resvlist;
26891 	mhioc_resv_desc_t	resvdesc;
26892 	uchar_t			*data_bufp = NULL;
26893 	int			data_len;
26894 	int			rval = 0;
26895 	int			i;
26896 	size_t			copysz = 0;
26897 	mhioc_resv_desc_t	*bufp;
26898 	sd_ssc_t		*ssc;
26899 
26900 	if ((ptr = usrp) == NULL) {
26901 		return (EINVAL);
26902 	}
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_resv_desc_list32);
26913 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
26914 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26915 			    "sd_persistent_reservation_in_read_resv: "
26916 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26917 			rval = EFAULT;
26918 			goto done;
26919 		}
26920 		resvlist.listsize = resvlist32.listsize;
26921 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
26922 		break;
26923 
26924 	case DDI_MODEL_NONE:
26925 		copysz = sizeof (mhioc_resv_desc_list_t);
26926 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26927 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26928 			    "sd_persistent_reservation_in_read_resv: "
26929 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26930 			rval = EFAULT;
26931 			goto done;
26932 		}
26933 		break;
26934 	}
26935 #else /* ! _MULTI_DATAMODEL */
26936 	copysz = sizeof (mhioc_resv_desc_list_t);
26937 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26938 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26939 		    "sd_persistent_reservation_in_read_resv: "
26940 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26941 		rval = EFAULT;
26942 		goto done;
26943 	}
26944 #endif /* ! _MULTI_DATAMODEL */
26945 
26946 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
26947 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
26948 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26949 
26950 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
26951 	    data_len, data_bufp);
26952 	if (rval != 0) {
26953 		if (rval == EIO)
26954 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26955 		else
26956 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26957 		goto done;
26958 	}
26959 	in = (sd_prin_readresv_t *)data_bufp;
26960 	ptr->generation = BE_32(in->generation);
26961 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
26962 
26963 	/*
26964 	 * Return the min(listsize, listlen( keys
26965 	 */
26966 #ifdef _MULTI_DATAMODEL
26967 
26968 	switch (ddi_model_convert_from(flag & FMODELS)) {
26969 	case DDI_MODEL_ILP32:
26970 		resvlist32.listlen = resvlist.listlen;
26971 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
26972 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26973 			    "sd_persistent_reservation_in_read_resv: "
26974 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26975 			rval = EFAULT;
26976 			goto done;
26977 		}
26978 		break;
26979 
26980 	case DDI_MODEL_NONE:
26981 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26982 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26983 			    "sd_persistent_reservation_in_read_resv: "
26984 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26985 			rval = EFAULT;
26986 			goto done;
26987 		}
26988 		break;
26989 	}
26990 
26991 #else /* ! _MULTI_DATAMODEL */
26992 
26993 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26994 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26995 		    "sd_persistent_reservation_in_read_resv: "
26996 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26997 		rval = EFAULT;
26998 		goto done;
26999 	}
27000 
27001 #endif /* ! _MULTI_DATAMODEL */
27002 
27003 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
27004 	bufp = resvlist.list;
27005 	copysz = sizeof (mhioc_resv_desc_t);
27006 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
27007 	    i++, readresv_ptr++, bufp++) {
27008 
27009 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
27010 		    MHIOC_RESV_KEY_SIZE);
27011 		resvdesc.type  = readresv_ptr->type;
27012 		resvdesc.scope = readresv_ptr->scope;
27013 		resvdesc.scope_specific_addr =
27014 		    BE_32(readresv_ptr->scope_specific_addr);
27015 
27016 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
27017 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
27018 			    "sd_persistent_reservation_in_read_resv: "
27019 			    "failed ddi_copyout: resvlist\n");
27020 			rval = EFAULT;
27021 			goto done;
27022 		}
27023 	}
27024 done:
27025 	sd_ssc_fini(ssc);
27026 	/* only if data_bufp is allocated, we need to free it */
27027 	if (data_bufp) {
27028 		kmem_free(data_bufp, data_len);
27029 	}
27030 	return (rval);
27031 }
27032 
27033 
27034 /*
27035  *    Function: sr_change_blkmode()
27036  *
27037  * Description: This routine is the driver entry point for handling CD-ROM
27038  *		block mode ioctl requests. Support for returning and changing
27039  *		the current block size in use by the device is implemented. The
27040  *		LBA size is changed via a MODE SELECT Block Descriptor.
27041  *
27042  *		This routine issues a mode sense with an allocation length of
27043  *		12 bytes for the mode page header and a single block descriptor.
27044  *
27045  *   Arguments: dev - the device 'dev_t'
27046  *		cmd - the request type; one of CDROMGBLKMODE (get) or
27047  *		      CDROMSBLKMODE (set)
27048  *		data - current block size or requested block size
27049  *		flag - this argument is a pass through to ddi_copyxxx() directly
27050  *		       from the mode argument of ioctl().
27051  *
27052  * Return Code: the code returned by sd_send_scsi_cmd()
27053  *		EINVAL if invalid arguments are provided
27054  *		EFAULT if ddi_copyxxx() fails
27055  *		ENXIO if fail ddi_get_soft_state
27056  *		EIO if invalid mode sense block descriptor length
27057  *
27058  */
27059 
27060 static int
27061 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
27062 {
27063 	struct sd_lun			*un = NULL;
27064 	struct mode_header		*sense_mhp, *select_mhp;
27065 	struct block_descriptor		*sense_desc, *select_desc;
27066 	int				current_bsize;
27067 	int				rval = EINVAL;
27068 	uchar_t				*sense = NULL;
27069 	uchar_t				*select = NULL;
27070 	sd_ssc_t			*ssc;
27071 
27072 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
27073 
27074 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27075 		return (ENXIO);
27076 	}
27077 
27078 	/*
27079 	 * The block length is changed via the Mode Select block descriptor, the
27080 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
27081 	 * required as part of this routine. Therefore the mode sense allocation
27082 	 * length is specified to be the length of a mode page header and a
27083 	 * block descriptor.
27084 	 */
27085 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27086 
27087 	ssc = sd_ssc_init(un);
27088 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27089 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
27090 	sd_ssc_fini(ssc);
27091 	if (rval != 0) {
27092 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27093 		    "sr_change_blkmode: Mode Sense Failed\n");
27094 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27095 		return (rval);
27096 	}
27097 
27098 	/* Check the block descriptor len to handle only 1 block descriptor */
27099 	sense_mhp = (struct mode_header *)sense;
27100 	if ((sense_mhp->bdesc_length == 0) ||
27101 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
27102 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27103 		    "sr_change_blkmode: Mode Sense returned invalid block"
27104 		    " descriptor length\n");
27105 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27106 		return (EIO);
27107 	}
27108 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
27109 	current_bsize = ((sense_desc->blksize_hi << 16) |
27110 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
27111 
27112 	/* Process command */
27113 	switch (cmd) {
27114 	case CDROMGBLKMODE:
27115 		/* Return the block size obtained during the mode sense */
27116 		if (ddi_copyout(&current_bsize, (void *)data,
27117 		    sizeof (int), flag) != 0)
27118 			rval = EFAULT;
27119 		break;
27120 	case CDROMSBLKMODE:
27121 		/* Validate the requested block size */
27122 		switch (data) {
27123 		case CDROM_BLK_512:
27124 		case CDROM_BLK_1024:
27125 		case CDROM_BLK_2048:
27126 		case CDROM_BLK_2056:
27127 		case CDROM_BLK_2336:
27128 		case CDROM_BLK_2340:
27129 		case CDROM_BLK_2352:
27130 		case CDROM_BLK_2368:
27131 		case CDROM_BLK_2448:
27132 		case CDROM_BLK_2646:
27133 		case CDROM_BLK_2647:
27134 			break;
27135 		default:
27136 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27137 			    "sr_change_blkmode: "
27138 			    "Block Size '%ld' Not Supported\n", data);
27139 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27140 			return (EINVAL);
27141 		}
27142 
27143 		/*
27144 		 * The current block size matches the requested block size so
27145 		 * there is no need to send the mode select to change the size
27146 		 */
27147 		if (current_bsize == data) {
27148 			break;
27149 		}
27150 
27151 		/* Build the select data for the requested block size */
27152 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27153 		select_mhp = (struct mode_header *)select;
27154 		select_desc =
27155 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
27156 		/*
27157 		 * The LBA size is changed via the block descriptor, so the
27158 		 * descriptor is built according to the user data
27159 		 */
27160 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
27161 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
27162 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
27163 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
27164 
27165 		/* Send the mode select for the requested block size */
27166 		ssc = sd_ssc_init(un);
27167 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
27168 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27169 		    SD_PATH_STANDARD);
27170 		sd_ssc_fini(ssc);
27171 		if (rval != 0) {
27172 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27173 			    "sr_change_blkmode: Mode Select Failed\n");
27174 			/*
27175 			 * The mode select failed for the requested block size,
27176 			 * so reset the data for the original block size and
27177 			 * send it to the target. The error is indicated by the
27178 			 * return value for the failed mode select.
27179 			 */
27180 			select_desc->blksize_hi  = sense_desc->blksize_hi;
27181 			select_desc->blksize_mid = sense_desc->blksize_mid;
27182 			select_desc->blksize_lo  = sense_desc->blksize_lo;
27183 			ssc = sd_ssc_init(un);
27184 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
27185 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27186 			    SD_PATH_STANDARD);
27187 			sd_ssc_fini(ssc);
27188 		} else {
27189 			ASSERT(!mutex_owned(SD_MUTEX(un)));
27190 			mutex_enter(SD_MUTEX(un));
27191 			sd_update_block_info(un, (uint32_t)data, 0);
27192 			mutex_exit(SD_MUTEX(un));
27193 		}
27194 		break;
27195 	default:
27196 		/* should not reach here, but check anyway */
27197 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27198 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
27199 		rval = EINVAL;
27200 		break;
27201 	}
27202 
27203 	if (select) {
27204 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
27205 	}
27206 	if (sense) {
27207 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27208 	}
27209 	return (rval);
27210 }
27211 
27212 
27213 /*
27214  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
27215  * implement driver support for getting and setting the CD speed. The command
27216  * set used will be based on the device type. If the device has not been
27217  * identified as MMC the Toshiba vendor specific mode page will be used. If
27218  * the device is MMC but does not support the Real Time Streaming feature
27219  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
27220  * be used to read the speed.
27221  */
27222 
27223 /*
27224  *    Function: sr_change_speed()
27225  *
27226  * Description: This routine is the driver entry point for handling CD-ROM
27227  *		drive speed ioctl requests for devices supporting the Toshiba
27228  *		vendor specific drive speed mode page. Support for returning
27229  *		and changing the current drive speed in use by the device is
27230  *		implemented.
27231  *
27232  *   Arguments: dev - the device 'dev_t'
27233  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
27234  *		      CDROMSDRVSPEED (set)
27235  *		data - current drive speed or requested drive speed
27236  *		flag - this argument is a pass through to ddi_copyxxx() directly
27237  *		       from the mode argument of ioctl().
27238  *
27239  * Return Code: the code returned by sd_send_scsi_cmd()
27240  *		EINVAL if invalid arguments are provided
27241  *		EFAULT if ddi_copyxxx() fails
27242  *		ENXIO if fail ddi_get_soft_state
27243  *		EIO if invalid mode sense block descriptor length
27244  */
27245 
27246 static int
27247 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27248 {
27249 	struct sd_lun			*un = NULL;
27250 	struct mode_header		*sense_mhp, *select_mhp;
27251 	struct mode_speed		*sense_page, *select_page;
27252 	int				current_speed;
27253 	int				rval = EINVAL;
27254 	int				bd_len;
27255 	uchar_t				*sense = NULL;
27256 	uchar_t				*select = NULL;
27257 	sd_ssc_t			*ssc;
27258 
27259 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27260 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27261 		return (ENXIO);
27262 	}
27263 
27264 	/*
27265 	 * Note: The drive speed is being modified here according to a Toshiba
27266 	 * vendor specific mode page (0x31).
27267 	 */
27268 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27269 
27270 	ssc = sd_ssc_init(un);
27271 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27272 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
27273 	    SD_PATH_STANDARD);
27274 	sd_ssc_fini(ssc);
27275 	if (rval != 0) {
27276 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27277 		    "sr_change_speed: Mode Sense Failed\n");
27278 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27279 		return (rval);
27280 	}
27281 	sense_mhp  = (struct mode_header *)sense;
27282 
27283 	/* Check the block descriptor len to handle only 1 block descriptor */
27284 	bd_len = sense_mhp->bdesc_length;
27285 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27286 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27287 		    "sr_change_speed: Mode Sense returned invalid block "
27288 		    "descriptor length\n");
27289 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27290 		return (EIO);
27291 	}
27292 
27293 	sense_page = (struct mode_speed *)
27294 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27295 	current_speed = sense_page->speed;
27296 
27297 	/* Process command */
27298 	switch (cmd) {
27299 	case CDROMGDRVSPEED:
27300 		/* Return the drive speed obtained during the mode sense */
27301 		if (current_speed == 0x2) {
27302 			current_speed = CDROM_TWELVE_SPEED;
27303 		}
27304 		if (ddi_copyout(&current_speed, (void *)data,
27305 		    sizeof (int), flag) != 0) {
27306 			rval = EFAULT;
27307 		}
27308 		break;
27309 	case CDROMSDRVSPEED:
27310 		/* Validate the requested drive speed */
27311 		switch ((uchar_t)data) {
27312 		case CDROM_TWELVE_SPEED:
27313 			data = 0x2;
27314 			/*FALLTHROUGH*/
27315 		case CDROM_NORMAL_SPEED:
27316 		case CDROM_DOUBLE_SPEED:
27317 		case CDROM_QUAD_SPEED:
27318 		case CDROM_MAXIMUM_SPEED:
27319 			break;
27320 		default:
27321 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27322 			    "sr_change_speed: "
27323 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
27324 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27325 			return (EINVAL);
27326 		}
27327 
27328 		/*
27329 		 * The current drive speed matches the requested drive speed so
27330 		 * there is no need to send the mode select to change the speed
27331 		 */
27332 		if (current_speed == data) {
27333 			break;
27334 		}
27335 
27336 		/* Build the select data for the requested drive speed */
27337 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27338 		select_mhp = (struct mode_header *)select;
27339 		select_mhp->bdesc_length = 0;
27340 		select_page =
27341 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27342 		select_page =
27343 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27344 		select_page->mode_page.code = CDROM_MODE_SPEED;
27345 		select_page->mode_page.length = 2;
27346 		select_page->speed = (uchar_t)data;
27347 
27348 		/* Send the mode select for the requested block size */
27349 		ssc = sd_ssc_init(un);
27350 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27351 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27352 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27353 		sd_ssc_fini(ssc);
27354 		if (rval != 0) {
27355 			/*
27356 			 * The mode select failed for the requested drive speed,
27357 			 * so reset the data for the original drive speed and
27358 			 * send it to the target. The error is indicated by the
27359 			 * return value for the failed mode select.
27360 			 */
27361 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27362 			    "sr_drive_speed: Mode Select Failed\n");
27363 			select_page->speed = sense_page->speed;
27364 			ssc = sd_ssc_init(un);
27365 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27366 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27367 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27368 			sd_ssc_fini(ssc);
27369 		}
27370 		break;
27371 	default:
27372 		/* should not reach here, but check anyway */
27373 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27374 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
27375 		rval = EINVAL;
27376 		break;
27377 	}
27378 
27379 	if (select) {
27380 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
27381 	}
27382 	if (sense) {
27383 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27384 	}
27385 
27386 	return (rval);
27387 }
27388 
27389 
27390 /*
27391  *    Function: sr_atapi_change_speed()
27392  *
27393  * Description: This routine is the driver entry point for handling CD-ROM
27394  *		drive speed ioctl requests for MMC devices that do not support
27395  *		the Real Time Streaming feature (0x107).
27396  *
27397  *		Note: This routine will use the SET SPEED command which may not
27398  *		be supported by all devices.
27399  *
27400  *   Arguments: dev- the device 'dev_t'
27401  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
27402  *		     CDROMSDRVSPEED (set)
27403  *		data- current drive speed or requested drive speed
27404  *		flag- this argument is a pass through to ddi_copyxxx() directly
27405  *		      from the mode argument of ioctl().
27406  *
27407  * Return Code: the code returned by sd_send_scsi_cmd()
27408  *		EINVAL if invalid arguments are provided
27409  *		EFAULT if ddi_copyxxx() fails
27410  *		ENXIO if fail ddi_get_soft_state
27411  *		EIO if invalid mode sense block descriptor length
27412  */
27413 
27414 static int
27415 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27416 {
27417 	struct sd_lun			*un;
27418 	struct uscsi_cmd		*com = NULL;
27419 	struct mode_header_grp2		*sense_mhp;
27420 	uchar_t				*sense_page;
27421 	uchar_t				*sense = NULL;
27422 	char				cdb[CDB_GROUP5];
27423 	int				bd_len;
27424 	int				current_speed = 0;
27425 	int				max_speed = 0;
27426 	int				rval;
27427 	sd_ssc_t			*ssc;
27428 
27429 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27430 
27431 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27432 		return (ENXIO);
27433 	}
27434 
27435 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
27436 
27437 	ssc = sd_ssc_init(un);
27438 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
27439 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
27440 	    SD_PATH_STANDARD);
27441 	sd_ssc_fini(ssc);
27442 	if (rval != 0) {
27443 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27444 		    "sr_atapi_change_speed: Mode Sense Failed\n");
27445 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27446 		return (rval);
27447 	}
27448 
27449 	/* Check the block descriptor len to handle only 1 block descriptor */
27450 	sense_mhp = (struct mode_header_grp2 *)sense;
27451 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
27452 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27453 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27454 		    "sr_atapi_change_speed: Mode Sense returned invalid "
27455 		    "block descriptor length\n");
27456 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27457 		return (EIO);
27458 	}
27459 
27460 	/* Calculate the current and maximum drive speeds */
27461 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27462 	current_speed = (sense_page[14] << 8) | sense_page[15];
27463 	max_speed = (sense_page[8] << 8) | sense_page[9];
27464 
27465 	/* Process the command */
27466 	switch (cmd) {
27467 	case CDROMGDRVSPEED:
27468 		current_speed /= SD_SPEED_1X;
27469 		if (ddi_copyout(&current_speed, (void *)data,
27470 		    sizeof (int), flag) != 0)
27471 			rval = EFAULT;
27472 		break;
27473 	case CDROMSDRVSPEED:
27474 		/* Convert the speed code to KB/sec */
27475 		switch ((uchar_t)data) {
27476 		case CDROM_NORMAL_SPEED:
27477 			current_speed = SD_SPEED_1X;
27478 			break;
27479 		case CDROM_DOUBLE_SPEED:
27480 			current_speed = 2 * SD_SPEED_1X;
27481 			break;
27482 		case CDROM_QUAD_SPEED:
27483 			current_speed = 4 * SD_SPEED_1X;
27484 			break;
27485 		case CDROM_TWELVE_SPEED:
27486 			current_speed = 12 * SD_SPEED_1X;
27487 			break;
27488 		case CDROM_MAXIMUM_SPEED:
27489 			current_speed = 0xffff;
27490 			break;
27491 		default:
27492 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27493 			    "sr_atapi_change_speed: invalid drive speed %d\n",
27494 			    (uchar_t)data);
27495 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27496 			return (EINVAL);
27497 		}
27498 
27499 		/* Check the request against the drive's max speed. */
27500 		if (current_speed != 0xffff) {
27501 			if (current_speed > max_speed) {
27502 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27503 				return (EINVAL);
27504 			}
27505 		}
27506 
27507 		/*
27508 		 * Build and send the SET SPEED command
27509 		 *
27510 		 * Note: The SET SPEED (0xBB) command used in this routine is
27511 		 * obsolete per the SCSI MMC spec but still supported in the
27512 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27513 		 * therefore the command is still implemented in this routine.
27514 		 */
27515 		bzero(cdb, sizeof (cdb));
27516 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
27517 		cdb[2] = (uchar_t)(current_speed >> 8);
27518 		cdb[3] = (uchar_t)current_speed;
27519 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27520 		com->uscsi_cdb	   = (caddr_t)cdb;
27521 		com->uscsi_cdblen  = CDB_GROUP5;
27522 		com->uscsi_bufaddr = NULL;
27523 		com->uscsi_buflen  = 0;
27524 		com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
27525 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
27526 		break;
27527 	default:
27528 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27529 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
27530 		rval = EINVAL;
27531 	}
27532 
27533 	if (sense) {
27534 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27535 	}
27536 	if (com) {
27537 		kmem_free(com, sizeof (*com));
27538 	}
27539 	return (rval);
27540 }
27541 
27542 
27543 /*
27544  *    Function: sr_pause_resume()
27545  *
27546  * Description: This routine is the driver entry point for handling CD-ROM
27547  *		pause/resume ioctl requests. This only affects the audio play
27548  *		operation.
27549  *
27550  *   Arguments: dev - the device 'dev_t'
27551  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
27552  *		      for setting the resume bit of the cdb.
27553  *
27554  * Return Code: the code returned by sd_send_scsi_cmd()
27555  *		EINVAL if invalid mode specified
27556  *
27557  */
27558 
27559 static int
27560 sr_pause_resume(dev_t dev, int cmd)
27561 {
27562 	struct sd_lun		*un;
27563 	struct uscsi_cmd	*com;
27564 	char			cdb[CDB_GROUP1];
27565 	int			rval;
27566 
27567 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27568 		return (ENXIO);
27569 	}
27570 
27571 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27572 	bzero(cdb, CDB_GROUP1);
27573 	cdb[0] = SCMD_PAUSE_RESUME;
27574 	switch (cmd) {
27575 	case CDROMRESUME:
27576 		cdb[8] = 1;
27577 		break;
27578 	case CDROMPAUSE:
27579 		cdb[8] = 0;
27580 		break;
27581 	default:
27582 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
27583 		    " Command '%x' Not Supported\n", cmd);
27584 		rval = EINVAL;
27585 		goto done;
27586 	}
27587 
27588 	com->uscsi_cdb    = cdb;
27589 	com->uscsi_cdblen = CDB_GROUP1;
27590 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27591 
27592 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27593 	    SD_PATH_STANDARD);
27594 
27595 done:
27596 	kmem_free(com, sizeof (*com));
27597 	return (rval);
27598 }
27599 
27600 
27601 /*
27602  *    Function: sr_play_msf()
27603  *
27604  * Description: This routine is the driver entry point for handling CD-ROM
27605  *		ioctl requests to output the audio signals at the specified
27606  *		starting address and continue the audio play until the specified
27607  *		ending address (CDROMPLAYMSF) The address is in Minute Second
27608  *		Frame (MSF) format.
27609  *
27610  *   Arguments: dev	- the device 'dev_t'
27611  *		data	- pointer to user provided audio msf structure,
27612  *		          specifying start/end addresses.
27613  *		flag	- this argument is a pass through to ddi_copyxxx()
27614  *		          directly from the mode argument of ioctl().
27615  *
27616  * Return Code: the code returned by sd_send_scsi_cmd()
27617  *		EFAULT if ddi_copyxxx() fails
27618  *		ENXIO if fail ddi_get_soft_state
27619  *		EINVAL if data pointer is NULL
27620  */
27621 
27622 static int
27623 sr_play_msf(dev_t dev, caddr_t data, int flag)
27624 {
27625 	struct sd_lun		*un;
27626 	struct uscsi_cmd	*com;
27627 	struct cdrom_msf	msf_struct;
27628 	struct cdrom_msf	*msf = &msf_struct;
27629 	char			cdb[CDB_GROUP1];
27630 	int			rval;
27631 
27632 	if (data == NULL) {
27633 		return (EINVAL);
27634 	}
27635 
27636 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27637 		return (ENXIO);
27638 	}
27639 
27640 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
27641 		return (EFAULT);
27642 	}
27643 
27644 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27645 	bzero(cdb, CDB_GROUP1);
27646 	cdb[0] = SCMD_PLAYAUDIO_MSF;
27647 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
27648 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
27649 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
27650 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
27651 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
27652 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
27653 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
27654 	} else {
27655 		cdb[3] = msf->cdmsf_min0;
27656 		cdb[4] = msf->cdmsf_sec0;
27657 		cdb[5] = msf->cdmsf_frame0;
27658 		cdb[6] = msf->cdmsf_min1;
27659 		cdb[7] = msf->cdmsf_sec1;
27660 		cdb[8] = msf->cdmsf_frame1;
27661 	}
27662 	com->uscsi_cdb    = cdb;
27663 	com->uscsi_cdblen = CDB_GROUP1;
27664 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27665 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27666 	    SD_PATH_STANDARD);
27667 	kmem_free(com, sizeof (*com));
27668 	return (rval);
27669 }
27670 
27671 
27672 /*
27673  *    Function: sr_play_trkind()
27674  *
27675  * Description: This routine is the driver entry point for handling CD-ROM
27676  *		ioctl requests to output the audio signals at the specified
27677  *		starting address and continue the audio play until the specified
27678  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
27679  *		format.
27680  *
27681  *   Arguments: dev	- the device 'dev_t'
27682  *		data	- pointer to user provided audio track/index structure,
27683  *		          specifying start/end addresses.
27684  *		flag	- this argument is a pass through to ddi_copyxxx()
27685  *		          directly from the mode argument of ioctl().
27686  *
27687  * Return Code: the code returned by sd_send_scsi_cmd()
27688  *		EFAULT if ddi_copyxxx() fails
27689  *		ENXIO if fail ddi_get_soft_state
27690  *		EINVAL if data pointer is NULL
27691  */
27692 
27693 static int
27694 sr_play_trkind(dev_t dev, caddr_t data, int flag)
27695 {
27696 	struct cdrom_ti		ti_struct;
27697 	struct cdrom_ti		*ti = &ti_struct;
27698 	struct uscsi_cmd	*com = NULL;
27699 	char			cdb[CDB_GROUP1];
27700 	int			rval;
27701 
27702 	if (data == NULL) {
27703 		return (EINVAL);
27704 	}
27705 
27706 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
27707 		return (EFAULT);
27708 	}
27709 
27710 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27711 	bzero(cdb, CDB_GROUP1);
27712 	cdb[0] = SCMD_PLAYAUDIO_TI;
27713 	cdb[4] = ti->cdti_trk0;
27714 	cdb[5] = ti->cdti_ind0;
27715 	cdb[7] = ti->cdti_trk1;
27716 	cdb[8] = ti->cdti_ind1;
27717 	com->uscsi_cdb    = cdb;
27718 	com->uscsi_cdblen = CDB_GROUP1;
27719 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27720 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27721 	    SD_PATH_STANDARD);
27722 	kmem_free(com, sizeof (*com));
27723 	return (rval);
27724 }
27725 
27726 
27727 /*
27728  *    Function: sr_read_all_subcodes()
27729  *
27730  * Description: This routine is the driver entry point for handling CD-ROM
27731  *		ioctl requests to return raw subcode data while the target is
27732  *		playing audio (CDROMSUBCODE).
27733  *
27734  *   Arguments: dev	- the device 'dev_t'
27735  *		data	- pointer to user provided cdrom subcode structure,
27736  *		          specifying the transfer length and address.
27737  *		flag	- this argument is a pass through to ddi_copyxxx()
27738  *		          directly from the mode argument of ioctl().
27739  *
27740  * Return Code: the code returned by sd_send_scsi_cmd()
27741  *		EFAULT if ddi_copyxxx() fails
27742  *		ENXIO if fail ddi_get_soft_state
27743  *		EINVAL if data pointer is NULL
27744  */
27745 
27746 static int
27747 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
27748 {
27749 	struct sd_lun		*un = NULL;
27750 	struct uscsi_cmd	*com = NULL;
27751 	struct cdrom_subcode	*subcode = NULL;
27752 	int			rval;
27753 	size_t			buflen;
27754 	char			cdb[CDB_GROUP5];
27755 
27756 #ifdef _MULTI_DATAMODEL
27757 	/* To support ILP32 applications in an LP64 world */
27758 	struct cdrom_subcode32		cdrom_subcode32;
27759 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
27760 #endif
27761 	if (data == NULL) {
27762 		return (EINVAL);
27763 	}
27764 
27765 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27766 		return (ENXIO);
27767 	}
27768 
27769 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
27770 
27771 #ifdef _MULTI_DATAMODEL
27772 	switch (ddi_model_convert_from(flag & FMODELS)) {
27773 	case DDI_MODEL_ILP32:
27774 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
27775 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27776 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27777 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27778 			return (EFAULT);
27779 		}
27780 		/* Convert the ILP32 uscsi data from the application to LP64 */
27781 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
27782 		break;
27783 	case DDI_MODEL_NONE:
27784 		if (ddi_copyin(data, subcode,
27785 		    sizeof (struct cdrom_subcode), flag)) {
27786 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27787 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27788 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27789 			return (EFAULT);
27790 		}
27791 		break;
27792 	}
27793 #else /* ! _MULTI_DATAMODEL */
27794 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
27795 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27796 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
27797 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27798 		return (EFAULT);
27799 	}
27800 #endif /* _MULTI_DATAMODEL */
27801 
27802 	/*
27803 	 * Since MMC-2 expects max 3 bytes for length, check if the
27804 	 * length input is greater than 3 bytes
27805 	 */
27806 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
27807 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27808 		    "sr_read_all_subcodes: "
27809 		    "cdrom transfer length too large: %d (limit %d)\n",
27810 		    subcode->cdsc_length, 0xFFFFFF);
27811 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27812 		return (EINVAL);
27813 	}
27814 
27815 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
27816 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27817 	bzero(cdb, CDB_GROUP5);
27818 
27819 	if (un->un_f_mmc_cap == TRUE) {
27820 		cdb[0] = (char)SCMD_READ_CD;
27821 		cdb[2] = (char)0xff;
27822 		cdb[3] = (char)0xff;
27823 		cdb[4] = (char)0xff;
27824 		cdb[5] = (char)0xff;
27825 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27826 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27827 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
27828 		cdb[10] = 1;
27829 	} else {
27830 		/*
27831 		 * Note: A vendor specific command (0xDF) is being used here to
27832 		 * request a read of all subcodes.
27833 		 */
27834 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
27835 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
27836 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27837 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27838 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
27839 	}
27840 	com->uscsi_cdb	   = cdb;
27841 	com->uscsi_cdblen  = CDB_GROUP5;
27842 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
27843 	com->uscsi_buflen  = buflen;
27844 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
27845 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27846 	    SD_PATH_STANDARD);
27847 	kmem_free(subcode, sizeof (struct cdrom_subcode));
27848 	kmem_free(com, sizeof (*com));
27849 	return (rval);
27850 }
27851 
27852 
27853 /*
27854  *    Function: sr_read_subchannel()
27855  *
27856  * Description: This routine is the driver entry point for handling CD-ROM
27857  *		ioctl requests to return the Q sub-channel data of the CD
27858  *		current position block. (CDROMSUBCHNL) The data includes the
27859  *		track number, index number, absolute CD-ROM address (LBA or MSF
27860  *		format per the user) , track relative CD-ROM address (LBA or MSF
27861  *		format per the user), control data and audio status.
27862  *
27863  *   Arguments: dev	- the device 'dev_t'
27864  *		data	- pointer to user provided cdrom sub-channel structure
27865  *		flag	- this argument is a pass through to ddi_copyxxx()
27866  *		          directly from the mode argument of ioctl().
27867  *
27868  * Return Code: the code returned by sd_send_scsi_cmd()
27869  *		EFAULT if ddi_copyxxx() fails
27870  *		ENXIO if fail ddi_get_soft_state
27871  *		EINVAL if data pointer is NULL
27872  */
27873 
27874 static int
27875 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
27876 {
27877 	struct sd_lun		*un;
27878 	struct uscsi_cmd	*com;
27879 	struct cdrom_subchnl	subchanel;
27880 	struct cdrom_subchnl	*subchnl = &subchanel;
27881 	char			cdb[CDB_GROUP1];
27882 	caddr_t			buffer;
27883 	int			rval;
27884 
27885 	if (data == NULL) {
27886 		return (EINVAL);
27887 	}
27888 
27889 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27890 	    (un->un_state == SD_STATE_OFFLINE)) {
27891 		return (ENXIO);
27892 	}
27893 
27894 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
27895 		return (EFAULT);
27896 	}
27897 
27898 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
27899 	bzero(cdb, CDB_GROUP1);
27900 	cdb[0] = SCMD_READ_SUBCHANNEL;
27901 	/* Set the MSF bit based on the user requested address format */
27902 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
27903 	/*
27904 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
27905 	 * returned
27906 	 */
27907 	cdb[2] = 0x40;
27908 	/*
27909 	 * Set byte 3 to specify the return data format. A value of 0x01
27910 	 * indicates that the CD-ROM current position should be returned.
27911 	 */
27912 	cdb[3] = 0x01;
27913 	cdb[8] = 0x10;
27914 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27915 	com->uscsi_cdb	   = cdb;
27916 	com->uscsi_cdblen  = CDB_GROUP1;
27917 	com->uscsi_bufaddr = buffer;
27918 	com->uscsi_buflen  = 16;
27919 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
27920 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27921 	    SD_PATH_STANDARD);
27922 	if (rval != 0) {
27923 		kmem_free(buffer, 16);
27924 		kmem_free(com, sizeof (*com));
27925 		return (rval);
27926 	}
27927 
27928 	/* Process the returned Q sub-channel data */
27929 	subchnl->cdsc_audiostatus = buffer[1];
27930 	subchnl->cdsc_adr	= (buffer[5] & 0xF0) >> 4;
27931 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
27932 	subchnl->cdsc_trk	= buffer[6];
27933 	subchnl->cdsc_ind	= buffer[7];
27934 	if (subchnl->cdsc_format & CDROM_LBA) {
27935 		subchnl->cdsc_absaddr.lba =
27936 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27937 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27938 		subchnl->cdsc_reladdr.lba =
27939 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
27940 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
27941 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
27942 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
27943 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
27944 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
27945 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
27946 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
27947 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
27948 	} else {
27949 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
27950 		subchnl->cdsc_absaddr.msf.second = buffer[10];
27951 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
27952 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
27953 		subchnl->cdsc_reladdr.msf.second = buffer[14];
27954 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
27955 	}
27956 	kmem_free(buffer, 16);
27957 	kmem_free(com, sizeof (*com));
27958 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
27959 	    != 0) {
27960 		return (EFAULT);
27961 	}
27962 	return (rval);
27963 }
27964 
27965 
27966 /*
27967  *    Function: sr_read_tocentry()
27968  *
27969  * Description: This routine is the driver entry point for handling CD-ROM
27970  *		ioctl requests to read from the Table of Contents (TOC)
27971  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
27972  *		fields, the starting address (LBA or MSF format per the user)
27973  *		and the data mode if the user specified track is a data track.
27974  *
27975  *		Note: The READ HEADER (0x44) command used in this routine is
27976  *		obsolete per the SCSI MMC spec but still supported in the
27977  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27978  *		therefore the command is still implemented in this routine.
27979  *
27980  *   Arguments: dev	- the device 'dev_t'
27981  *		data	- pointer to user provided toc entry structure,
27982  *			  specifying the track # and the address format
27983  *			  (LBA or MSF).
27984  *		flag	- this argument is a pass through to ddi_copyxxx()
27985  *		          directly from the mode argument of ioctl().
27986  *
27987  * Return Code: the code returned by sd_send_scsi_cmd()
27988  *		EFAULT if ddi_copyxxx() fails
27989  *		ENXIO if fail ddi_get_soft_state
27990  *		EINVAL if data pointer is NULL
27991  */
27992 
27993 static int
27994 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
27995 {
27996 	struct sd_lun		*un = NULL;
27997 	struct uscsi_cmd	*com;
27998 	struct cdrom_tocentry	toc_entry;
27999 	struct cdrom_tocentry	*entry = &toc_entry;
28000 	caddr_t			buffer;
28001 	int			rval;
28002 	char			cdb[CDB_GROUP1];
28003 
28004 	if (data == NULL) {
28005 		return (EINVAL);
28006 	}
28007 
28008 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28009 	    (un->un_state == SD_STATE_OFFLINE)) {
28010 		return (ENXIO);
28011 	}
28012 
28013 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
28014 		return (EFAULT);
28015 	}
28016 
28017 	/* Validate the requested track and address format */
28018 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
28019 		return (EINVAL);
28020 	}
28021 
28022 	if (entry->cdte_track == 0) {
28023 		return (EINVAL);
28024 	}
28025 
28026 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
28027 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28028 	bzero(cdb, CDB_GROUP1);
28029 
28030 	cdb[0] = SCMD_READ_TOC;
28031 	/* Set the MSF bit based on the user requested address format  */
28032 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
28033 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
28034 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
28035 	} else {
28036 		cdb[6] = entry->cdte_track;
28037 	}
28038 
28039 	/*
28040 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
28041 	 * (4 byte TOC response header + 8 byte track descriptor)
28042 	 */
28043 	cdb[8] = 12;
28044 	com->uscsi_cdb	   = cdb;
28045 	com->uscsi_cdblen  = CDB_GROUP1;
28046 	com->uscsi_bufaddr = buffer;
28047 	com->uscsi_buflen  = 0x0C;
28048 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
28049 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28050 	    SD_PATH_STANDARD);
28051 	if (rval != 0) {
28052 		kmem_free(buffer, 12);
28053 		kmem_free(com, sizeof (*com));
28054 		return (rval);
28055 	}
28056 
28057 	/* Process the toc entry */
28058 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
28059 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
28060 	if (entry->cdte_format & CDROM_LBA) {
28061 		entry->cdte_addr.lba =
28062 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
28063 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
28064 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
28065 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
28066 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
28067 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
28068 		/*
28069 		 * Send a READ TOC command using the LBA address format to get
28070 		 * the LBA for the track requested so it can be used in the
28071 		 * READ HEADER request
28072 		 *
28073 		 * Note: The MSF bit of the READ HEADER command specifies the
28074 		 * output format. The block address specified in that command
28075 		 * must be in LBA format.
28076 		 */
28077 		cdb[1] = 0;
28078 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28079 		    SD_PATH_STANDARD);
28080 		if (rval != 0) {
28081 			kmem_free(buffer, 12);
28082 			kmem_free(com, sizeof (*com));
28083 			return (rval);
28084 		}
28085 	} else {
28086 		entry->cdte_addr.msf.minute	= buffer[9];
28087 		entry->cdte_addr.msf.second	= buffer[10];
28088 		entry->cdte_addr.msf.frame	= buffer[11];
28089 		/*
28090 		 * Send a READ TOC command using the LBA address format to get
28091 		 * the LBA for the track requested so it can be used in the
28092 		 * READ HEADER request
28093 		 *
28094 		 * Note: The MSF bit of the READ HEADER command specifies the
28095 		 * output format. The block address specified in that command
28096 		 * must be in LBA format.
28097 		 */
28098 		cdb[1] = 0;
28099 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28100 		    SD_PATH_STANDARD);
28101 		if (rval != 0) {
28102 			kmem_free(buffer, 12);
28103 			kmem_free(com, sizeof (*com));
28104 			return (rval);
28105 		}
28106 	}
28107 
28108 	/*
28109 	 * Build and send the READ HEADER command to determine the data mode of
28110 	 * the user specified track.
28111 	 */
28112 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
28113 	    (entry->cdte_track != CDROM_LEADOUT)) {
28114 		bzero(cdb, CDB_GROUP1);
28115 		cdb[0] = SCMD_READ_HEADER;
28116 		cdb[2] = buffer[8];
28117 		cdb[3] = buffer[9];
28118 		cdb[4] = buffer[10];
28119 		cdb[5] = buffer[11];
28120 		cdb[8] = 0x08;
28121 		com->uscsi_buflen = 0x08;
28122 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28123 		    SD_PATH_STANDARD);
28124 		if (rval == 0) {
28125 			entry->cdte_datamode = buffer[0];
28126 		} else {
28127 			/*
28128 			 * READ HEADER command failed, since this is
28129 			 * obsoleted in one spec, its better to return
28130 			 * -1 for an invlid track so that we can still
28131 			 * receive the rest of the TOC data.
28132 			 */
28133 			entry->cdte_datamode = (uchar_t)-1;
28134 		}
28135 	} else {
28136 		entry->cdte_datamode = (uchar_t)-1;
28137 	}
28138 
28139 	kmem_free(buffer, 12);
28140 	kmem_free(com, sizeof (*com));
28141 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
28142 		return (EFAULT);
28143 
28144 	return (rval);
28145 }
28146 
28147 
28148 /*
28149  *    Function: sr_read_tochdr()
28150  *
28151  * Description: This routine is the driver entry point for handling CD-ROM
28152  *		ioctl requests to read the Table of Contents (TOC) header
28153  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
28154  *		and ending track numbers
28155  *
28156  *   Arguments: dev	- the device 'dev_t'
28157  *		data	- pointer to user provided toc header structure,
28158  *			  specifying the starting and ending track numbers.
28159  *		flag	- this argument is a pass through to ddi_copyxxx()
28160  *			  directly from the mode argument of ioctl().
28161  *
28162  * Return Code: the code returned by sd_send_scsi_cmd()
28163  *		EFAULT if ddi_copyxxx() fails
28164  *		ENXIO if fail ddi_get_soft_state
28165  *		EINVAL if data pointer is NULL
28166  */
28167 
28168 static int
28169 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
28170 {
28171 	struct sd_lun		*un;
28172 	struct uscsi_cmd	*com;
28173 	struct cdrom_tochdr	toc_header;
28174 	struct cdrom_tochdr	*hdr = &toc_header;
28175 	char			cdb[CDB_GROUP1];
28176 	int			rval;
28177 	caddr_t			buffer;
28178 
28179 	if (data == NULL) {
28180 		return (EINVAL);
28181 	}
28182 
28183 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28184 	    (un->un_state == SD_STATE_OFFLINE)) {
28185 		return (ENXIO);
28186 	}
28187 
28188 	buffer = kmem_zalloc(4, KM_SLEEP);
28189 	bzero(cdb, CDB_GROUP1);
28190 	cdb[0] = SCMD_READ_TOC;
28191 	/*
28192 	 * Specifying a track number of 0x00 in the READ TOC command indicates
28193 	 * that the TOC header should be returned
28194 	 */
28195 	cdb[6] = 0x00;
28196 	/*
28197 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
28198 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
28199 	 */
28200 	cdb[8] = 0x04;
28201 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28202 	com->uscsi_cdb	   = cdb;
28203 	com->uscsi_cdblen  = CDB_GROUP1;
28204 	com->uscsi_bufaddr = buffer;
28205 	com->uscsi_buflen  = 0x04;
28206 	com->uscsi_timeout = 300;
28207 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28208 
28209 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28210 	    SD_PATH_STANDARD);
28211 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
28212 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
28213 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
28214 	} else {
28215 		hdr->cdth_trk0 = buffer[2];
28216 		hdr->cdth_trk1 = buffer[3];
28217 	}
28218 	kmem_free(buffer, 4);
28219 	kmem_free(com, sizeof (*com));
28220 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
28221 		return (EFAULT);
28222 	}
28223 	return (rval);
28224 }
28225 
28226 
28227 /*
28228  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
28229  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
28230  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
28231  * digital audio and extended architecture digital audio. These modes are
28232  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
28233  * MMC specs.
28234  *
28235  * In addition to support for the various data formats these routines also
28236  * include support for devices that implement only the direct access READ
28237  * commands (0x08, 0x28), devices that implement the READ_CD commands
28238  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
28239  * READ CDXA commands (0xD8, 0xDB)
28240  */
28241 
28242 /*
28243  *    Function: sr_read_mode1()
28244  *
28245  * Description: This routine is the driver entry point for handling CD-ROM
28246  *		ioctl read mode1 requests (CDROMREADMODE1).
28247  *
28248  *   Arguments: dev	- the device 'dev_t'
28249  *		data	- pointer to user provided cd read structure specifying
28250  *			  the lba buffer address and length.
28251  *		flag	- this argument is a pass through to ddi_copyxxx()
28252  *			  directly from the mode argument of ioctl().
28253  *
28254  * Return Code: the code returned by sd_send_scsi_cmd()
28255  *		EFAULT if ddi_copyxxx() fails
28256  *		ENXIO if fail ddi_get_soft_state
28257  *		EINVAL if data pointer is NULL
28258  */
28259 
28260 static int
28261 sr_read_mode1(dev_t dev, caddr_t data, int flag)
28262 {
28263 	struct sd_lun		*un;
28264 	struct cdrom_read	mode1_struct;
28265 	struct cdrom_read	*mode1 = &mode1_struct;
28266 	int			rval;
28267 	sd_ssc_t		*ssc;
28268 
28269 #ifdef _MULTI_DATAMODEL
28270 	/* To support ILP32 applications in an LP64 world */
28271 	struct cdrom_read32	cdrom_read32;
28272 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28273 #endif /* _MULTI_DATAMODEL */
28274 
28275 	if (data == NULL) {
28276 		return (EINVAL);
28277 	}
28278 
28279 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28280 	    (un->un_state == SD_STATE_OFFLINE)) {
28281 		return (ENXIO);
28282 	}
28283 
28284 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28285 	    "sd_read_mode1: entry: un:0x%p\n", un);
28286 
28287 #ifdef _MULTI_DATAMODEL
28288 	switch (ddi_model_convert_from(flag & FMODELS)) {
28289 	case DDI_MODEL_ILP32:
28290 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28291 			return (EFAULT);
28292 		}
28293 		/* Convert the ILP32 uscsi data from the application to LP64 */
28294 		cdrom_read32tocdrom_read(cdrd32, mode1);
28295 		break;
28296 	case DDI_MODEL_NONE:
28297 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28298 			return (EFAULT);
28299 		}
28300 	}
28301 #else /* ! _MULTI_DATAMODEL */
28302 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28303 		return (EFAULT);
28304 	}
28305 #endif /* _MULTI_DATAMODEL */
28306 
28307 	ssc = sd_ssc_init(un);
28308 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
28309 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
28310 	sd_ssc_fini(ssc);
28311 
28312 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28313 	    "sd_read_mode1: exit: un:0x%p\n", un);
28314 
28315 	return (rval);
28316 }
28317 
28318 
28319 /*
28320  *    Function: sr_read_cd_mode2()
28321  *
28322  * Description: This routine is the driver entry point for handling CD-ROM
28323  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28324  *		support the READ CD (0xBE) command or the 1st generation
28325  *		READ CD (0xD4) command.
28326  *
28327  *   Arguments: dev	- the device 'dev_t'
28328  *		data	- pointer to user provided cd read structure specifying
28329  *			  the lba buffer address and length.
28330  *		flag	- this argument is a pass through to ddi_copyxxx()
28331  *			  directly from the mode argument of ioctl().
28332  *
28333  * Return Code: the code returned by sd_send_scsi_cmd()
28334  *		EFAULT if ddi_copyxxx() fails
28335  *		ENXIO if fail ddi_get_soft_state
28336  *		EINVAL if data pointer is NULL
28337  */
28338 
28339 static int
28340 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
28341 {
28342 	struct sd_lun		*un;
28343 	struct uscsi_cmd	*com;
28344 	struct cdrom_read	mode2_struct;
28345 	struct cdrom_read	*mode2 = &mode2_struct;
28346 	uchar_t			cdb[CDB_GROUP5];
28347 	int			nblocks;
28348 	int			rval;
28349 #ifdef _MULTI_DATAMODEL
28350 	/*  To support ILP32 applications in an LP64 world */
28351 	struct cdrom_read32	cdrom_read32;
28352 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28353 #endif /* _MULTI_DATAMODEL */
28354 
28355 	if (data == NULL) {
28356 		return (EINVAL);
28357 	}
28358 
28359 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28360 	    (un->un_state == SD_STATE_OFFLINE)) {
28361 		return (ENXIO);
28362 	}
28363 
28364 #ifdef _MULTI_DATAMODEL
28365 	switch (ddi_model_convert_from(flag & FMODELS)) {
28366 	case DDI_MODEL_ILP32:
28367 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28368 			return (EFAULT);
28369 		}
28370 		/* Convert the ILP32 uscsi data from the application to LP64 */
28371 		cdrom_read32tocdrom_read(cdrd32, mode2);
28372 		break;
28373 	case DDI_MODEL_NONE:
28374 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28375 			return (EFAULT);
28376 		}
28377 		break;
28378 	}
28379 
28380 #else /* ! _MULTI_DATAMODEL */
28381 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28382 		return (EFAULT);
28383 	}
28384 #endif /* _MULTI_DATAMODEL */
28385 
28386 	bzero(cdb, sizeof (cdb));
28387 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
28388 		/* Read command supported by 1st generation atapi drives */
28389 		cdb[0] = SCMD_READ_CDD4;
28390 	} else {
28391 		/* Universal CD Access Command */
28392 		cdb[0] = SCMD_READ_CD;
28393 	}
28394 
28395 	/*
28396 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
28397 	 */
28398 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
28399 
28400 	/* set the start address */
28401 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
28402 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
28403 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28404 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
28405 
28406 	/* set the transfer length */
28407 	nblocks = mode2->cdread_buflen / 2336;
28408 	cdb[6] = (uchar_t)(nblocks >> 16);
28409 	cdb[7] = (uchar_t)(nblocks >> 8);
28410 	cdb[8] = (uchar_t)nblocks;
28411 
28412 	/* set the filter bits */
28413 	cdb[9] = CDROM_READ_CD_USERDATA;
28414 
28415 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28416 	com->uscsi_cdb = (caddr_t)cdb;
28417 	com->uscsi_cdblen = sizeof (cdb);
28418 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28419 	com->uscsi_buflen = mode2->cdread_buflen;
28420 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28421 
28422 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28423 	    SD_PATH_STANDARD);
28424 	kmem_free(com, sizeof (*com));
28425 	return (rval);
28426 }
28427 
28428 
28429 /*
28430  *    Function: sr_read_mode2()
28431  *
28432  * Description: This routine is the driver entry point for handling CD-ROM
28433  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28434  *		do not support the READ CD (0xBE) command.
28435  *
28436  *   Arguments: dev	- the device 'dev_t'
28437  *		data	- pointer to user provided cd read structure specifying
28438  *			  the lba buffer address and length.
28439  *		flag	- this argument is a pass through to ddi_copyxxx()
28440  *			  directly from the mode argument of ioctl().
28441  *
28442  * Return Code: the code returned by sd_send_scsi_cmd()
28443  *		EFAULT if ddi_copyxxx() fails
28444  *		ENXIO if fail ddi_get_soft_state
28445  *		EINVAL if data pointer is NULL
28446  *		EIO if fail to reset block size
28447  *		EAGAIN if commands are in progress in the driver
28448  */
28449 
28450 static int
28451 sr_read_mode2(dev_t dev, caddr_t data, int flag)
28452 {
28453 	struct sd_lun		*un;
28454 	struct cdrom_read	mode2_struct;
28455 	struct cdrom_read	*mode2 = &mode2_struct;
28456 	int			rval;
28457 	uint32_t		restore_blksize;
28458 	struct uscsi_cmd	*com;
28459 	uchar_t			cdb[CDB_GROUP0];
28460 	int			nblocks;
28461 
28462 #ifdef _MULTI_DATAMODEL
28463 	/* To support ILP32 applications in an LP64 world */
28464 	struct cdrom_read32	cdrom_read32;
28465 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28466 #endif /* _MULTI_DATAMODEL */
28467 
28468 	if (data == NULL) {
28469 		return (EINVAL);
28470 	}
28471 
28472 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28473 	    (un->un_state == SD_STATE_OFFLINE)) {
28474 		return (ENXIO);
28475 	}
28476 
28477 	/*
28478 	 * Because this routine will update the device and driver block size
28479 	 * being used we want to make sure there are no commands in progress.
28480 	 * If commands are in progress the user will have to try again.
28481 	 *
28482 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
28483 	 * in sdioctl to protect commands from sdioctl through to the top of
28484 	 * sd_uscsi_strategy. See sdioctl for details.
28485 	 */
28486 	mutex_enter(SD_MUTEX(un));
28487 	if (un->un_ncmds_in_driver != 1) {
28488 		mutex_exit(SD_MUTEX(un));
28489 		return (EAGAIN);
28490 	}
28491 	mutex_exit(SD_MUTEX(un));
28492 
28493 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28494 	    "sd_read_mode2: entry: un:0x%p\n", un);
28495 
28496 #ifdef _MULTI_DATAMODEL
28497 	switch (ddi_model_convert_from(flag & FMODELS)) {
28498 	case DDI_MODEL_ILP32:
28499 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28500 			return (EFAULT);
28501 		}
28502 		/* Convert the ILP32 uscsi data from the application to LP64 */
28503 		cdrom_read32tocdrom_read(cdrd32, mode2);
28504 		break;
28505 	case DDI_MODEL_NONE:
28506 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28507 			return (EFAULT);
28508 		}
28509 		break;
28510 	}
28511 #else /* ! _MULTI_DATAMODEL */
28512 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
28513 		return (EFAULT);
28514 	}
28515 #endif /* _MULTI_DATAMODEL */
28516 
28517 	/* Store the current target block size for restoration later */
28518 	restore_blksize = un->un_tgt_blocksize;
28519 
28520 	/* Change the device and soft state target block size to 2336 */
28521 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
28522 		rval = EIO;
28523 		goto done;
28524 	}
28525 
28526 
28527 	bzero(cdb, sizeof (cdb));
28528 
28529 	/* set READ operation */
28530 	cdb[0] = SCMD_READ;
28531 
28532 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
28533 	mode2->cdread_lba >>= 2;
28534 
28535 	/* set the start address */
28536 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
28537 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28538 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
28539 
28540 	/* set the transfer length */
28541 	nblocks = mode2->cdread_buflen / 2336;
28542 	cdb[4] = (uchar_t)nblocks & 0xFF;
28543 
28544 	/* build command */
28545 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28546 	com->uscsi_cdb = (caddr_t)cdb;
28547 	com->uscsi_cdblen = sizeof (cdb);
28548 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28549 	com->uscsi_buflen = mode2->cdread_buflen;
28550 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28551 
28552 	/*
28553 	 * Issue SCSI command with user space address for read buffer.
28554 	 *
28555 	 * This sends the command through main channel in the driver.
28556 	 *
28557 	 * Since this is accessed via an IOCTL call, we go through the
28558 	 * standard path, so that if the device was powered down, then
28559 	 * it would be 'awakened' to handle the command.
28560 	 */
28561 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28562 	    SD_PATH_STANDARD);
28563 
28564 	kmem_free(com, sizeof (*com));
28565 
28566 	/* Restore the device and soft state target block size */
28567 	if (sr_sector_mode(dev, restore_blksize) != 0) {
28568 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28569 		    "can't do switch back to mode 1\n");
28570 		/*
28571 		 * If sd_send_scsi_READ succeeded we still need to report
28572 		 * an error because we failed to reset the block size
28573 		 */
28574 		if (rval == 0) {
28575 			rval = EIO;
28576 		}
28577 	}
28578 
28579 done:
28580 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28581 	    "sd_read_mode2: exit: un:0x%p\n", un);
28582 
28583 	return (rval);
28584 }
28585 
28586 
28587 /*
28588  *    Function: sr_sector_mode()
28589  *
28590  * Description: This utility function is used by sr_read_mode2 to set the target
28591  *		block size based on the user specified size. This is a legacy
28592  *		implementation based upon a vendor specific mode page
28593  *
28594  *   Arguments: dev	- the device 'dev_t'
28595  *		data	- flag indicating if block size is being set to 2336 or
28596  *			  512.
28597  *
28598  * Return Code: the code returned by sd_send_scsi_cmd()
28599  *		EFAULT if ddi_copyxxx() fails
28600  *		ENXIO if fail ddi_get_soft_state
28601  *		EINVAL if data pointer is NULL
28602  */
28603 
28604 static int
28605 sr_sector_mode(dev_t dev, uint32_t blksize)
28606 {
28607 	struct sd_lun	*un;
28608 	uchar_t		*sense;
28609 	uchar_t		*select;
28610 	int		rval;
28611 	sd_ssc_t	*ssc;
28612 
28613 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28614 	    (un->un_state == SD_STATE_OFFLINE)) {
28615 		return (ENXIO);
28616 	}
28617 
28618 	sense = kmem_zalloc(20, KM_SLEEP);
28619 
28620 	/* Note: This is a vendor specific mode page (0x81) */
28621 	ssc = sd_ssc_init(un);
28622 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
28623 	    SD_PATH_STANDARD);
28624 	sd_ssc_fini(ssc);
28625 	if (rval != 0) {
28626 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28627 		    "sr_sector_mode: Mode Sense failed\n");
28628 		kmem_free(sense, 20);
28629 		return (rval);
28630 	}
28631 	select = kmem_zalloc(20, KM_SLEEP);
28632 	select[3] = 0x08;
28633 	select[10] = ((blksize >> 8) & 0xff);
28634 	select[11] = (blksize & 0xff);
28635 	select[12] = 0x01;
28636 	select[13] = 0x06;
28637 	select[14] = sense[14];
28638 	select[15] = sense[15];
28639 	if (blksize == SD_MODE2_BLKSIZE) {
28640 		select[14] |= 0x01;
28641 	}
28642 
28643 	ssc = sd_ssc_init(un);
28644 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
28645 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28646 	sd_ssc_fini(ssc);
28647 	if (rval != 0) {
28648 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28649 		    "sr_sector_mode: Mode Select failed\n");
28650 	} else {
28651 		/*
28652 		 * Only update the softstate block size if we successfully
28653 		 * changed the device block mode.
28654 		 */
28655 		mutex_enter(SD_MUTEX(un));
28656 		sd_update_block_info(un, blksize, 0);
28657 		mutex_exit(SD_MUTEX(un));
28658 	}
28659 	kmem_free(sense, 20);
28660 	kmem_free(select, 20);
28661 	return (rval);
28662 }
28663 
28664 
28665 /*
28666  *    Function: sr_read_cdda()
28667  *
28668  * Description: This routine is the driver entry point for handling CD-ROM
28669  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
28670  *		the target supports CDDA these requests are handled via a vendor
28671  *		specific command (0xD8) If the target does not support CDDA
28672  *		these requests are handled via the READ CD command (0xBE).
28673  *
28674  *   Arguments: dev	- the device 'dev_t'
28675  *		data	- pointer to user provided CD-DA structure specifying
28676  *			  the track starting address, transfer length, and
28677  *			  subcode options.
28678  *		flag	- this argument is a pass through to ddi_copyxxx()
28679  *			  directly from the mode argument of ioctl().
28680  *
28681  * Return Code: the code returned by sd_send_scsi_cmd()
28682  *		EFAULT if ddi_copyxxx() fails
28683  *		ENXIO if fail ddi_get_soft_state
28684  *		EINVAL if invalid arguments are provided
28685  *		ENOTTY
28686  */
28687 
28688 static int
28689 sr_read_cdda(dev_t dev, caddr_t data, int flag)
28690 {
28691 	struct sd_lun			*un;
28692 	struct uscsi_cmd		*com;
28693 	struct cdrom_cdda		*cdda;
28694 	int				rval;
28695 	size_t				buflen;
28696 	char				cdb[CDB_GROUP5];
28697 
28698 #ifdef _MULTI_DATAMODEL
28699 	/* To support ILP32 applications in an LP64 world */
28700 	struct cdrom_cdda32	cdrom_cdda32;
28701 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
28702 #endif /* _MULTI_DATAMODEL */
28703 
28704 	if (data == NULL) {
28705 		return (EINVAL);
28706 	}
28707 
28708 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28709 		return (ENXIO);
28710 	}
28711 
28712 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
28713 
28714 #ifdef _MULTI_DATAMODEL
28715 	switch (ddi_model_convert_from(flag & FMODELS)) {
28716 	case DDI_MODEL_ILP32:
28717 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
28718 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28719 			    "sr_read_cdda: ddi_copyin Failed\n");
28720 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28721 			return (EFAULT);
28722 		}
28723 		/* Convert the ILP32 uscsi data from the application to LP64 */
28724 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
28725 		break;
28726 	case DDI_MODEL_NONE:
28727 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28728 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28729 			    "sr_read_cdda: ddi_copyin Failed\n");
28730 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28731 			return (EFAULT);
28732 		}
28733 		break;
28734 	}
28735 #else /* ! _MULTI_DATAMODEL */
28736 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28737 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28738 		    "sr_read_cdda: ddi_copyin Failed\n");
28739 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28740 		return (EFAULT);
28741 	}
28742 #endif /* _MULTI_DATAMODEL */
28743 
28744 	/*
28745 	 * Since MMC-2 expects max 3 bytes for length, check if the
28746 	 * length input is greater than 3 bytes
28747 	 */
28748 	if ((cdda->cdda_length & 0xFF000000) != 0) {
28749 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
28750 		    "cdrom transfer length too large: %d (limit %d)\n",
28751 		    cdda->cdda_length, 0xFFFFFF);
28752 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28753 		return (EINVAL);
28754 	}
28755 
28756 	switch (cdda->cdda_subcode) {
28757 	case CDROM_DA_NO_SUBCODE:
28758 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
28759 		break;
28760 	case CDROM_DA_SUBQ:
28761 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
28762 		break;
28763 	case CDROM_DA_ALL_SUBCODE:
28764 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
28765 		break;
28766 	case CDROM_DA_SUBCODE_ONLY:
28767 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
28768 		break;
28769 	default:
28770 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28771 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
28772 		    cdda->cdda_subcode);
28773 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28774 		return (EINVAL);
28775 	}
28776 
28777 	/* Build and send the command */
28778 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28779 	bzero(cdb, CDB_GROUP5);
28780 
28781 	if (un->un_f_cfg_cdda == TRUE) {
28782 		cdb[0] = (char)SCMD_READ_CD;
28783 		cdb[1] = 0x04;
28784 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28785 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28786 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28787 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28788 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28789 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28790 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
28791 		cdb[9] = 0x10;
28792 		switch (cdda->cdda_subcode) {
28793 		case CDROM_DA_NO_SUBCODE :
28794 			cdb[10] = 0x0;
28795 			break;
28796 		case CDROM_DA_SUBQ :
28797 			cdb[10] = 0x2;
28798 			break;
28799 		case CDROM_DA_ALL_SUBCODE :
28800 			cdb[10] = 0x1;
28801 			break;
28802 		case CDROM_DA_SUBCODE_ONLY :
28803 			/* FALLTHROUGH */
28804 		default :
28805 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28806 			kmem_free(com, sizeof (*com));
28807 			return (ENOTTY);
28808 		}
28809 	} else {
28810 		cdb[0] = (char)SCMD_READ_CDDA;
28811 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28812 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28813 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28814 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28815 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
28816 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28817 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28818 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
28819 		cdb[10] = cdda->cdda_subcode;
28820 	}
28821 
28822 	com->uscsi_cdb = cdb;
28823 	com->uscsi_cdblen = CDB_GROUP5;
28824 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
28825 	com->uscsi_buflen = buflen;
28826 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28827 
28828 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28829 	    SD_PATH_STANDARD);
28830 
28831 	kmem_free(cdda, sizeof (struct cdrom_cdda));
28832 	kmem_free(com, sizeof (*com));
28833 	return (rval);
28834 }
28835 
28836 
28837 /*
28838  *    Function: sr_read_cdxa()
28839  *
28840  * Description: This routine is the driver entry point for handling CD-ROM
28841  *		ioctl requests to return CD-XA (Extended Architecture) data.
28842  *		(CDROMCDXA).
28843  *
28844  *   Arguments: dev	- the device 'dev_t'
28845  *		data	- pointer to user provided CD-XA structure specifying
28846  *			  the data starting address, transfer length, and format
28847  *		flag	- this argument is a pass through to ddi_copyxxx()
28848  *			  directly from the mode argument of ioctl().
28849  *
28850  * Return Code: the code returned by sd_send_scsi_cmd()
28851  *		EFAULT if ddi_copyxxx() fails
28852  *		ENXIO if fail ddi_get_soft_state
28853  *		EINVAL if data pointer is NULL
28854  */
28855 
28856 static int
28857 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
28858 {
28859 	struct sd_lun		*un;
28860 	struct uscsi_cmd	*com;
28861 	struct cdrom_cdxa	*cdxa;
28862 	int			rval;
28863 	size_t			buflen;
28864 	char			cdb[CDB_GROUP5];
28865 	uchar_t			read_flags;
28866 
28867 #ifdef _MULTI_DATAMODEL
28868 	/* To support ILP32 applications in an LP64 world */
28869 	struct cdrom_cdxa32		cdrom_cdxa32;
28870 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
28871 #endif /* _MULTI_DATAMODEL */
28872 
28873 	if (data == NULL) {
28874 		return (EINVAL);
28875 	}
28876 
28877 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28878 		return (ENXIO);
28879 	}
28880 
28881 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
28882 
28883 #ifdef _MULTI_DATAMODEL
28884 	switch (ddi_model_convert_from(flag & FMODELS)) {
28885 	case DDI_MODEL_ILP32:
28886 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
28887 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28888 			return (EFAULT);
28889 		}
28890 		/*
28891 		 * Convert the ILP32 uscsi data from the
28892 		 * application to LP64 for internal use.
28893 		 */
28894 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
28895 		break;
28896 	case DDI_MODEL_NONE:
28897 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28898 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28899 			return (EFAULT);
28900 		}
28901 		break;
28902 	}
28903 #else /* ! _MULTI_DATAMODEL */
28904 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28905 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28906 		return (EFAULT);
28907 	}
28908 #endif /* _MULTI_DATAMODEL */
28909 
28910 	/*
28911 	 * Since MMC-2 expects max 3 bytes for length, check if the
28912 	 * length input is greater than 3 bytes
28913 	 */
28914 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
28915 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
28916 		    "cdrom transfer length too large: %d (limit %d)\n",
28917 		    cdxa->cdxa_length, 0xFFFFFF);
28918 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28919 		return (EINVAL);
28920 	}
28921 
28922 	switch (cdxa->cdxa_format) {
28923 	case CDROM_XA_DATA:
28924 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
28925 		read_flags = 0x10;
28926 		break;
28927 	case CDROM_XA_SECTOR_DATA:
28928 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
28929 		read_flags = 0xf8;
28930 		break;
28931 	case CDROM_XA_DATA_W_ERROR:
28932 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
28933 		read_flags = 0xfc;
28934 		break;
28935 	default:
28936 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28937 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
28938 		    cdxa->cdxa_format);
28939 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28940 		return (EINVAL);
28941 	}
28942 
28943 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28944 	bzero(cdb, CDB_GROUP5);
28945 	if (un->un_f_mmc_cap == TRUE) {
28946 		cdb[0] = (char)SCMD_READ_CD;
28947 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28948 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28949 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28950 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28951 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28952 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28953 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
28954 		cdb[9] = (char)read_flags;
28955 	} else {
28956 		/*
28957 		 * Note: A vendor specific command (0xDB) is being used her to
28958 		 * request a read of all subcodes.
28959 		 */
28960 		cdb[0] = (char)SCMD_READ_CDXA;
28961 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28962 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28963 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28964 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28965 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
28966 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28967 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28968 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
28969 		cdb[10] = cdxa->cdxa_format;
28970 	}
28971 	com->uscsi_cdb	   = cdb;
28972 	com->uscsi_cdblen  = CDB_GROUP5;
28973 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
28974 	com->uscsi_buflen  = buflen;
28975 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28976 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28977 	    SD_PATH_STANDARD);
28978 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28979 	kmem_free(com, sizeof (*com));
28980 	return (rval);
28981 }
28982 
28983 
28984 /*
28985  *    Function: sr_eject()
28986  *
28987  * Description: This routine is the driver entry point for handling CD-ROM
28988  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
28989  *
28990  *   Arguments: dev	- the device 'dev_t'
28991  *
28992  * Return Code: the code returned by sd_send_scsi_cmd()
28993  */
28994 
28995 static int
28996 sr_eject(dev_t dev)
28997 {
28998 	struct sd_lun	*un;
28999 	int		rval;
29000 	sd_ssc_t	*ssc;
29001 
29002 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29003 	    (un->un_state == SD_STATE_OFFLINE)) {
29004 		return (ENXIO);
29005 	}
29006 
29007 	/*
29008 	 * To prevent race conditions with the eject
29009 	 * command, keep track of an eject command as
29010 	 * it progresses. If we are already handling
29011 	 * an eject command in the driver for the given
29012 	 * unit and another request to eject is received
29013 	 * immediately return EAGAIN so we don't lose
29014 	 * the command if the current eject command fails.
29015 	 */
29016 	mutex_enter(SD_MUTEX(un));
29017 	if (un->un_f_ejecting == TRUE) {
29018 		mutex_exit(SD_MUTEX(un));
29019 		return (EAGAIN);
29020 	}
29021 	un->un_f_ejecting = TRUE;
29022 	mutex_exit(SD_MUTEX(un));
29023 
29024 	ssc = sd_ssc_init(un);
29025 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
29026 	    SD_PATH_STANDARD);
29027 	sd_ssc_fini(ssc);
29028 
29029 	if (rval != 0) {
29030 		mutex_enter(SD_MUTEX(un));
29031 		un->un_f_ejecting = FALSE;
29032 		mutex_exit(SD_MUTEX(un));
29033 		return (rval);
29034 	}
29035 
29036 	ssc = sd_ssc_init(un);
29037 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
29038 	    SD_TARGET_EJECT, SD_PATH_STANDARD);
29039 	sd_ssc_fini(ssc);
29040 
29041 	if (rval == 0) {
29042 		mutex_enter(SD_MUTEX(un));
29043 		sr_ejected(un);
29044 		un->un_mediastate = DKIO_EJECTED;
29045 		un->un_f_ejecting = FALSE;
29046 		cv_broadcast(&un->un_state_cv);
29047 		mutex_exit(SD_MUTEX(un));
29048 	} else {
29049 		mutex_enter(SD_MUTEX(un));
29050 		un->un_f_ejecting = FALSE;
29051 		mutex_exit(SD_MUTEX(un));
29052 	}
29053 	return (rval);
29054 }
29055 
29056 
29057 /*
29058  *    Function: sr_ejected()
29059  *
29060  * Description: This routine updates the soft state structure to invalidate the
29061  *		geometry information after the media has been ejected or a
29062  *		media eject has been detected.
29063  *
29064  *   Arguments: un - driver soft state (unit) structure
29065  */
29066 
29067 static void
29068 sr_ejected(struct sd_lun *un)
29069 {
29070 	struct sd_errstats *stp;
29071 
29072 	ASSERT(un != NULL);
29073 	ASSERT(mutex_owned(SD_MUTEX(un)));
29074 
29075 	un->un_f_blockcount_is_valid	= FALSE;
29076 	un->un_f_tgt_blocksize_is_valid	= FALSE;
29077 	mutex_exit(SD_MUTEX(un));
29078 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
29079 	mutex_enter(SD_MUTEX(un));
29080 
29081 	if (un->un_errstats != NULL) {
29082 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
29083 		stp->sd_capacity.value.ui64 = 0;
29084 	}
29085 }
29086 
29087 
29088 /*
29089  *    Function: sr_check_wp()
29090  *
29091  * Description: This routine checks the write protection of a removable
29092  *      media disk and hotpluggable devices via the write protect bit of
29093  *      the Mode Page Header device specific field. Some devices choke
29094  *      on unsupported mode page. In order to workaround this issue,
29095  *      this routine has been implemented to use 0x3f mode page(request
29096  *      for all pages) for all device types.
29097  *
29098  *   Arguments: dev             - the device 'dev_t'
29099  *
29100  * Return Code: int indicating if the device is write protected (1) or not (0)
29101  *
29102  *     Context: Kernel thread.
29103  *
29104  */
29105 
29106 static int
29107 sr_check_wp(dev_t dev)
29108 {
29109 	struct sd_lun	*un;
29110 	uchar_t		device_specific;
29111 	uchar_t		*sense;
29112 	int		hdrlen;
29113 	int		rval = FALSE;
29114 	int		status;
29115 	sd_ssc_t	*ssc;
29116 
29117 	/*
29118 	 * Note: The return codes for this routine should be reworked to
29119 	 * properly handle the case of a NULL softstate.
29120 	 */
29121 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
29122 		return (FALSE);
29123 	}
29124 
29125 	if (un->un_f_cfg_is_atapi == TRUE) {
29126 		/*
29127 		 * The mode page contents are not required; set the allocation
29128 		 * length for the mode page header only
29129 		 */
29130 		hdrlen = MODE_HEADER_LENGTH_GRP2;
29131 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29132 		ssc = sd_ssc_init(un);
29133 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
29134 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
29135 		sd_ssc_fini(ssc);
29136 		if (status != 0)
29137 			goto err_exit;
29138 		device_specific =
29139 		    ((struct mode_header_grp2 *)sense)->device_specific;
29140 	} else {
29141 		hdrlen = MODE_HEADER_LENGTH;
29142 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29143 		ssc = sd_ssc_init(un);
29144 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
29145 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
29146 		sd_ssc_fini(ssc);
29147 		if (status != 0)
29148 			goto err_exit;
29149 		device_specific =
29150 		    ((struct mode_header *)sense)->device_specific;
29151 	}
29152 
29153 
29154 	/*
29155 	 * Write protect mode sense failed; not all disks
29156 	 * understand this query. Return FALSE assuming that
29157 	 * these devices are not writable.
29158 	 */
29159 	if (device_specific & WRITE_PROTECT) {
29160 		rval = TRUE;
29161 	}
29162 
29163 err_exit:
29164 	kmem_free(sense, hdrlen);
29165 	return (rval);
29166 }
29167 
29168 /*
29169  *    Function: sr_volume_ctrl()
29170  *
29171  * Description: This routine is the driver entry point for handling CD-ROM
29172  *		audio output volume ioctl requests. (CDROMVOLCTRL)
29173  *
29174  *   Arguments: dev	- the device 'dev_t'
29175  *		data	- pointer to user audio volume control structure
29176  *		flag	- this argument is a pass through to ddi_copyxxx()
29177  *			  directly from the mode argument of ioctl().
29178  *
29179  * Return Code: the code returned by sd_send_scsi_cmd()
29180  *		EFAULT if ddi_copyxxx() fails
29181  *		ENXIO if fail ddi_get_soft_state
29182  *		EINVAL if data pointer is NULL
29183  *
29184  */
29185 
29186 static int
29187 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
29188 {
29189 	struct sd_lun		*un;
29190 	struct cdrom_volctrl    volume;
29191 	struct cdrom_volctrl    *vol = &volume;
29192 	uchar_t			*sense_page;
29193 	uchar_t			*select_page;
29194 	uchar_t			*sense;
29195 	uchar_t			*select;
29196 	int			sense_buflen;
29197 	int			select_buflen;
29198 	int			rval;
29199 	sd_ssc_t		*ssc;
29200 
29201 	if (data == NULL) {
29202 		return (EINVAL);
29203 	}
29204 
29205 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29206 	    (un->un_state == SD_STATE_OFFLINE)) {
29207 		return (ENXIO);
29208 	}
29209 
29210 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
29211 		return (EFAULT);
29212 	}
29213 
29214 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29215 		struct mode_header_grp2		*sense_mhp;
29216 		struct mode_header_grp2		*select_mhp;
29217 		int				bd_len;
29218 
29219 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
29220 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
29221 		    MODEPAGE_AUDIO_CTRL_LEN;
29222 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29223 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29224 		ssc = sd_ssc_init(un);
29225 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
29226 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29227 		    SD_PATH_STANDARD);
29228 		sd_ssc_fini(ssc);
29229 
29230 		if (rval != 0) {
29231 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
29232 			    "sr_volume_ctrl: Mode Sense Failed\n");
29233 			kmem_free(sense, sense_buflen);
29234 			kmem_free(select, select_buflen);
29235 			return (rval);
29236 		}
29237 		sense_mhp = (struct mode_header_grp2 *)sense;
29238 		select_mhp = (struct mode_header_grp2 *)select;
29239 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
29240 		    sense_mhp->bdesc_length_lo;
29241 		if (bd_len > MODE_BLK_DESC_LENGTH) {
29242 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29243 			    "sr_volume_ctrl: Mode Sense returned invalid "
29244 			    "block descriptor length\n");
29245 			kmem_free(sense, sense_buflen);
29246 			kmem_free(select, select_buflen);
29247 			return (EIO);
29248 		}
29249 		sense_page = (uchar_t *)
29250 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
29251 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
29252 		select_mhp->length_msb = 0;
29253 		select_mhp->length_lsb = 0;
29254 		select_mhp->bdesc_length_hi = 0;
29255 		select_mhp->bdesc_length_lo = 0;
29256 	} else {
29257 		struct mode_header		*sense_mhp, *select_mhp;
29258 
29259 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29260 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29261 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29262 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29263 		ssc = sd_ssc_init(un);
29264 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
29265 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29266 		    SD_PATH_STANDARD);
29267 		sd_ssc_fini(ssc);
29268 
29269 		if (rval != 0) {
29270 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29271 			    "sr_volume_ctrl: Mode Sense Failed\n");
29272 			kmem_free(sense, sense_buflen);
29273 			kmem_free(select, select_buflen);
29274 			return (rval);
29275 		}
29276 		sense_mhp  = (struct mode_header *)sense;
29277 		select_mhp = (struct mode_header *)select;
29278 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
29279 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29280 			    "sr_volume_ctrl: Mode Sense returned invalid "
29281 			    "block descriptor length\n");
29282 			kmem_free(sense, sense_buflen);
29283 			kmem_free(select, select_buflen);
29284 			return (EIO);
29285 		}
29286 		sense_page = (uchar_t *)
29287 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
29288 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
29289 		select_mhp->length = 0;
29290 		select_mhp->bdesc_length = 0;
29291 	}
29292 	/*
29293 	 * Note: An audio control data structure could be created and overlayed
29294 	 * on the following in place of the array indexing method implemented.
29295 	 */
29296 
29297 	/* Build the select data for the user volume data */
29298 	select_page[0] = MODEPAGE_AUDIO_CTRL;
29299 	select_page[1] = 0xE;
29300 	/* Set the immediate bit */
29301 	select_page[2] = 0x04;
29302 	/* Zero out reserved fields */
29303 	select_page[3] = 0x00;
29304 	select_page[4] = 0x00;
29305 	/* Return sense data for fields not to be modified */
29306 	select_page[5] = sense_page[5];
29307 	select_page[6] = sense_page[6];
29308 	select_page[7] = sense_page[7];
29309 	/* Set the user specified volume levels for channel 0 and 1 */
29310 	select_page[8] = 0x01;
29311 	select_page[9] = vol->channel0;
29312 	select_page[10] = 0x02;
29313 	select_page[11] = vol->channel1;
29314 	/* Channel 2 and 3 are currently unsupported so return the sense data */
29315 	select_page[12] = sense_page[12];
29316 	select_page[13] = sense_page[13];
29317 	select_page[14] = sense_page[14];
29318 	select_page[15] = sense_page[15];
29319 
29320 	ssc = sd_ssc_init(un);
29321 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29322 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
29323 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29324 	} else {
29325 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
29326 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29327 	}
29328 	sd_ssc_fini(ssc);
29329 
29330 	kmem_free(sense, sense_buflen);
29331 	kmem_free(select, select_buflen);
29332 	return (rval);
29333 }
29334 
29335 
29336 /*
29337  *    Function: sr_read_sony_session_offset()
29338  *
29339  * Description: This routine is the driver entry point for handling CD-ROM
29340  *		ioctl requests for session offset information. (CDROMREADOFFSET)
29341  *		The address of the first track in the last session of a
29342  *		multi-session CD-ROM is returned
29343  *
29344  *		Note: This routine uses a vendor specific key value in the
29345  *		command control field without implementing any vendor check here
29346  *		or in the ioctl routine.
29347  *
29348  *   Arguments: dev	- the device 'dev_t'
29349  *		data	- pointer to an int to hold the requested address
29350  *		flag	- this argument is a pass through to ddi_copyxxx()
29351  *			  directly from the mode argument of ioctl().
29352  *
29353  * Return Code: the code returned by sd_send_scsi_cmd()
29354  *		EFAULT if ddi_copyxxx() fails
29355  *		ENXIO if fail ddi_get_soft_state
29356  *		EINVAL if data pointer is NULL
29357  */
29358 
29359 static int
29360 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
29361 {
29362 	struct sd_lun		*un;
29363 	struct uscsi_cmd	*com;
29364 	caddr_t			buffer;
29365 	char			cdb[CDB_GROUP1];
29366 	int			session_offset = 0;
29367 	int			rval;
29368 
29369 	if (data == NULL) {
29370 		return (EINVAL);
29371 	}
29372 
29373 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29374 	    (un->un_state == SD_STATE_OFFLINE)) {
29375 		return (ENXIO);
29376 	}
29377 
29378 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
29379 	bzero(cdb, CDB_GROUP1);
29380 	cdb[0] = SCMD_READ_TOC;
29381 	/*
29382 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
29383 	 * (4 byte TOC response header + 8 byte response data)
29384 	 */
29385 	cdb[8] = SONY_SESSION_OFFSET_LEN;
29386 	/* Byte 9 is the control byte. A vendor specific value is used */
29387 	cdb[9] = SONY_SESSION_OFFSET_KEY;
29388 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
29389 	com->uscsi_cdb = cdb;
29390 	com->uscsi_cdblen = CDB_GROUP1;
29391 	com->uscsi_bufaddr = buffer;
29392 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
29393 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
29394 
29395 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
29396 	    SD_PATH_STANDARD);
29397 	if (rval != 0) {
29398 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29399 		kmem_free(com, sizeof (*com));
29400 		return (rval);
29401 	}
29402 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
29403 		session_offset =
29404 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
29405 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
29406 		/*
29407 		 * Offset returned offset in current lbasize block's. Convert to
29408 		 * 2k block's to return to the user
29409 		 */
29410 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
29411 			session_offset >>= 2;
29412 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
29413 			session_offset >>= 1;
29414 		}
29415 	}
29416 
29417 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
29418 		rval = EFAULT;
29419 	}
29420 
29421 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29422 	kmem_free(com, sizeof (*com));
29423 	return (rval);
29424 }
29425 
29426 
29427 /*
29428  *    Function: sd_wm_cache_constructor()
29429  *
29430  * Description: Cache Constructor for the wmap cache for the read/modify/write
29431  *		devices.
29432  *
29433  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29434  *		un	- sd_lun structure for the device.
29435  *		flag	- the km flags passed to constructor
29436  *
29437  * Return Code: 0 on success.
29438  *		-1 on failure.
29439  */
29440 
29441 /*ARGSUSED*/
29442 static int
29443 sd_wm_cache_constructor(void *wm, void *un, int flags)
29444 {
29445 	bzero(wm, sizeof (struct sd_w_map));
29446 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
29447 	return (0);
29448 }
29449 
29450 
29451 /*
29452  *    Function: sd_wm_cache_destructor()
29453  *
29454  * Description: Cache destructor for the wmap cache for the read/modify/write
29455  *		devices.
29456  *
29457  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29458  *		un	- sd_lun structure for the device.
29459  */
29460 /*ARGSUSED*/
29461 static void
29462 sd_wm_cache_destructor(void *wm, void *un)
29463 {
29464 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
29465 }
29466 
29467 
29468 /*
29469  *    Function: sd_range_lock()
29470  *
29471  * Description: Lock the range of blocks specified as parameter to ensure
29472  *		that read, modify write is atomic and no other i/o writes
29473  *		to the same location. The range is specified in terms
29474  *		of start and end blocks. Block numbers are the actual
29475  *		media block numbers and not system.
29476  *
29477  *   Arguments: un	- sd_lun structure for the device.
29478  *		startb - The starting block number
29479  *		endb - The end block number
29480  *		typ - type of i/o - simple/read_modify_write
29481  *
29482  * Return Code: wm  - pointer to the wmap structure.
29483  *
29484  *     Context: This routine can sleep.
29485  */
29486 
29487 static struct sd_w_map *
29488 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
29489 {
29490 	struct sd_w_map *wmp = NULL;
29491 	struct sd_w_map *sl_wmp = NULL;
29492 	struct sd_w_map *tmp_wmp;
29493 	wm_state state = SD_WM_CHK_LIST;
29494 
29495 
29496 	ASSERT(un != NULL);
29497 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29498 
29499 	mutex_enter(SD_MUTEX(un));
29500 
29501 	while (state != SD_WM_DONE) {
29502 
29503 		switch (state) {
29504 		case SD_WM_CHK_LIST:
29505 			/*
29506 			 * This is the starting state. Check the wmap list
29507 			 * to see if the range is currently available.
29508 			 */
29509 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
29510 				/*
29511 				 * If this is a simple write and no rmw
29512 				 * i/o is pending then try to lock the
29513 				 * range as the range should be available.
29514 				 */
29515 				state = SD_WM_LOCK_RANGE;
29516 			} else {
29517 				tmp_wmp = sd_get_range(un, startb, endb);
29518 				if (tmp_wmp != NULL) {
29519 					if ((wmp != NULL) && ONLIST(un, wmp)) {
29520 						/*
29521 						 * Should not keep onlist wmps
29522 						 * while waiting this macro
29523 						 * will also do wmp = NULL;
29524 						 */
29525 						FREE_ONLIST_WMAP(un, wmp);
29526 					}
29527 					/*
29528 					 * sl_wmp is the wmap on which wait
29529 					 * is done, since the tmp_wmp points
29530 					 * to the inuse wmap, set sl_wmp to
29531 					 * tmp_wmp and change the state to sleep
29532 					 */
29533 					sl_wmp = tmp_wmp;
29534 					state = SD_WM_WAIT_MAP;
29535 				} else {
29536 					state = SD_WM_LOCK_RANGE;
29537 				}
29538 
29539 			}
29540 			break;
29541 
29542 		case SD_WM_LOCK_RANGE:
29543 			ASSERT(un->un_wm_cache);
29544 			/*
29545 			 * The range need to be locked, try to get a wmap.
29546 			 * First attempt it with NO_SLEEP, want to avoid a sleep
29547 			 * if possible as we will have to release the sd mutex
29548 			 * if we have to sleep.
29549 			 */
29550 			if (wmp == NULL)
29551 				wmp = kmem_cache_alloc(un->un_wm_cache,
29552 				    KM_NOSLEEP);
29553 			if (wmp == NULL) {
29554 				mutex_exit(SD_MUTEX(un));
29555 				_NOTE(DATA_READABLE_WITHOUT_LOCK
29556 				    (sd_lun::un_wm_cache))
29557 				wmp = kmem_cache_alloc(un->un_wm_cache,
29558 				    KM_SLEEP);
29559 				mutex_enter(SD_MUTEX(un));
29560 				/*
29561 				 * we released the mutex so recheck and go to
29562 				 * check list state.
29563 				 */
29564 				state = SD_WM_CHK_LIST;
29565 			} else {
29566 				/*
29567 				 * We exit out of state machine since we
29568 				 * have the wmap. Do the housekeeping first.
29569 				 * place the wmap on the wmap list if it is not
29570 				 * on it already and then set the state to done.
29571 				 */
29572 				wmp->wm_start = startb;
29573 				wmp->wm_end = endb;
29574 				wmp->wm_flags = typ | SD_WM_BUSY;
29575 				if (typ & SD_WTYPE_RMW) {
29576 					un->un_rmw_count++;
29577 				}
29578 				/*
29579 				 * If not already on the list then link
29580 				 */
29581 				if (!ONLIST(un, wmp)) {
29582 					wmp->wm_next = un->un_wm;
29583 					wmp->wm_prev = NULL;
29584 					if (wmp->wm_next)
29585 						wmp->wm_next->wm_prev = wmp;
29586 					un->un_wm = wmp;
29587 				}
29588 				state = SD_WM_DONE;
29589 			}
29590 			break;
29591 
29592 		case SD_WM_WAIT_MAP:
29593 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
29594 			/*
29595 			 * Wait is done on sl_wmp, which is set in the
29596 			 * check_list state.
29597 			 */
29598 			sl_wmp->wm_wanted_count++;
29599 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
29600 			sl_wmp->wm_wanted_count--;
29601 			/*
29602 			 * We can reuse the memory from the completed sl_wmp
29603 			 * lock range for our new lock, but only if noone is
29604 			 * waiting for it.
29605 			 */
29606 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
29607 			if (sl_wmp->wm_wanted_count == 0) {
29608 				if (wmp != NULL) {
29609 					CHK_N_FREEWMP(un, wmp);
29610 				}
29611 				wmp = sl_wmp;
29612 			}
29613 			sl_wmp = NULL;
29614 			/*
29615 			 * After waking up, need to recheck for availability of
29616 			 * range.
29617 			 */
29618 			state = SD_WM_CHK_LIST;
29619 			break;
29620 
29621 		default:
29622 			panic("sd_range_lock: "
29623 			    "Unknown state %d in sd_range_lock", state);
29624 			/*NOTREACHED*/
29625 		} /* switch(state) */
29626 
29627 	} /* while(state != SD_WM_DONE) */
29628 
29629 	mutex_exit(SD_MUTEX(un));
29630 
29631 	ASSERT(wmp != NULL);
29632 
29633 	return (wmp);
29634 }
29635 
29636 
29637 /*
29638  *    Function: sd_get_range()
29639  *
29640  * Description: Find if there any overlapping I/O to this one
29641  *		Returns the write-map of 1st such I/O, NULL otherwise.
29642  *
29643  *   Arguments: un	- sd_lun structure for the device.
29644  *		startb - The starting block number
29645  *		endb - The end block number
29646  *
29647  * Return Code: wm  - pointer to the wmap structure.
29648  */
29649 
29650 static struct sd_w_map *
29651 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
29652 {
29653 	struct sd_w_map *wmp;
29654 
29655 	ASSERT(un != NULL);
29656 
29657 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
29658 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
29659 			continue;
29660 		}
29661 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
29662 			break;
29663 		}
29664 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
29665 			break;
29666 		}
29667 	}
29668 
29669 	return (wmp);
29670 }
29671 
29672 
29673 /*
29674  *    Function: sd_free_inlist_wmap()
29675  *
29676  * Description: Unlink and free a write map struct.
29677  *
29678  *   Arguments: un      - sd_lun structure for the device.
29679  *		wmp	- sd_w_map which needs to be unlinked.
29680  */
29681 
29682 static void
29683 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
29684 {
29685 	ASSERT(un != NULL);
29686 
29687 	if (un->un_wm == wmp) {
29688 		un->un_wm = wmp->wm_next;
29689 	} else {
29690 		wmp->wm_prev->wm_next = wmp->wm_next;
29691 	}
29692 
29693 	if (wmp->wm_next) {
29694 		wmp->wm_next->wm_prev = wmp->wm_prev;
29695 	}
29696 
29697 	wmp->wm_next = wmp->wm_prev = NULL;
29698 
29699 	kmem_cache_free(un->un_wm_cache, wmp);
29700 }
29701 
29702 
29703 /*
29704  *    Function: sd_range_unlock()
29705  *
29706  * Description: Unlock the range locked by wm.
29707  *		Free write map if nobody else is waiting on it.
29708  *
29709  *   Arguments: un      - sd_lun structure for the device.
29710  *              wmp     - sd_w_map which needs to be unlinked.
29711  */
29712 
29713 static void
29714 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
29715 {
29716 	ASSERT(un != NULL);
29717 	ASSERT(wm != NULL);
29718 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29719 
29720 	mutex_enter(SD_MUTEX(un));
29721 
29722 	if (wm->wm_flags & SD_WTYPE_RMW) {
29723 		un->un_rmw_count--;
29724 	}
29725 
29726 	if (wm->wm_wanted_count) {
29727 		wm->wm_flags = 0;
29728 		/*
29729 		 * Broadcast that the wmap is available now.
29730 		 */
29731 		cv_broadcast(&wm->wm_avail);
29732 	} else {
29733 		/*
29734 		 * If no one is waiting on the map, it should be free'ed.
29735 		 */
29736 		sd_free_inlist_wmap(un, wm);
29737 	}
29738 
29739 	mutex_exit(SD_MUTEX(un));
29740 }
29741 
29742 
29743 /*
29744  *    Function: sd_read_modify_write_task
29745  *
29746  * Description: Called from a taskq thread to initiate the write phase of
29747  *		a read-modify-write request.  This is used for targets where
29748  *		un->un_sys_blocksize != un->un_tgt_blocksize.
29749  *
29750  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
29751  *
29752  *     Context: Called under taskq thread context.
29753  */
29754 
29755 static void
29756 sd_read_modify_write_task(void *arg)
29757 {
29758 	struct sd_mapblocksize_info	*bsp;
29759 	struct buf	*bp;
29760 	struct sd_xbuf	*xp;
29761 	struct sd_lun	*un;
29762 
29763 	bp = arg;	/* The bp is given in arg */
29764 	ASSERT(bp != NULL);
29765 
29766 	/* Get the pointer to the layer-private data struct */
29767 	xp = SD_GET_XBUF(bp);
29768 	ASSERT(xp != NULL);
29769 	bsp = xp->xb_private;
29770 	ASSERT(bsp != NULL);
29771 
29772 	un = SD_GET_UN(bp);
29773 	ASSERT(un != NULL);
29774 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29775 
29776 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29777 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
29778 
29779 	/*
29780 	 * This is the write phase of a read-modify-write request, called
29781 	 * under the context of a taskq thread in response to the completion
29782 	 * of the read portion of the rmw request completing under interrupt
29783 	 * context. The write request must be sent from here down the iostart
29784 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
29785 	 * we use the layer index saved in the layer-private data area.
29786 	 */
29787 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
29788 
29789 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29790 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
29791 }
29792 
29793 
29794 /*
29795  *    Function: sddump_do_read_of_rmw()
29796  *
29797  * Description: This routine will be called from sddump, If sddump is called
29798  *		with an I/O which not aligned on device blocksize boundary
29799  *		then the write has to be converted to read-modify-write.
29800  *		Do the read part here in order to keep sddump simple.
29801  *		Note - That the sd_mutex is held across the call to this
29802  *		routine.
29803  *
29804  *   Arguments: un	- sd_lun
29805  *		blkno	- block number in terms of media block size.
29806  *		nblk	- number of blocks.
29807  *		bpp	- pointer to pointer to the buf structure. On return
29808  *			from this function, *bpp points to the valid buffer
29809  *			to which the write has to be done.
29810  *
29811  * Return Code: 0 for success or errno-type return code
29812  */
29813 
29814 static int
29815 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
29816     struct buf **bpp)
29817 {
29818 	int err;
29819 	int i;
29820 	int rval;
29821 	struct buf *bp;
29822 	struct scsi_pkt *pkt = NULL;
29823 	uint32_t target_blocksize;
29824 
29825 	ASSERT(un != NULL);
29826 	ASSERT(mutex_owned(SD_MUTEX(un)));
29827 
29828 	target_blocksize = un->un_tgt_blocksize;
29829 
29830 	mutex_exit(SD_MUTEX(un));
29831 
29832 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
29833 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
29834 	if (bp == NULL) {
29835 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29836 		    "no resources for dumping; giving up");
29837 		err = ENOMEM;
29838 		goto done;
29839 	}
29840 
29841 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
29842 	    blkno, nblk);
29843 	if (rval != 0) {
29844 		scsi_free_consistent_buf(bp);
29845 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29846 		    "no resources for dumping; giving up");
29847 		err = ENOMEM;
29848 		goto done;
29849 	}
29850 
29851 	pkt->pkt_flags |= FLAG_NOINTR;
29852 
29853 	err = EIO;
29854 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
29855 
29856 		/*
29857 		 * Scsi_poll returns 0 (success) if the command completes and
29858 		 * the status block is STATUS_GOOD.  We should only check
29859 		 * errors if this condition is not true.  Even then we should
29860 		 * send our own request sense packet only if we have a check
29861 		 * condition and auto request sense has not been performed by
29862 		 * the hba.
29863 		 */
29864 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
29865 
29866 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
29867 			err = 0;
29868 			break;
29869 		}
29870 
29871 		/*
29872 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
29873 		 * no need to read RQS data.
29874 		 */
29875 		if (pkt->pkt_reason == CMD_DEV_GONE) {
29876 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29877 			    "Error while dumping state with rmw..."
29878 			    "Device is gone\n");
29879 			break;
29880 		}
29881 
29882 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
29883 			SD_INFO(SD_LOG_DUMP, un,
29884 			    "sddump: read failed with CHECK, try # %d\n", i);
29885 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
29886 				(void) sd_send_polled_RQS(un);
29887 			}
29888 
29889 			continue;
29890 		}
29891 
29892 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
29893 			int reset_retval = 0;
29894 
29895 			SD_INFO(SD_LOG_DUMP, un,
29896 			    "sddump: read failed with BUSY, try # %d\n", i);
29897 
29898 			if (un->un_f_lun_reset_enabled == TRUE) {
29899 				reset_retval = scsi_reset(SD_ADDRESS(un),
29900 				    RESET_LUN);
29901 			}
29902 			if (reset_retval == 0) {
29903 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
29904 			}
29905 			(void) sd_send_polled_RQS(un);
29906 
29907 		} else {
29908 			SD_INFO(SD_LOG_DUMP, un,
29909 			    "sddump: read failed with 0x%x, try # %d\n",
29910 			    SD_GET_PKT_STATUS(pkt), i);
29911 			mutex_enter(SD_MUTEX(un));
29912 			sd_reset_target(un, pkt);
29913 			mutex_exit(SD_MUTEX(un));
29914 		}
29915 
29916 		/*
29917 		 * If we are not getting anywhere with lun/target resets,
29918 		 * let's reset the bus.
29919 		 */
29920 		if (i > SD_NDUMP_RETRIES / 2) {
29921 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
29922 			(void) sd_send_polled_RQS(un);
29923 		}
29924 
29925 	}
29926 	scsi_destroy_pkt(pkt);
29927 
29928 	if (err != 0) {
29929 		scsi_free_consistent_buf(bp);
29930 		*bpp = NULL;
29931 	} else {
29932 		*bpp = bp;
29933 	}
29934 
29935 done:
29936 	mutex_enter(SD_MUTEX(un));
29937 	return (err);
29938 }
29939 
29940 
29941 /*
29942  *    Function: sd_failfast_flushq
29943  *
29944  * Description: Take all bp's on the wait queue that have B_FAILFAST set
29945  *		in b_flags and move them onto the failfast queue, then kick
29946  *		off a thread to return all bp's on the failfast queue to
29947  *		their owners with an error set.
29948  *
29949  *   Arguments: un - pointer to the soft state struct for the instance.
29950  *
29951  *     Context: may execute in interrupt context.
29952  */
29953 
29954 static void
29955 sd_failfast_flushq(struct sd_lun *un)
29956 {
29957 	struct buf *bp;
29958 	struct buf *next_waitq_bp;
29959 	struct buf *prev_waitq_bp = NULL;
29960 
29961 	ASSERT(un != NULL);
29962 	ASSERT(mutex_owned(SD_MUTEX(un)));
29963 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
29964 	ASSERT(un->un_failfast_bp == NULL);
29965 
29966 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29967 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
29968 
29969 	/*
29970 	 * Check if we should flush all bufs when entering failfast state, or
29971 	 * just those with B_FAILFAST set.
29972 	 */
29973 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
29974 		/*
29975 		 * Move *all* bp's on the wait queue to the failfast flush
29976 		 * queue, including those that do NOT have B_FAILFAST set.
29977 		 */
29978 		if (un->un_failfast_headp == NULL) {
29979 			ASSERT(un->un_failfast_tailp == NULL);
29980 			un->un_failfast_headp = un->un_waitq_headp;
29981 		} else {
29982 			ASSERT(un->un_failfast_tailp != NULL);
29983 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
29984 		}
29985 
29986 		un->un_failfast_tailp = un->un_waitq_tailp;
29987 
29988 		/* update kstat for each bp moved out of the waitq */
29989 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
29990 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29991 		}
29992 
29993 		/* empty the waitq */
29994 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
29995 
29996 	} else {
29997 		/*
29998 		 * Go thru the wait queue, pick off all entries with
29999 		 * B_FAILFAST set, and move these onto the failfast queue.
30000 		 */
30001 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
30002 			/*
30003 			 * Save the pointer to the next bp on the wait queue,
30004 			 * so we get to it on the next iteration of this loop.
30005 			 */
30006 			next_waitq_bp = bp->av_forw;
30007 
30008 			/*
30009 			 * If this bp from the wait queue does NOT have
30010 			 * B_FAILFAST set, just move on to the next element
30011 			 * in the wait queue. Note, this is the only place
30012 			 * where it is correct to set prev_waitq_bp.
30013 			 */
30014 			if ((bp->b_flags & B_FAILFAST) == 0) {
30015 				prev_waitq_bp = bp;
30016 				continue;
30017 			}
30018 
30019 			/*
30020 			 * Remove the bp from the wait queue.
30021 			 */
30022 			if (bp == un->un_waitq_headp) {
30023 				/* The bp is the first element of the waitq. */
30024 				un->un_waitq_headp = next_waitq_bp;
30025 				if (un->un_waitq_headp == NULL) {
30026 					/* The wait queue is now empty */
30027 					un->un_waitq_tailp = NULL;
30028 				}
30029 			} else {
30030 				/*
30031 				 * The bp is either somewhere in the middle
30032 				 * or at the end of the wait queue.
30033 				 */
30034 				ASSERT(un->un_waitq_headp != NULL);
30035 				ASSERT(prev_waitq_bp != NULL);
30036 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
30037 				    == 0);
30038 				if (bp == un->un_waitq_tailp) {
30039 					/* bp is the last entry on the waitq. */
30040 					ASSERT(next_waitq_bp == NULL);
30041 					un->un_waitq_tailp = prev_waitq_bp;
30042 				}
30043 				prev_waitq_bp->av_forw = next_waitq_bp;
30044 			}
30045 			bp->av_forw = NULL;
30046 
30047 			/*
30048 			 * update kstat since the bp is moved out of
30049 			 * the waitq
30050 			 */
30051 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
30052 
30053 			/*
30054 			 * Now put the bp onto the failfast queue.
30055 			 */
30056 			if (un->un_failfast_headp == NULL) {
30057 				/* failfast queue is currently empty */
30058 				ASSERT(un->un_failfast_tailp == NULL);
30059 				un->un_failfast_headp =
30060 				    un->un_failfast_tailp = bp;
30061 			} else {
30062 				/* Add the bp to the end of the failfast q */
30063 				ASSERT(un->un_failfast_tailp != NULL);
30064 				ASSERT(un->un_failfast_tailp->b_flags &
30065 				    B_FAILFAST);
30066 				un->un_failfast_tailp->av_forw = bp;
30067 				un->un_failfast_tailp = bp;
30068 			}
30069 		}
30070 	}
30071 
30072 	/*
30073 	 * Now return all bp's on the failfast queue to their owners.
30074 	 */
30075 	while ((bp = un->un_failfast_headp) != NULL) {
30076 
30077 		un->un_failfast_headp = bp->av_forw;
30078 		if (un->un_failfast_headp == NULL) {
30079 			un->un_failfast_tailp = NULL;
30080 		}
30081 
30082 		/*
30083 		 * We want to return the bp with a failure error code, but
30084 		 * we do not want a call to sd_start_cmds() to occur here,
30085 		 * so use sd_return_failed_command_no_restart() instead of
30086 		 * sd_return_failed_command().
30087 		 */
30088 		sd_return_failed_command_no_restart(un, bp, EIO);
30089 	}
30090 
30091 	/* Flush the xbuf queues if required. */
30092 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
30093 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
30094 	}
30095 
30096 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
30097 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
30098 }
30099 
30100 
30101 /*
30102  *    Function: sd_failfast_flushq_callback
30103  *
30104  * Description: Return TRUE if the given bp meets the criteria for failfast
30105  *		flushing. Used with ddi_xbuf_flushq(9F).
30106  *
30107  *   Arguments: bp - ptr to buf struct to be examined.
30108  *
30109  *     Context: Any
30110  */
30111 
30112 static int
30113 sd_failfast_flushq_callback(struct buf *bp)
30114 {
30115 	/*
30116 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
30117 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
30118 	 */
30119 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
30120 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
30121 }
30122 
30123 
30124 
30125 /*
30126  * Function: sd_setup_next_xfer
30127  *
30128  * Description: Prepare next I/O operation using DMA_PARTIAL
30129  *
30130  */
30131 
30132 static int
30133 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
30134     struct scsi_pkt *pkt, struct sd_xbuf *xp)
30135 {
30136 	ssize_t	num_blks_not_xfered;
30137 	daddr_t	strt_blk_num;
30138 	ssize_t	bytes_not_xfered;
30139 	int	rval;
30140 
30141 	ASSERT(pkt->pkt_resid == 0);
30142 
30143 	/*
30144 	 * Calculate next block number and amount to be transferred.
30145 	 *
30146 	 * How much data NOT transfered to the HBA yet.
30147 	 */
30148 	bytes_not_xfered = xp->xb_dma_resid;
30149 
30150 	/*
30151 	 * figure how many blocks NOT transfered to the HBA yet.
30152 	 */
30153 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
30154 
30155 	/*
30156 	 * set starting block number to the end of what WAS transfered.
30157 	 */
30158 	strt_blk_num = xp->xb_blkno +
30159 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
30160 
30161 	/*
30162 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
30163 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
30164 	 * the disk mutex here.
30165 	 */
30166 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
30167 	    strt_blk_num, num_blks_not_xfered);
30168 
30169 	if (rval == 0) {
30170 
30171 		/*
30172 		 * Success.
30173 		 *
30174 		 * Adjust things if there are still more blocks to be
30175 		 * transfered.
30176 		 */
30177 		xp->xb_dma_resid = pkt->pkt_resid;
30178 		pkt->pkt_resid = 0;
30179 
30180 		return (1);
30181 	}
30182 
30183 	/*
30184 	 * There's really only one possible return value from
30185 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
30186 	 * returns NULL.
30187 	 */
30188 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
30189 
30190 	bp->b_resid = bp->b_bcount;
30191 	bp->b_flags |= B_ERROR;
30192 
30193 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30194 	    "Error setting up next portion of DMA transfer\n");
30195 
30196 	return (0);
30197 }
30198 
30199 /*
30200  *    Function: sd_panic_for_res_conflict
30201  *
30202  * Description: Call panic with a string formatted with "Reservation Conflict"
30203  *		and a human readable identifier indicating the SD instance
30204  *		that experienced the reservation conflict.
30205  *
30206  *   Arguments: un - pointer to the soft state struct for the instance.
30207  *
30208  *     Context: may execute in interrupt context.
30209  */
30210 
30211 #define	SD_RESV_CONFLICT_FMT_LEN 40
30212 void
30213 sd_panic_for_res_conflict(struct sd_lun *un)
30214 {
30215 	char panic_str[SD_RESV_CONFLICT_FMT_LEN + MAXPATHLEN];
30216 	char path_str[MAXPATHLEN];
30217 
30218 	(void) snprintf(panic_str, sizeof (panic_str),
30219 	    "Reservation Conflict\nDisk: %s",
30220 	    ddi_pathname(SD_DEVINFO(un), path_str));
30221 
30222 	panic(panic_str);
30223 }
30224 
30225 /*
30226  * Note: The following sd_faultinjection_ioctl( ) routines implement
30227  * driver support for handling fault injection for error analysis
30228  * causing faults in multiple layers of the driver.
30229  *
30230  */
30231 
30232 #ifdef SD_FAULT_INJECTION
30233 static uint_t   sd_fault_injection_on = 0;
30234 
30235 /*
30236  *    Function: sd_faultinjection_ioctl()
30237  *
30238  * Description: This routine is the driver entry point for handling
30239  *              faultinjection ioctls to inject errors into the
30240  *              layer model
30241  *
30242  *   Arguments: cmd	- the ioctl cmd received
30243  *		arg	- the arguments from user and returns
30244  */
30245 
30246 static void
30247 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un)
30248 {
30249 	uint_t i = 0;
30250 	uint_t rval;
30251 
30252 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
30253 
30254 	mutex_enter(SD_MUTEX(un));
30255 
30256 	switch (cmd) {
30257 	case SDIOCRUN:
30258 		/* Allow pushed faults to be injected */
30259 		SD_INFO(SD_LOG_SDTEST, un,
30260 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
30261 
30262 		sd_fault_injection_on = 1;
30263 
30264 		SD_INFO(SD_LOG_IOERR, un,
30265 		    "sd_faultinjection_ioctl: run finished\n");
30266 		break;
30267 
30268 	case SDIOCSTART:
30269 		/* Start Injection Session */
30270 		SD_INFO(SD_LOG_SDTEST, un,
30271 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
30272 
30273 		sd_fault_injection_on = 0;
30274 		un->sd_injection_mask = 0xFFFFFFFF;
30275 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30276 			un->sd_fi_fifo_pkt[i] = NULL;
30277 			un->sd_fi_fifo_xb[i] = NULL;
30278 			un->sd_fi_fifo_un[i] = NULL;
30279 			un->sd_fi_fifo_arq[i] = NULL;
30280 		}
30281 		un->sd_fi_fifo_start = 0;
30282 		un->sd_fi_fifo_end = 0;
30283 
30284 		mutex_enter(&(un->un_fi_mutex));
30285 		un->sd_fi_log[0] = '\0';
30286 		un->sd_fi_buf_len = 0;
30287 		mutex_exit(&(un->un_fi_mutex));
30288 
30289 		SD_INFO(SD_LOG_IOERR, un,
30290 		    "sd_faultinjection_ioctl: start finished\n");
30291 		break;
30292 
30293 	case SDIOCSTOP:
30294 		/* Stop Injection Session */
30295 		SD_INFO(SD_LOG_SDTEST, un,
30296 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
30297 		sd_fault_injection_on = 0;
30298 		un->sd_injection_mask = 0x0;
30299 
30300 		/* Empty stray or unuseds structs from fifo */
30301 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30302 			if (un->sd_fi_fifo_pkt[i] != NULL) {
30303 				kmem_free(un->sd_fi_fifo_pkt[i],
30304 				    sizeof (struct sd_fi_pkt));
30305 			}
30306 			if (un->sd_fi_fifo_xb[i] != NULL) {
30307 				kmem_free(un->sd_fi_fifo_xb[i],
30308 				    sizeof (struct sd_fi_xb));
30309 			}
30310 			if (un->sd_fi_fifo_un[i] != NULL) {
30311 				kmem_free(un->sd_fi_fifo_un[i],
30312 				    sizeof (struct sd_fi_un));
30313 			}
30314 			if (un->sd_fi_fifo_arq[i] != NULL) {
30315 				kmem_free(un->sd_fi_fifo_arq[i],
30316 				    sizeof (struct sd_fi_arq));
30317 			}
30318 			un->sd_fi_fifo_pkt[i] = NULL;
30319 			un->sd_fi_fifo_un[i] = NULL;
30320 			un->sd_fi_fifo_xb[i] = NULL;
30321 			un->sd_fi_fifo_arq[i] = NULL;
30322 		}
30323 		un->sd_fi_fifo_start = 0;
30324 		un->sd_fi_fifo_end = 0;
30325 
30326 		SD_INFO(SD_LOG_IOERR, un,
30327 		    "sd_faultinjection_ioctl: stop finished\n");
30328 		break;
30329 
30330 	case SDIOCINSERTPKT:
30331 		/* Store a packet struct to be pushed onto fifo */
30332 		SD_INFO(SD_LOG_SDTEST, un,
30333 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
30334 
30335 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30336 
30337 		sd_fault_injection_on = 0;
30338 
30339 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
30340 		if (un->sd_fi_fifo_pkt[i] != NULL) {
30341 			kmem_free(un->sd_fi_fifo_pkt[i],
30342 			    sizeof (struct sd_fi_pkt));
30343 		}
30344 		if (arg != (uintptr_t)NULL) {
30345 			un->sd_fi_fifo_pkt[i] =
30346 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
30347 			if (un->sd_fi_fifo_pkt[i] == NULL) {
30348 				/* Alloc failed don't store anything */
30349 				break;
30350 			}
30351 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
30352 			    sizeof (struct sd_fi_pkt), 0);
30353 			if (rval == -1) {
30354 				kmem_free(un->sd_fi_fifo_pkt[i],
30355 				    sizeof (struct sd_fi_pkt));
30356 				un->sd_fi_fifo_pkt[i] = NULL;
30357 			}
30358 		} else {
30359 			SD_INFO(SD_LOG_IOERR, un,
30360 			    "sd_faultinjection_ioctl: pkt null\n");
30361 		}
30362 		break;
30363 
30364 	case SDIOCINSERTXB:
30365 		/* Store a xb struct to be pushed onto fifo */
30366 		SD_INFO(SD_LOG_SDTEST, un,
30367 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
30368 
30369 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30370 
30371 		sd_fault_injection_on = 0;
30372 
30373 		if (un->sd_fi_fifo_xb[i] != NULL) {
30374 			kmem_free(un->sd_fi_fifo_xb[i],
30375 			    sizeof (struct sd_fi_xb));
30376 			un->sd_fi_fifo_xb[i] = NULL;
30377 		}
30378 		if (arg != (uintptr_t)NULL) {
30379 			un->sd_fi_fifo_xb[i] =
30380 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
30381 			if (un->sd_fi_fifo_xb[i] == NULL) {
30382 				/* Alloc failed don't store anything */
30383 				break;
30384 			}
30385 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
30386 			    sizeof (struct sd_fi_xb), 0);
30387 
30388 			if (rval == -1) {
30389 				kmem_free(un->sd_fi_fifo_xb[i],
30390 				    sizeof (struct sd_fi_xb));
30391 				un->sd_fi_fifo_xb[i] = NULL;
30392 			}
30393 		} else {
30394 			SD_INFO(SD_LOG_IOERR, un,
30395 			    "sd_faultinjection_ioctl: xb null\n");
30396 		}
30397 		break;
30398 
30399 	case SDIOCINSERTUN:
30400 		/* Store a un struct to be pushed onto fifo */
30401 		SD_INFO(SD_LOG_SDTEST, un,
30402 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
30403 
30404 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30405 
30406 		sd_fault_injection_on = 0;
30407 
30408 		if (un->sd_fi_fifo_un[i] != NULL) {
30409 			kmem_free(un->sd_fi_fifo_un[i],
30410 			    sizeof (struct sd_fi_un));
30411 			un->sd_fi_fifo_un[i] = NULL;
30412 		}
30413 		if (arg != (uintptr_t)NULL) {
30414 			un->sd_fi_fifo_un[i] =
30415 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
30416 			if (un->sd_fi_fifo_un[i] == NULL) {
30417 				/* Alloc failed don't store anything */
30418 				break;
30419 			}
30420 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
30421 			    sizeof (struct sd_fi_un), 0);
30422 			if (rval == -1) {
30423 				kmem_free(un->sd_fi_fifo_un[i],
30424 				    sizeof (struct sd_fi_un));
30425 				un->sd_fi_fifo_un[i] = NULL;
30426 			}
30427 
30428 		} else {
30429 			SD_INFO(SD_LOG_IOERR, un,
30430 			    "sd_faultinjection_ioctl: un null\n");
30431 		}
30432 
30433 		break;
30434 
30435 	case SDIOCINSERTARQ:
30436 		/* Store a arq struct to be pushed onto fifo */
30437 		SD_INFO(SD_LOG_SDTEST, un,
30438 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
30439 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30440 
30441 		sd_fault_injection_on = 0;
30442 
30443 		if (un->sd_fi_fifo_arq[i] != NULL) {
30444 			kmem_free(un->sd_fi_fifo_arq[i],
30445 			    sizeof (struct sd_fi_arq));
30446 			un->sd_fi_fifo_arq[i] = NULL;
30447 		}
30448 		if (arg != (uintptr_t)NULL) {
30449 			un->sd_fi_fifo_arq[i] =
30450 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
30451 			if (un->sd_fi_fifo_arq[i] == NULL) {
30452 				/* Alloc failed don't store anything */
30453 				break;
30454 			}
30455 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
30456 			    sizeof (struct sd_fi_arq), 0);
30457 			if (rval == -1) {
30458 				kmem_free(un->sd_fi_fifo_arq[i],
30459 				    sizeof (struct sd_fi_arq));
30460 				un->sd_fi_fifo_arq[i] = NULL;
30461 			}
30462 
30463 		} else {
30464 			SD_INFO(SD_LOG_IOERR, un,
30465 			    "sd_faultinjection_ioctl: arq null\n");
30466 		}
30467 
30468 		break;
30469 
30470 	case SDIOCPUSH:
30471 		/* Push stored xb, pkt, un, and arq onto fifo */
30472 		sd_fault_injection_on = 0;
30473 
30474 		if (arg != (uintptr_t)NULL) {
30475 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
30476 			if (rval != -1 &&
30477 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30478 				un->sd_fi_fifo_end += i;
30479 			}
30480 		} else {
30481 			SD_INFO(SD_LOG_IOERR, un,
30482 			    "sd_faultinjection_ioctl: push arg null\n");
30483 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30484 				un->sd_fi_fifo_end++;
30485 			}
30486 		}
30487 		SD_INFO(SD_LOG_IOERR, un,
30488 		    "sd_faultinjection_ioctl: push to end=%d\n",
30489 		    un->sd_fi_fifo_end);
30490 		break;
30491 
30492 	case SDIOCRETRIEVE:
30493 		/* Return buffer of log from Injection session */
30494 		SD_INFO(SD_LOG_SDTEST, un,
30495 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
30496 
30497 		sd_fault_injection_on = 0;
30498 
30499 		mutex_enter(&(un->un_fi_mutex));
30500 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
30501 		    un->sd_fi_buf_len+1, 0);
30502 		mutex_exit(&(un->un_fi_mutex));
30503 
30504 		if (rval == -1) {
30505 			/*
30506 			 * arg is possibly invalid setting
30507 			 * it to NULL for return
30508 			 */
30509 			arg = (uintptr_t)NULL;
30510 		}
30511 		break;
30512 	}
30513 
30514 	mutex_exit(SD_MUTEX(un));
30515 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: exit\n");
30516 }
30517 
30518 
30519 /*
30520  *    Function: sd_injection_log()
30521  *
30522  * Description: This routine adds buff to the already existing injection log
30523  *              for retrieval via faultinjection_ioctl for use in fault
30524  *              detection and recovery
30525  *
30526  *   Arguments: buf - the string to add to the log
30527  */
30528 
30529 static void
30530 sd_injection_log(char *buf, struct sd_lun *un)
30531 {
30532 	uint_t len;
30533 
30534 	ASSERT(un != NULL);
30535 	ASSERT(buf != NULL);
30536 
30537 	mutex_enter(&(un->un_fi_mutex));
30538 
30539 	len = min(strlen(buf), 255);
30540 	/* Add logged value to Injection log to be returned later */
30541 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
30542 		uint_t	offset = strlen((char *)un->sd_fi_log);
30543 		char *destp = (char *)un->sd_fi_log + offset;
30544 		int i;
30545 		for (i = 0; i < len; i++) {
30546 			*destp++ = *buf++;
30547 		}
30548 		un->sd_fi_buf_len += len;
30549 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
30550 	}
30551 
30552 	mutex_exit(&(un->un_fi_mutex));
30553 }
30554 
30555 
30556 /*
30557  *    Function: sd_faultinjection()
30558  *
30559  * Description: This routine takes the pkt and changes its
30560  *		content based on error injection scenerio.
30561  *
30562  *   Arguments: pktp	- packet to be changed
30563  */
30564 
30565 static void
30566 sd_faultinjection(struct scsi_pkt *pktp)
30567 {
30568 	uint_t i;
30569 	struct sd_fi_pkt *fi_pkt;
30570 	struct sd_fi_xb *fi_xb;
30571 	struct sd_fi_un *fi_un;
30572 	struct sd_fi_arq *fi_arq;
30573 	struct buf *bp;
30574 	struct sd_xbuf *xb;
30575 	struct sd_lun *un;
30576 
30577 	ASSERT(pktp != NULL);
30578 
30579 	/* pull bp xb and un from pktp */
30580 	bp = (struct buf *)pktp->pkt_private;
30581 	xb = SD_GET_XBUF(bp);
30582 	un = SD_GET_UN(bp);
30583 
30584 	ASSERT(un != NULL);
30585 
30586 	mutex_enter(SD_MUTEX(un));
30587 
30588 	SD_TRACE(SD_LOG_SDTEST, un,
30589 	    "sd_faultinjection: entry Injection from sdintr\n");
30590 
30591 	/* if injection is off return */
30592 	if (sd_fault_injection_on == 0 ||
30593 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
30594 		mutex_exit(SD_MUTEX(un));
30595 		return;
30596 	}
30597 
30598 	SD_INFO(SD_LOG_SDTEST, un,
30599 	    "sd_faultinjection: is working for copying\n");
30600 
30601 	/* take next set off fifo */
30602 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
30603 
30604 	fi_pkt = un->sd_fi_fifo_pkt[i];
30605 	fi_xb = un->sd_fi_fifo_xb[i];
30606 	fi_un = un->sd_fi_fifo_un[i];
30607 	fi_arq = un->sd_fi_fifo_arq[i];
30608 
30609 
30610 	/* set variables accordingly */
30611 	/* set pkt if it was on fifo */
30612 	if (fi_pkt != NULL) {
30613 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
30614 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
30615 		if (fi_pkt->pkt_cdbp != 0xff)
30616 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
30617 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
30618 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
30619 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
30620 
30621 	}
30622 	/* set xb if it was on fifo */
30623 	if (fi_xb != NULL) {
30624 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
30625 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
30626 		if (fi_xb->xb_retry_count != 0)
30627 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
30628 		SD_CONDSET(xb, xb, xb_victim_retry_count,
30629 		    "xb_victim_retry_count");
30630 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
30631 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
30632 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
30633 
30634 		/* copy in block data from sense */
30635 		/*
30636 		 * if (fi_xb->xb_sense_data[0] != -1) {
30637 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
30638 		 *	SENSE_LENGTH);
30639 		 * }
30640 		 */
30641 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
30642 
30643 		/* copy in extended sense codes */
30644 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30645 		    xb, es_code, "es_code");
30646 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30647 		    xb, es_key, "es_key");
30648 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30649 		    xb, es_add_code, "es_add_code");
30650 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30651 		    xb, es_qual_code, "es_qual_code");
30652 		struct scsi_extended_sense *esp;
30653 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
30654 		esp->es_class = CLASS_EXTENDED_SENSE;
30655 	}
30656 
30657 	/* set un if it was on fifo */
30658 	if (fi_un != NULL) {
30659 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
30660 		SD_CONDSET(un, un, un_ctype, "un_ctype");
30661 		SD_CONDSET(un, un, un_reset_retry_count,
30662 		    "un_reset_retry_count");
30663 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
30664 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
30665 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
30666 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
30667 		    "un_f_allow_bus_device_reset");
30668 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
30669 
30670 	}
30671 
30672 	/* copy in auto request sense if it was on fifo */
30673 	if (fi_arq != NULL) {
30674 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
30675 	}
30676 
30677 	/* free structs */
30678 	if (un->sd_fi_fifo_pkt[i] != NULL) {
30679 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
30680 	}
30681 	if (un->sd_fi_fifo_xb[i] != NULL) {
30682 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
30683 	}
30684 	if (un->sd_fi_fifo_un[i] != NULL) {
30685 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
30686 	}
30687 	if (un->sd_fi_fifo_arq[i] != NULL) {
30688 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
30689 	}
30690 
30691 	/*
30692 	 * kmem_free does not gurantee to set to NULL
30693 	 * since we uses these to determine if we set
30694 	 * values or not lets confirm they are always
30695 	 * NULL after free
30696 	 */
30697 	un->sd_fi_fifo_pkt[i] = NULL;
30698 	un->sd_fi_fifo_un[i] = NULL;
30699 	un->sd_fi_fifo_xb[i] = NULL;
30700 	un->sd_fi_fifo_arq[i] = NULL;
30701 
30702 	un->sd_fi_fifo_start++;
30703 
30704 	mutex_exit(SD_MUTEX(un));
30705 
30706 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
30707 }
30708 
30709 #endif /* SD_FAULT_INJECTION */
30710 
30711 /*
30712  * This routine is invoked in sd_unit_attach(). Before calling it, the
30713  * properties in conf file should be processed already, and "hotpluggable"
30714  * property was processed also.
30715  *
30716  * The sd driver distinguishes 3 different type of devices: removable media,
30717  * non-removable media, and hotpluggable. Below the differences are defined:
30718  *
30719  * 1. Device ID
30720  *
30721  *     The device ID of a device is used to identify this device. Refer to
30722  *     ddi_devid_register(9F).
30723  *
30724  *     For a non-removable media disk device which can provide 0x80 or 0x83
30725  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
30726  *     device ID is created to identify this device. For other non-removable
30727  *     media devices, a default device ID is created only if this device has
30728  *     at least 2 alter cylinders. Otherwise, this device has no devid.
30729  *
30730  *     -------------------------------------------------------
30731  *     removable media   hotpluggable  | Can Have Device ID
30732  *     -------------------------------------------------------
30733  *         false             false     |     Yes
30734  *         false             true      |     Yes
30735  *         true                x       |     No
30736  *     ------------------------------------------------------
30737  *
30738  *
30739  * 2. SCSI group 4 commands
30740  *
30741  *     In SCSI specs, only some commands in group 4 command set can use
30742  *     8-byte addresses that can be used to access >2TB storage spaces.
30743  *     Other commands have no such capability. Without supporting group4,
30744  *     it is impossible to make full use of storage spaces of a disk with
30745  *     capacity larger than 2TB.
30746  *
30747  *     -----------------------------------------------
30748  *     removable media   hotpluggable   LP64  |  Group
30749  *     -----------------------------------------------
30750  *           false          false       false |   1
30751  *           false          false       true  |   4
30752  *           false          true        false |   1
30753  *           false          true        true  |   4
30754  *           true             x           x   |   5
30755  *     -----------------------------------------------
30756  *
30757  *
30758  * 3. Check for VTOC Label
30759  *
30760  *     If a direct-access disk has no EFI label, sd will check if it has a
30761  *     valid VTOC label. Now, sd also does that check for removable media
30762  *     and hotpluggable devices.
30763  *
30764  *     --------------------------------------------------------------
30765  *     Direct-Access   removable media    hotpluggable |  Check Label
30766  *     -------------------------------------------------------------
30767  *         false          false           false        |   No
30768  *         false          false           true         |   No
30769  *         false          true            false        |   Yes
30770  *         false          true            true         |   Yes
30771  *         true            x                x          |   Yes
30772  *     --------------------------------------------------------------
30773  *
30774  *
30775  * 4. Building default VTOC label
30776  *
30777  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
30778  *     If those devices have no valid VTOC label, sd(4D) will attempt to
30779  *     create default VTOC for them. Currently sd creates default VTOC label
30780  *     for all devices on x86 platform (VTOC_16), but only for removable
30781  *     media devices on SPARC (VTOC_8).
30782  *
30783  *     -----------------------------------------------------------
30784  *       removable media hotpluggable platform   |   Default Label
30785  *     -----------------------------------------------------------
30786  *             false          false    sparc     |     No
30787  *             false          true      x86      |     Yes
30788  *             false          true     sparc     |     Yes
30789  *             true             x        x       |     Yes
30790  *     ----------------------------------------------------------
30791  *
30792  *
30793  * 5. Supported blocksizes of target devices
30794  *
30795  *     Sd supports non-512-byte blocksize for removable media devices only.
30796  *     For other devices, only 512-byte blocksize is supported. This may be
30797  *     changed in near future because some RAID devices require non-512-byte
30798  *     blocksize
30799  *
30800  *     -----------------------------------------------------------
30801  *     removable media    hotpluggable    | non-512-byte blocksize
30802  *     -----------------------------------------------------------
30803  *           false          false         |   No
30804  *           false          true          |   No
30805  *           true             x           |   Yes
30806  *     -----------------------------------------------------------
30807  *
30808  *
30809  * 6. Automatic mount & unmount
30810  *
30811  *     sd(4D) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
30812  *     if a device is removable media device. It return 1 for removable media
30813  *     devices, and 0 for others.
30814  *
30815  *     The automatic mounting subsystem should distinguish between the types
30816  *     of devices and apply automounting policies to each.
30817  *
30818  *
30819  * 7. fdisk partition management
30820  *
30821  *     Fdisk is traditional partition method on x86 platform. sd(4D) driver
30822  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
30823  *     doesn't support fdisk partitions at all. Note: pcfs(4FS) can recognize
30824  *     fdisk partitions on both x86 and SPARC platform.
30825  *
30826  *     -----------------------------------------------------------
30827  *       platform   removable media  USB/1394  |  fdisk supported
30828  *     -----------------------------------------------------------
30829  *        x86         X               X        |       true
30830  *     ------------------------------------------------------------
30831  *        sparc       X               X        |       false
30832  *     ------------------------------------------------------------
30833  *
30834  *
30835  * 8. MBOOT/MBR
30836  *
30837  *     Although sd(4D) doesn't support fdisk on SPARC platform, it does support
30838  *     read/write mboot for removable media devices on sparc platform.
30839  *
30840  *     -----------------------------------------------------------
30841  *       platform   removable media  USB/1394  |  mboot supported
30842  *     -----------------------------------------------------------
30843  *        x86         X               X        |       true
30844  *     ------------------------------------------------------------
30845  *        sparc      false           false     |       false
30846  *        sparc      false           true      |       true
30847  *        sparc      true            false     |       true
30848  *        sparc      true            true      |       true
30849  *     ------------------------------------------------------------
30850  *
30851  *
30852  * 9.  error handling during opening device
30853  *
30854  *     If failed to open a disk device, an errno is returned. For some kinds
30855  *     of errors, different errno is returned depending on if this device is
30856  *     a removable media device. This brings USB/1394 hard disks in line with
30857  *     expected hard disk behavior. It is not expected that this breaks any
30858  *     application.
30859  *
30860  *     ------------------------------------------------------
30861  *       removable media    hotpluggable   |  errno
30862  *     ------------------------------------------------------
30863  *             false          false        |   EIO
30864  *             false          true         |   EIO
30865  *             true             x          |   ENXIO
30866  *     ------------------------------------------------------
30867  *
30868  *
30869  * 11. ioctls: DKIOCEJECT, CDROMEJECT
30870  *
30871  *     These IOCTLs are applicable only to removable media devices.
30872  *
30873  *     -----------------------------------------------------------
30874  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
30875  *     -----------------------------------------------------------
30876  *             false          false        |     No
30877  *             false          true         |     No
30878  *             true            x           |     Yes
30879  *     -----------------------------------------------------------
30880  *
30881  *
30882  * 12. Kstats for partitions
30883  *
30884  *     sd creates partition kstat for non-removable media devices. USB and
30885  *     Firewire hard disks now have partition kstats
30886  *
30887  *      ------------------------------------------------------
30888  *       removable media    hotpluggable   |   kstat
30889  *      ------------------------------------------------------
30890  *             false          false        |    Yes
30891  *             false          true         |    Yes
30892  *             true             x          |    No
30893  *       ------------------------------------------------------
30894  *
30895  *
30896  * 13. Removable media & hotpluggable properties
30897  *
30898  *     Sd driver creates a "removable-media" property for removable media
30899  *     devices. Parent nexus drivers create a "hotpluggable" property if
30900  *     it supports hotplugging.
30901  *
30902  *     ---------------------------------------------------------------------
30903  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
30904  *     ---------------------------------------------------------------------
30905  *       false            false       |    No                   No
30906  *       false            true        |    No                   Yes
30907  *       true             false       |    Yes                  No
30908  *       true             true        |    Yes                  Yes
30909  *     ---------------------------------------------------------------------
30910  *
30911  *
30912  * 14. Power Management
30913  *
30914  *     sd only power manages removable media devices or devices that support
30915  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
30916  *
30917  *     A parent nexus that supports hotplugging can also set "pm-capable"
30918  *     if the disk can be power managed.
30919  *
30920  *     ------------------------------------------------------------
30921  *       removable media hotpluggable pm-capable  |   power manage
30922  *     ------------------------------------------------------------
30923  *             false          false     false     |     No
30924  *             false          false     true      |     Yes
30925  *             false          true      false     |     No
30926  *             false          true      true      |     Yes
30927  *             true             x        x        |     Yes
30928  *     ------------------------------------------------------------
30929  *
30930  *      USB and firewire hard disks can now be power managed independently
30931  *      of the framebuffer
30932  *
30933  *
30934  * 15. Support for USB disks with capacity larger than 1TB
30935  *
30936  *     Currently, sd doesn't permit a fixed disk device with capacity
30937  *     larger than 1TB to be used in a 32-bit operating system environment.
30938  *     However, sd doesn't do that for removable media devices. Instead, it
30939  *     assumes that removable media devices cannot have a capacity larger
30940  *     than 1TB. Therefore, using those devices on 32-bit system is partially
30941  *     supported, which can cause some unexpected results.
30942  *
30943  *     ---------------------------------------------------------------------
30944  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
30945  *     ---------------------------------------------------------------------
30946  *             false          false  |   true         |     no
30947  *             false          true   |   true         |     no
30948  *             true           false  |   true         |     Yes
30949  *             true           true   |   true         |     Yes
30950  *     ---------------------------------------------------------------------
30951  *
30952  *
30953  * 16. Check write-protection at open time
30954  *
30955  *     When a removable media device is being opened for writing without NDELAY
30956  *     flag, sd will check if this device is writable. If attempting to open
30957  *     without NDELAY flag a write-protected device, this operation will abort.
30958  *
30959  *     ------------------------------------------------------------
30960  *       removable media    USB/1394   |   WP Check
30961  *     ------------------------------------------------------------
30962  *             false          false    |     No
30963  *             false          true     |     No
30964  *             true           false    |     Yes
30965  *             true           true     |     Yes
30966  *     ------------------------------------------------------------
30967  *
30968  *
30969  * 17. syslog when corrupted VTOC is encountered
30970  *
30971  *      Currently, if an invalid VTOC is encountered, sd only print syslog
30972  *      for fixed SCSI disks.
30973  *     ------------------------------------------------------------
30974  *       removable media    USB/1394   |   print syslog
30975  *     ------------------------------------------------------------
30976  *             false          false    |     Yes
30977  *             false          true     |     No
30978  *             true           false    |     No
30979  *             true           true     |     No
30980  *     ------------------------------------------------------------
30981  */
30982 static void
30983 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
30984 {
30985 	int	pm_cap;
30986 
30987 	ASSERT(un->un_sd);
30988 	ASSERT(un->un_sd->sd_inq);
30989 
30990 	/*
30991 	 * Enable SYNC CACHE support for all devices.
30992 	 */
30993 	un->un_f_sync_cache_supported = TRUE;
30994 
30995 	/*
30996 	 * Set the sync cache required flag to false.
30997 	 * This would ensure that there is no SYNC CACHE
30998 	 * sent when there are no writes
30999 	 */
31000 	un->un_f_sync_cache_required = FALSE;
31001 
31002 	if (un->un_sd->sd_inq->inq_rmb) {
31003 		/*
31004 		 * The media of this device is removable. And for this kind
31005 		 * of devices, it is possible to change medium after opening
31006 		 * devices. Thus we should support this operation.
31007 		 */
31008 		un->un_f_has_removable_media = TRUE;
31009 
31010 		/*
31011 		 * support non-512-byte blocksize of removable media devices
31012 		 */
31013 		un->un_f_non_devbsize_supported = TRUE;
31014 
31015 		/*
31016 		 * Assume that all removable media devices support DOOR_LOCK
31017 		 */
31018 		un->un_f_doorlock_supported = TRUE;
31019 
31020 		/*
31021 		 * For a removable media device, it is possible to be opened
31022 		 * with NDELAY flag when there is no media in drive, in this
31023 		 * case we don't care if device is writable. But if without
31024 		 * NDELAY flag, we need to check if media is write-protected.
31025 		 */
31026 		un->un_f_chk_wp_open = TRUE;
31027 
31028 		/*
31029 		 * need to start a SCSI watch thread to monitor media state,
31030 		 * when media is being inserted or ejected, notify syseventd.
31031 		 */
31032 		un->un_f_monitor_media_state = TRUE;
31033 
31034 		/*
31035 		 * Some devices don't support START_STOP_UNIT command.
31036 		 * Therefore, we'd better check if a device supports it
31037 		 * before sending it.
31038 		 */
31039 		un->un_f_check_start_stop = TRUE;
31040 
31041 		/*
31042 		 * support eject media ioctl:
31043 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
31044 		 */
31045 		un->un_f_eject_media_supported = TRUE;
31046 
31047 		/*
31048 		 * Because many removable-media devices don't support
31049 		 * LOG_SENSE, we couldn't use this command to check if
31050 		 * a removable media device support power-management.
31051 		 * We assume that they support power-management via
31052 		 * START_STOP_UNIT command and can be spun up and down
31053 		 * without limitations.
31054 		 */
31055 		un->un_f_pm_supported = TRUE;
31056 
31057 		/*
31058 		 * Need to create a zero length (Boolean) property
31059 		 * removable-media for the removable media devices.
31060 		 * Note that the return value of the property is not being
31061 		 * checked, since if unable to create the property
31062 		 * then do not want the attach to fail altogether. Consistent
31063 		 * with other property creation in attach.
31064 		 */
31065 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
31066 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
31067 
31068 	} else {
31069 		/*
31070 		 * create device ID for device
31071 		 */
31072 		un->un_f_devid_supported = TRUE;
31073 
31074 		/*
31075 		 * Spin up non-removable-media devices once it is attached
31076 		 */
31077 		un->un_f_attach_spinup = TRUE;
31078 
31079 		/*
31080 		 * According to SCSI specification, Sense data has two kinds of
31081 		 * format: fixed format, and descriptor format. At present, we
31082 		 * don't support descriptor format sense data for removable
31083 		 * media.
31084 		 */
31085 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
31086 			un->un_f_descr_format_supported = TRUE;
31087 		}
31088 
31089 		/*
31090 		 * kstats are created only for non-removable media devices.
31091 		 *
31092 		 * Set this in sd.conf to 0 in order to disable kstats.  The
31093 		 * default is 1, so they are enabled by default.
31094 		 */
31095 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
31096 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
31097 		    "enable-partition-kstats", 1));
31098 
31099 		/*
31100 		 * Check if HBA has set the "pm-capable" property.
31101 		 * If "pm-capable" exists and is non-zero then we can
31102 		 * power manage the device without checking the start/stop
31103 		 * cycle count log sense page.
31104 		 *
31105 		 * If "pm-capable" exists and is set to be false (0),
31106 		 * then we should not power manage the device.
31107 		 *
31108 		 * If "pm-capable" doesn't exist then pm_cap will
31109 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
31110 		 * sd will check the start/stop cycle count log sense page
31111 		 * and power manage the device if the cycle count limit has
31112 		 * not been exceeded.
31113 		 */
31114 		pm_cap = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
31115 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
31116 		if (SD_PM_CAPABLE_IS_UNDEFINED(pm_cap)) {
31117 			un->un_f_log_sense_supported = TRUE;
31118 			if (!un->un_f_power_condition_disabled &&
31119 			    SD_INQUIRY(un)->inq_ansi == 6) {
31120 				un->un_f_power_condition_supported = TRUE;
31121 			}
31122 		} else {
31123 			/*
31124 			 * pm-capable property exists.
31125 			 *
31126 			 * Convert "TRUE" values for pm_cap to
31127 			 * SD_PM_CAPABLE_IS_TRUE to make it easier to check
31128 			 * later. "TRUE" values are any values defined in
31129 			 * inquiry.h.
31130 			 */
31131 			if (SD_PM_CAPABLE_IS_FALSE(pm_cap)) {
31132 				un->un_f_log_sense_supported = FALSE;
31133 			} else {
31134 				/* SD_PM_CAPABLE_IS_TRUE case */
31135 				un->un_f_pm_supported = TRUE;
31136 				if (!un->un_f_power_condition_disabled &&
31137 				    SD_PM_CAPABLE_IS_SPC_4(pm_cap)) {
31138 					un->un_f_power_condition_supported =
31139 					    TRUE;
31140 				}
31141 				if (SD_PM_CAP_LOG_SUPPORTED(pm_cap)) {
31142 					un->un_f_log_sense_supported = TRUE;
31143 					un->un_f_pm_log_sense_smart =
31144 					    SD_PM_CAP_SMART_LOG(pm_cap);
31145 				}
31146 			}
31147 
31148 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
31149 			    "sd_unit_attach: un:0x%p pm-capable "
31150 			    "property set to %d.\n", un, un->un_f_pm_supported);
31151 		}
31152 	}
31153 
31154 	if (un->un_f_is_hotpluggable) {
31155 
31156 		/*
31157 		 * Have to watch hotpluggable devices as well, since
31158 		 * that's the only way for userland applications to
31159 		 * detect hot removal while device is busy/mounted.
31160 		 */
31161 		un->un_f_monitor_media_state = TRUE;
31162 
31163 		un->un_f_check_start_stop = TRUE;
31164 
31165 	}
31166 }
31167 
31168 /*
31169  * sd_tg_rdwr:
31170  * Provides rdwr access for cmlb via sd_tgops. The start_block is
31171  * in sys block size, req_length in bytes.
31172  *
31173  */
31174 static int
31175 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
31176     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
31177 {
31178 	struct sd_lun *un;
31179 	int path_flag = (int)(uintptr_t)tg_cookie;
31180 	char *dkl = NULL;
31181 	diskaddr_t real_addr = start_block;
31182 	diskaddr_t first_byte, end_block;
31183 
31184 	size_t	buffer_size = reqlength;
31185 	int rval = 0;
31186 	diskaddr_t	cap;
31187 	uint32_t	lbasize;
31188 	sd_ssc_t	*ssc;
31189 
31190 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31191 	if (un == NULL)
31192 		return (ENXIO);
31193 
31194 	if (cmd != TG_READ && cmd != TG_WRITE)
31195 		return (EINVAL);
31196 
31197 	ssc = sd_ssc_init(un);
31198 	mutex_enter(SD_MUTEX(un));
31199 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
31200 		mutex_exit(SD_MUTEX(un));
31201 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31202 		    &lbasize, path_flag);
31203 		if (rval != 0)
31204 			goto done1;
31205 		mutex_enter(SD_MUTEX(un));
31206 		sd_update_block_info(un, lbasize, cap);
31207 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
31208 			mutex_exit(SD_MUTEX(un));
31209 			rval = EIO;
31210 			goto done;
31211 		}
31212 	}
31213 
31214 	if (NOT_DEVBSIZE(un)) {
31215 		/*
31216 		 * sys_blocksize != tgt_blocksize, need to re-adjust
31217 		 * blkno and save the index to beginning of dk_label
31218 		 */
31219 		first_byte  = SD_SYSBLOCKS2BYTES(start_block);
31220 		real_addr = first_byte / un->un_tgt_blocksize;
31221 
31222 		end_block = (first_byte + reqlength +
31223 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
31224 
31225 		/* round up buffer size to multiple of target block size */
31226 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
31227 
31228 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
31229 		    "label_addr: 0x%x allocation size: 0x%x\n",
31230 		    real_addr, buffer_size);
31231 
31232 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
31233 		    (reqlength % un->un_tgt_blocksize) != 0)
31234 			/* the request is not aligned */
31235 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
31236 	}
31237 
31238 	/*
31239 	 * The MMC standard allows READ CAPACITY to be
31240 	 * inaccurate by a bounded amount (in the interest of
31241 	 * response latency).  As a result, failed READs are
31242 	 * commonplace (due to the reading of metadata and not
31243 	 * data). Depending on the per-Vendor/drive Sense data,
31244 	 * the failed READ can cause many (unnecessary) retries.
31245 	 */
31246 
31247 	if (ISCD(un) && (cmd == TG_READ) &&
31248 	    (un->un_f_blockcount_is_valid == TRUE) &&
31249 	    ((start_block == (un->un_blockcount - 1)) ||
31250 	    (start_block == (un->un_blockcount - 2)))) {
31251 			path_flag = SD_PATH_DIRECT_PRIORITY;
31252 	}
31253 
31254 	mutex_exit(SD_MUTEX(un));
31255 	if (cmd == TG_READ) {
31256 		rval = sd_send_scsi_READ(ssc, (dkl != NULL) ? dkl : bufaddr,
31257 		    buffer_size, real_addr, path_flag);
31258 		if (dkl != NULL)
31259 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
31260 			    real_addr), bufaddr, reqlength);
31261 	} else {
31262 		if (dkl) {
31263 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
31264 			    real_addr, path_flag);
31265 			if (rval) {
31266 				goto done1;
31267 			}
31268 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
31269 			    real_addr), reqlength);
31270 		}
31271 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL) ? dkl : bufaddr,
31272 		    buffer_size, real_addr, path_flag);
31273 	}
31274 
31275 done1:
31276 	if (dkl != NULL)
31277 		kmem_free(dkl, buffer_size);
31278 
31279 	if (rval != 0) {
31280 		if (rval == EIO)
31281 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
31282 		else
31283 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31284 	}
31285 done:
31286 	sd_ssc_fini(ssc);
31287 	return (rval);
31288 }
31289 
31290 
31291 static int
31292 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
31293 {
31294 
31295 	struct sd_lun *un;
31296 	diskaddr_t	cap;
31297 	uint32_t	lbasize;
31298 	int		path_flag = (int)(uintptr_t)tg_cookie;
31299 	int		ret = 0;
31300 
31301 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31302 	if (un == NULL)
31303 		return (ENXIO);
31304 
31305 	switch (cmd) {
31306 	case TG_GETPHYGEOM:
31307 	case TG_GETVIRTGEOM:
31308 	case TG_GETCAPACITY:
31309 	case TG_GETBLOCKSIZE:
31310 		mutex_enter(SD_MUTEX(un));
31311 
31312 		if ((un->un_f_blockcount_is_valid == TRUE) &&
31313 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
31314 			cap = un->un_blockcount;
31315 			lbasize = un->un_tgt_blocksize;
31316 			mutex_exit(SD_MUTEX(un));
31317 		} else {
31318 			sd_ssc_t	*ssc;
31319 			mutex_exit(SD_MUTEX(un));
31320 			ssc = sd_ssc_init(un);
31321 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31322 			    &lbasize, path_flag);
31323 			if (ret != 0) {
31324 				if (ret == EIO)
31325 					sd_ssc_assessment(ssc,
31326 					    SD_FMT_STATUS_CHECK);
31327 				else
31328 					sd_ssc_assessment(ssc,
31329 					    SD_FMT_IGNORE);
31330 				sd_ssc_fini(ssc);
31331 				return (ret);
31332 			}
31333 			sd_ssc_fini(ssc);
31334 			mutex_enter(SD_MUTEX(un));
31335 			sd_update_block_info(un, lbasize, cap);
31336 			if ((un->un_f_blockcount_is_valid == FALSE) ||
31337 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
31338 				mutex_exit(SD_MUTEX(un));
31339 				return (EIO);
31340 			}
31341 			mutex_exit(SD_MUTEX(un));
31342 		}
31343 
31344 		if (cmd == TG_GETCAPACITY) {
31345 			*(diskaddr_t *)arg = cap;
31346 			return (0);
31347 		}
31348 
31349 		if (cmd == TG_GETBLOCKSIZE) {
31350 			*(uint32_t *)arg = lbasize;
31351 			return (0);
31352 		}
31353 
31354 		if (cmd == TG_GETPHYGEOM)
31355 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
31356 			    cap, lbasize, path_flag);
31357 		else
31358 			/* TG_GETVIRTGEOM */
31359 			ret = sd_get_virtual_geometry(un,
31360 			    (cmlb_geom_t *)arg, cap, lbasize);
31361 
31362 		return (ret);
31363 
31364 	case TG_GETATTR:
31365 		mutex_enter(SD_MUTEX(un));
31366 		((tg_attribute_t *)arg)->media_is_writable =
31367 		    un->un_f_mmc_writable_media;
31368 		((tg_attribute_t *)arg)->media_is_solid_state =
31369 		    un->un_f_is_solid_state;
31370 		((tg_attribute_t *)arg)->media_is_rotational =
31371 		    un->un_f_is_rotational;
31372 		mutex_exit(SD_MUTEX(un));
31373 		return (0);
31374 	default:
31375 		return (ENOTTY);
31376 
31377 	}
31378 }
31379 
31380 /*
31381  *    Function: sd_ssc_ereport_post
31382  *
31383  * Description: Will be called when SD driver need to post an ereport.
31384  *
31385  *    Context: Kernel thread or interrupt context.
31386  */
31387 
31388 #define	DEVID_IF_KNOWN(d) "devid", DATA_TYPE_STRING, (d) ? (d) : "unknown"
31389 
31390 static void
31391 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
31392 {
31393 	int uscsi_path_instance = 0;
31394 	uchar_t	uscsi_pkt_reason;
31395 	uint32_t uscsi_pkt_state;
31396 	uint32_t uscsi_pkt_statistics;
31397 	uint64_t uscsi_ena;
31398 	uchar_t op_code;
31399 	uint8_t *sensep;
31400 	union scsi_cdb *cdbp;
31401 	uint_t cdblen = 0;
31402 	uint_t senlen = 0;
31403 	struct sd_lun *un;
31404 	dev_info_t *dip;
31405 	char *devid;
31406 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
31407 	    SSC_FLAGS_INVALID_STATUS |
31408 	    SSC_FLAGS_INVALID_SENSE |
31409 	    SSC_FLAGS_INVALID_DATA;
31410 	char assessment[16];
31411 
31412 	ASSERT(ssc != NULL);
31413 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
31414 	ASSERT(ssc->ssc_uscsi_info != NULL);
31415 
31416 	un = ssc->ssc_un;
31417 	ASSERT(un != NULL);
31418 
31419 	dip = un->un_sd->sd_dev;
31420 
31421 	/*
31422 	 * Get the devid:
31423 	 *	devid will only be passed to non-transport error reports.
31424 	 */
31425 	devid = DEVI(dip)->devi_devid_str;
31426 
31427 	/*
31428 	 * If we are syncing or dumping, the command will not be executed
31429 	 * so we bypass this situation.
31430 	 */
31431 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
31432 	    (un->un_state == SD_STATE_DUMPING))
31433 		return;
31434 
31435 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
31436 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
31437 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
31438 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
31439 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
31440 
31441 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
31442 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
31443 
31444 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
31445 	if (cdbp == NULL) {
31446 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
31447 		    "sd_ssc_ereport_post meet empty cdb\n");
31448 		return;
31449 	}
31450 
31451 	op_code = cdbp->scc_cmd;
31452 
31453 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
31454 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
31455 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
31456 
31457 	if (senlen > 0)
31458 		ASSERT(sensep != NULL);
31459 
31460 	/*
31461 	 * Initialize drv_assess to corresponding values.
31462 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
31463 	 * on the sense-key returned back.
31464 	 */
31465 	switch (drv_assess) {
31466 		case SD_FM_DRV_RECOVERY:
31467 			(void) sprintf(assessment, "%s", "recovered");
31468 			break;
31469 		case SD_FM_DRV_RETRY:
31470 			(void) sprintf(assessment, "%s", "retry");
31471 			break;
31472 		case SD_FM_DRV_NOTICE:
31473 			(void) sprintf(assessment, "%s", "info");
31474 			break;
31475 		case SD_FM_DRV_FATAL:
31476 		default:
31477 			(void) sprintf(assessment, "%s", "unknown");
31478 	}
31479 	/*
31480 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
31481 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
31482 	 * driver-assessment will always be "recovered" here.
31483 	 */
31484 	if (drv_assess == SD_FM_DRV_RECOVERY) {
31485 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31486 		    "cmd.disk.recovered", uscsi_ena, devid, NULL,
31487 		    DDI_NOSLEEP, NULL,
31488 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31489 		    DEVID_IF_KNOWN(devid),
31490 		    "driver-assessment", DATA_TYPE_STRING, assessment,
31491 		    "op-code", DATA_TYPE_UINT8, op_code,
31492 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31493 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31494 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31495 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31496 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31497 		    NULL);
31498 		return;
31499 	}
31500 
31501 	/*
31502 	 * If there is un-expected/un-decodable data, we should post
31503 	 * ereport.io.scsi.cmd.disk.dev.uderr.
31504 	 * driver-assessment will be set based on parameter drv_assess.
31505 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
31506 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
31507 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
31508 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
31509 	 */
31510 	if (ssc->ssc_flags & ssc_invalid_flags) {
31511 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
31512 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31513 			    NULL, "cmd.disk.dev.uderr", uscsi_ena, devid,
31514 			    NULL, DDI_NOSLEEP, NULL,
31515 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31516 			    DEVID_IF_KNOWN(devid),
31517 			    "driver-assessment", DATA_TYPE_STRING,
31518 			    drv_assess == SD_FM_DRV_FATAL ?
31519 			    "fail" : assessment,
31520 			    "op-code", DATA_TYPE_UINT8, op_code,
31521 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31522 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31523 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31524 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31525 			    "pkt-stats", DATA_TYPE_UINT32,
31526 			    uscsi_pkt_statistics,
31527 			    "stat-code", DATA_TYPE_UINT8,
31528 			    ssc->ssc_uscsi_cmd->uscsi_status,
31529 			    "un-decode-info", DATA_TYPE_STRING,
31530 			    ssc->ssc_info,
31531 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31532 			    senlen, sensep,
31533 			    NULL);
31534 		} else {
31535 			/*
31536 			 * For other type of invalid data, the
31537 			 * un-decode-value field would be empty because the
31538 			 * un-decodable content could be seen from upper
31539 			 * level payload or inside un-decode-info.
31540 			 */
31541 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31542 			    NULL,
31543 			    "cmd.disk.dev.uderr", uscsi_ena, devid,
31544 			    NULL, DDI_NOSLEEP, NULL,
31545 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31546 			    DEVID_IF_KNOWN(devid),
31547 			    "driver-assessment", DATA_TYPE_STRING,
31548 			    drv_assess == SD_FM_DRV_FATAL ?
31549 			    "fail" : assessment,
31550 			    "op-code", DATA_TYPE_UINT8, op_code,
31551 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31552 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31553 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31554 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31555 			    "pkt-stats", DATA_TYPE_UINT32,
31556 			    uscsi_pkt_statistics,
31557 			    "stat-code", DATA_TYPE_UINT8,
31558 			    ssc->ssc_uscsi_cmd->uscsi_status,
31559 			    "un-decode-info", DATA_TYPE_STRING,
31560 			    ssc->ssc_info,
31561 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31562 			    0, NULL,
31563 			    NULL);
31564 		}
31565 		ssc->ssc_flags &= ~ssc_invalid_flags;
31566 		return;
31567 	}
31568 
31569 	if (uscsi_pkt_reason != CMD_CMPLT ||
31570 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
31571 		/*
31572 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
31573 		 * set inside sd_start_cmds due to errors(bad packet or
31574 		 * fatal transport error), we should take it as a
31575 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
31576 		 * driver-assessment will be set based on drv_assess.
31577 		 * We will set devid to NULL because it is a transport
31578 		 * error.
31579 		 */
31580 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
31581 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
31582 
31583 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31584 		    "cmd.disk.tran", uscsi_ena, NULL, NULL, DDI_NOSLEEP, NULL,
31585 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31586 		    DEVID_IF_KNOWN(devid),
31587 		    "driver-assessment", DATA_TYPE_STRING,
31588 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31589 		    "op-code", DATA_TYPE_UINT8, op_code,
31590 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31591 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31592 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31593 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
31594 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31595 		    NULL);
31596 	} else {
31597 		/*
31598 		 * If we got here, we have a completed command, and we need
31599 		 * to further investigate the sense data to see what kind
31600 		 * of ereport we should post.
31601 		 * No ereport is needed if sense-key is KEY_RECOVERABLE_ERROR
31602 		 * and asc/ascq is "ATA PASS-THROUGH INFORMATION AVAILABLE".
31603 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr if sense-key is
31604 		 * KEY_MEDIUM_ERROR.
31605 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
31606 		 * driver-assessment will be set based on the parameter
31607 		 * drv_assess.
31608 		 */
31609 		if (senlen > 0) {
31610 			/*
31611 			 * Here we have sense data available.
31612 			 */
31613 			uint8_t sense_key = scsi_sense_key(sensep);
31614 			uint8_t sense_asc = scsi_sense_asc(sensep);
31615 			uint8_t sense_ascq = scsi_sense_ascq(sensep);
31616 
31617 			if (sense_key == KEY_RECOVERABLE_ERROR &&
31618 			    sense_asc == 0x00 && sense_ascq == 0x1d)
31619 				return;
31620 
31621 			if (sense_key == KEY_MEDIUM_ERROR) {
31622 				/*
31623 				 * driver-assessment should be "fatal" if
31624 				 * drv_assess is SD_FM_DRV_FATAL.
31625 				 */
31626 				scsi_fm_ereport_post(un->un_sd,
31627 				    uscsi_path_instance, NULL,
31628 				    "cmd.disk.dev.rqs.merr",
31629 				    uscsi_ena, devid, NULL, DDI_NOSLEEP, NULL,
31630 				    FM_VERSION, DATA_TYPE_UINT8,
31631 				    FM_EREPORT_VERS0,
31632 				    DEVID_IF_KNOWN(devid),
31633 				    "driver-assessment",
31634 				    DATA_TYPE_STRING,
31635 				    drv_assess == SD_FM_DRV_FATAL ?
31636 				    "fatal" : assessment,
31637 				    "op-code",
31638 				    DATA_TYPE_UINT8, op_code,
31639 				    "cdb",
31640 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31641 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31642 				    "pkt-reason",
31643 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31644 				    "pkt-state",
31645 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31646 				    "pkt-stats",
31647 				    DATA_TYPE_UINT32,
31648 				    uscsi_pkt_statistics,
31649 				    "stat-code",
31650 				    DATA_TYPE_UINT8,
31651 				    ssc->ssc_uscsi_cmd->uscsi_status,
31652 				    "key",
31653 				    DATA_TYPE_UINT8,
31654 				    scsi_sense_key(sensep),
31655 				    "asc",
31656 				    DATA_TYPE_UINT8,
31657 				    scsi_sense_asc(sensep),
31658 				    "ascq",
31659 				    DATA_TYPE_UINT8,
31660 				    scsi_sense_ascq(sensep),
31661 				    "sense-data",
31662 				    DATA_TYPE_UINT8_ARRAY,
31663 				    senlen, sensep,
31664 				    "lba",
31665 				    DATA_TYPE_UINT64,
31666 				    ssc->ssc_uscsi_info->ui_lba,
31667 				    NULL);
31668 			} else {
31669 				/*
31670 				 * if sense-key == 0x4(hardware
31671 				 * error), driver-assessment should
31672 				 * be "fatal" if drv_assess is
31673 				 * SD_FM_DRV_FATAL.
31674 				 */
31675 				scsi_fm_ereport_post(un->un_sd,
31676 				    uscsi_path_instance, NULL,
31677 				    "cmd.disk.dev.rqs.derr",
31678 				    uscsi_ena, devid,
31679 				    NULL, DDI_NOSLEEP, NULL,
31680 				    FM_VERSION,
31681 				    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31682 				    DEVID_IF_KNOWN(devid),
31683 				    "driver-assessment",
31684 				    DATA_TYPE_STRING,
31685 				    drv_assess == SD_FM_DRV_FATAL ?
31686 				    (sense_key == 0x4 ?
31687 				    "fatal" : "fail") : assessment,
31688 				    "op-code",
31689 				    DATA_TYPE_UINT8, op_code,
31690 				    "cdb",
31691 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31692 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31693 				    "pkt-reason",
31694 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31695 				    "pkt-state",
31696 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31697 				    "pkt-stats",
31698 				    DATA_TYPE_UINT32,
31699 				    uscsi_pkt_statistics,
31700 				    "stat-code",
31701 				    DATA_TYPE_UINT8,
31702 				    ssc->ssc_uscsi_cmd->uscsi_status,
31703 				    "key",
31704 				    DATA_TYPE_UINT8,
31705 				    scsi_sense_key(sensep),
31706 				    "asc",
31707 				    DATA_TYPE_UINT8,
31708 				    scsi_sense_asc(sensep),
31709 				    "ascq",
31710 				    DATA_TYPE_UINT8,
31711 				    scsi_sense_ascq(sensep),
31712 				    "sense-data",
31713 				    DATA_TYPE_UINT8_ARRAY,
31714 				    senlen, sensep,
31715 				    NULL);
31716 			}
31717 		} else {
31718 			/*
31719 			 * For stat_code == STATUS_GOOD, this is not a
31720 			 * hardware error.
31721 			 */
31722 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
31723 				return;
31724 
31725 			/*
31726 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
31727 			 * stat-code but with sense data unavailable.
31728 			 * driver-assessment will be set based on parameter
31729 			 * drv_assess.
31730 			 */
31731 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31732 			    NULL,
31733 			    "cmd.disk.dev.serr", uscsi_ena,
31734 			    devid, NULL, DDI_NOSLEEP, NULL,
31735 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31736 			    DEVID_IF_KNOWN(devid),
31737 			    "driver-assessment", DATA_TYPE_STRING,
31738 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31739 			    "op-code", DATA_TYPE_UINT8, op_code,
31740 			    "cdb",
31741 			    DATA_TYPE_UINT8_ARRAY,
31742 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31743 			    "pkt-reason",
31744 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
31745 			    "pkt-state",
31746 			    DATA_TYPE_UINT8, uscsi_pkt_state,
31747 			    "pkt-stats",
31748 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
31749 			    "stat-code",
31750 			    DATA_TYPE_UINT8,
31751 			    ssc->ssc_uscsi_cmd->uscsi_status,
31752 			    NULL);
31753 		}
31754 	}
31755 }
31756 
31757 /*
31758  *     Function: sd_ssc_extract_info
31759  *
31760  * Description: Extract information available to help generate ereport.
31761  *
31762  *     Context: Kernel thread or interrupt context.
31763  */
31764 static void
31765 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
31766     struct buf *bp, struct sd_xbuf *xp)
31767 {
31768 	size_t senlen = 0;
31769 	union scsi_cdb *cdbp;
31770 	int path_instance;
31771 	/*
31772 	 * Need scsi_cdb_size array to determine the cdb length.
31773 	 */
31774 	extern uchar_t	scsi_cdb_size[];
31775 
31776 	ASSERT(un != NULL);
31777 	ASSERT(pktp != NULL);
31778 	ASSERT(bp != NULL);
31779 	ASSERT(xp != NULL);
31780 	ASSERT(ssc != NULL);
31781 	ASSERT(mutex_owned(SD_MUTEX(un)));
31782 
31783 	/*
31784 	 * Transfer the cdb buffer pointer here.
31785 	 */
31786 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
31787 
31788 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
31789 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
31790 
31791 	/*
31792 	 * Transfer the sense data buffer pointer if sense data is available,
31793 	 * calculate the sense data length first.
31794 	 */
31795 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
31796 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
31797 		/*
31798 		 * For arq case, we will enter here.
31799 		 */
31800 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
31801 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
31802 		} else {
31803 			senlen = SENSE_LENGTH;
31804 		}
31805 	} else {
31806 		/*
31807 		 * For non-arq case, we will enter this branch.
31808 		 */
31809 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
31810 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
31811 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
31812 		}
31813 
31814 	}
31815 
31816 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
31817 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
31818 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
31819 
31820 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
31821 
31822 	/*
31823 	 * Only transfer path_instance when scsi_pkt was properly allocated.
31824 	 */
31825 	path_instance = pktp->pkt_path_instance;
31826 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
31827 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
31828 	else
31829 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
31830 
31831 	/*
31832 	 * Copy in the other fields we may need when posting ereport.
31833 	 */
31834 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
31835 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
31836 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
31837 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
31838 
31839 	/*
31840 	 * For partially read/write command, we will not create ena
31841 	 * in case of a successful command be reconized as recovered.
31842 	 */
31843 	if ((pktp->pkt_reason == CMD_CMPLT) &&
31844 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
31845 	    (senlen == 0)) {
31846 		return;
31847 	}
31848 
31849 	/*
31850 	 * To associate ereports of a single command execution flow, we
31851 	 * need a shared ena for a specific command.
31852 	 */
31853 	if (xp->xb_ena == 0)
31854 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
31855 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
31856 }
31857 
31858 
31859 /*
31860  *     Function: sd_check_bdc_vpd
31861  *
31862  * Description: Query the optional INQUIRY VPD page 0xb1. If the device
31863  *              supports VPD page 0xb1, sd examines the MEDIUM ROTATION
31864  *              RATE.
31865  *
31866  *		Set the following based on RPM value:
31867  *		= 0	device is not solid state, non-rotational
31868  *		= 1	device is solid state, non-rotational
31869  *		> 1	device is not solid state, rotational
31870  *
31871  *     Context: Kernel thread or interrupt context.
31872  */
31873 
31874 static void
31875 sd_check_bdc_vpd(sd_ssc_t *ssc)
31876 {
31877 	int		rval		= 0;
31878 	uchar_t		*inqb1		= NULL;
31879 	size_t		inqb1_len	= MAX_INQUIRY_SIZE;
31880 	size_t		inqb1_resid	= 0;
31881 	struct sd_lun	*un;
31882 
31883 	ASSERT(ssc != NULL);
31884 	un = ssc->ssc_un;
31885 	ASSERT(un != NULL);
31886 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31887 
31888 	mutex_enter(SD_MUTEX(un));
31889 	un->un_f_is_rotational = TRUE;
31890 	un->un_f_is_solid_state = FALSE;
31891 
31892 	if (ISCD(un)) {
31893 		mutex_exit(SD_MUTEX(un));
31894 		return;
31895 	}
31896 
31897 	if (sd_check_vpd_page_support(ssc) == 0 &&
31898 	    un->un_vpd_page_mask & SD_VPD_DEV_CHARACTER_PG) {
31899 		mutex_exit(SD_MUTEX(un));
31900 		/* collect page b1 data */
31901 		inqb1 = kmem_zalloc(inqb1_len, KM_SLEEP);
31902 
31903 		rval = sd_send_scsi_INQUIRY(ssc, inqb1, inqb1_len,
31904 		    0x01, 0xB1, &inqb1_resid);
31905 
31906 		if (rval == 0 && (inqb1_len - inqb1_resid > 5)) {
31907 			SD_TRACE(SD_LOG_COMMON, un,
31908 			    "sd_check_bdc_vpd: \
31909 			    successfully get VPD page: %x \
31910 			    PAGE LENGTH: %x BYTE 4: %x \
31911 			    BYTE 5: %x", inqb1[1], inqb1[3], inqb1[4],
31912 			    inqb1[5]);
31913 
31914 			mutex_enter(SD_MUTEX(un));
31915 			/*
31916 			 * Check the MEDIUM ROTATION RATE.
31917 			 */
31918 			if (inqb1[4] == 0) {
31919 				if (inqb1[5] == 0) {
31920 					un->un_f_is_rotational = FALSE;
31921 				} else if (inqb1[5] == 1) {
31922 					un->un_f_is_rotational = FALSE;
31923 					un->un_f_is_solid_state = TRUE;
31924 					/*
31925 					 * Solid state drives don't need
31926 					 * disksort.
31927 					 */
31928 					un->un_f_disksort_disabled = TRUE;
31929 				}
31930 			}
31931 			mutex_exit(SD_MUTEX(un));
31932 		} else if (rval != 0) {
31933 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31934 		}
31935 
31936 		kmem_free(inqb1, inqb1_len);
31937 	} else {
31938 		mutex_exit(SD_MUTEX(un));
31939 	}
31940 }
31941 
31942 /*
31943  *	Function: sd_check_emulation_mode
31944  *
31945  *   Description: Check whether the SSD is at emulation mode
31946  *		  by issuing READ_CAPACITY_16 to see whether
31947  *		  we can get physical block size of the drive.
31948  *
31949  *	 Context: Kernel thread or interrupt context.
31950  */
31951 
31952 static void
31953 sd_check_emulation_mode(sd_ssc_t *ssc)
31954 {
31955 	int		rval = 0;
31956 	uint64_t	capacity;
31957 	uint_t		lbasize;
31958 	uint_t		pbsize;
31959 	int		i;
31960 	int		devid_len;
31961 	struct sd_lun	*un;
31962 
31963 	ASSERT(ssc != NULL);
31964 	un = ssc->ssc_un;
31965 	ASSERT(un != NULL);
31966 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31967 
31968 	mutex_enter(SD_MUTEX(un));
31969 	if (ISCD(un)) {
31970 		mutex_exit(SD_MUTEX(un));
31971 		return;
31972 	}
31973 
31974 	if (un->un_f_descr_format_supported) {
31975 		mutex_exit(SD_MUTEX(un));
31976 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
31977 		    &pbsize, SD_PATH_DIRECT);
31978 		mutex_enter(SD_MUTEX(un));
31979 
31980 		if (rval != 0) {
31981 			un->un_phy_blocksize = DEV_BSIZE;
31982 		} else {
31983 			if (!ISP2(pbsize % DEV_BSIZE) || pbsize == 0) {
31984 				un->un_phy_blocksize = DEV_BSIZE;
31985 			} else if (pbsize > un->un_phy_blocksize) {
31986 				/*
31987 				 * Don't reset the physical blocksize
31988 				 * unless we've detected a larger value.
31989 				 */
31990 				un->un_phy_blocksize = pbsize;
31991 			}
31992 		}
31993 	}
31994 
31995 	for (i = 0; i < sd_flash_dev_table_size; i++) {
31996 		devid_len = (int)strlen(sd_flash_dev_table[i]);
31997 		if (sd_sdconf_id_match(un, sd_flash_dev_table[i], devid_len)
31998 		    == SD_SUCCESS) {
31999 			un->un_phy_blocksize = SSD_SECSIZE;
32000 			if (un->un_f_is_solid_state &&
32001 			    un->un_phy_blocksize != un->un_tgt_blocksize)
32002 				un->un_f_enable_rmw = TRUE;
32003 		}
32004 	}
32005 
32006 	mutex_exit(SD_MUTEX(un));
32007 }
32008